carlos / platform Public

rootfs apps plan 3: invariant guards INV-1, 2, 4, 5 and the binary goldens (INV-6)

Task 1. The copy deck already holds the RFS-3 rows (bare file cells,
C13 struck); this adds the guards every later Plan 3 task keeps green:

- TestRootfsFilesNameNoBinaryVerb (INV-1): a typed (go/packages) scan of
  the non-test rootfs*.go and backend_rootfs.go refusing the binary
  Control/GenControl/cmdExeStarter verbs (by receiver type or the verb's
  signature), KillHost, EmptyHost, hostKiller, hostEmptier, childEnv,
  openHostCleanup and cgroup.Manager.OpenCleanup; fixtures overlaid into
  the package prove each refusal and a clean file.
- TestEveryRootfsProofNamesTheRootfsUnit (INV-1 behaviour): the web
  generation's unitProc and the rootfs cmdUnit, production-wired over a
  cgroup fixture with no binary unit, stop and poll their rootfs unit and
  stay unproven while its group is populated.
- TestRootfsRemovalOwnersUnchanged (INV-2), TestRootfsRefusalsAreNotBuild
  Failures (INV-4), TestRootfsLaunchFilesCarryOnlyComposedEnv (INV-5, web
  row), and a floor so the tables only grow.
- binary_golden_test.go (INV-6): StartCmd's launch.cmd.json and root
  call, StartStaged nested and flat, the 30 s health bound in genHealthy
  and verdictFloorGate, KillHost/EmptyHost, HasSidecar, byte-compared
  with testdata/binary_golden.
- plan3_groups_test.go: the A/R/W copy sets against the deck and the
  built list, and the release/worker machinery inventory of
  internal/activator with its a912a342 baseline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 057ee3a33e25ae6a940c157d42313248b43c18c7 parent 148f64f
25 files changed, +1,716 −0
  • internal/activator/binary_golden_test.go +399 −0
  • internal/activator/rootfs_invariants_test.go +699 −0
  • internal/activator/testdata/binary_golden/gen_healthy_bound.txt +4 −0
  • internal/activator/testdata/binary_golden/has_sidecar.txt +4 −0
  • internal/activator/testdata/binary_golden/kill_host.txt +9 −0
  • internal/activator/testdata/binary_golden/start_cmd_live.calls +3 −0
  • internal/activator/testdata/binary_golden/start_cmd_live.launch.cmd.json +20 −0
  • internal/activator/testdata/binary_golden/start_cmd_serving.calls +3 −0
  • internal/activator/testdata/binary_golden/start_cmd_serving.launch.cmd.json +20 −0
  • internal/activator/testdata/binary_golden/start_staged_flat.argv +5 −0
  • internal/activator/testdata/binary_golden/start_staged_flat.gen.json +13 −0
  • internal/activator/testdata/binary_golden/start_staged_nested.calls +3 −0
  • internal/activator/testdata/binary_golden/start_staged_nested.gen.json +13 −0
  • internal/activator/testdata/rootfs_removal_owners/added.go +18 −0
  • internal/activator/testdata/rootfs_removal_owners/missing.go +13 −0
  • internal/activator/testdata/rootfs_removal_owners/shrunk.go +16 −0
  • internal/activator/testdata/rootfs_verb_guard/alias.go +24 −0
  • internal/activator/testdata/rootfs_verb_guard/childenv.go +14 −0
  • internal/activator/testdata/rootfs_verb_guard/clean.go +32 −0
  • internal/activator/testdata/rootfs_verb_guard/direct.go +13 −0
  • internal/activator/testdata/rootfs_verb_guard/killhost.go +13 −0
  • internal/activator/testdata/rootfs_verb_guard/methodvalue.go +22 −0
  • internal/activator/testdata/rootfs_verb_guard/others.go +33 −0
  • plan3_groups_test.go +303 −0
  • testdata/plan3_inventory/added.go +20 −0
diff --git a/internal/activator/binary_golden_test.go b/internal/activator/binary_golden_test.go
new file mode 100644
index 000000000..393a323b4
--- /dev/null
+++ b/internal/activator/binary_golden_test.go
@@ -0,0 +1,399 @@
+package activator
+
+// INV-6: binary rows unchanged (rootfs apps Plan 3, "Invariants"). Each
+// test here records what a binary row's start, health bound, host kill or
+// sidecar answer is today and compares it byte for byte with a file under
+// testdata/binary_golden, written once from main at Plan 3 Task 1. Plan 3
+// adds rootfs arms beside these paths (N1); a binary row must not notice.
+// A change to a golden file needs its own reason in review.
+//
+// A missing or differing golden fails. CARLOS_WRITE_BINARY_GOLDEN=1 writes
+// the files instead (Task 1 only, or a reviewed binary change).
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const binaryGoldenDir = "testdata/binary_golden"
+
+// writeBinaryGolden is read once, before any test here clears the
+// environment (goldenEnv).
+var writeBinaryGolden = os.Getenv("CARLOS_WRITE_BINARY_GOLDEN") == "1"
+
+// checkBinaryGolden compares got with testdata/binary_golden/name.
+func checkBinaryGolden(t *testing.T, name string, got []byte) {
+ t.Helper()
+ path := filepath.Join(binaryGoldenDir, name)
+ if writeBinaryGolden {
+ if err := os.MkdirAll(binaryGoldenDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, got, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ want, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("golden %s: %v", path, err)
+ }
+ if string(got) != string(want) {
+ t.Errorf("a binary row changed (INV-6): %s differs\n--- got\n%s\n--- want\n%s", path, got, want)
+ }
+}
+
+// goldenPaths replaces the test's temporary roots with stable names, the
+// longest first.
+func goldenPaths(b []byte, roots map[string]string) []byte {
+ keys := make([]string, 0, len(roots))
+ for k := range roots {
+ keys = append(keys, k)
+ }
+ sort.Slice(keys, func(i, j int) bool { return len(keys[i]) > len(keys[j]) })
+ s := string(b)
+ for _, k := range keys {
+ s = strings.ReplaceAll(s, k, roots[k])
+ }
+ return []byte(s)
+}
+
+// nestedRoots is nestedBackend's temporary roots: the opt dir and the root
+// holding data and run.
+func nestedRoots(b *ExecBackend) map[string]string {
+ return map[string]string{b.OptDir: "$OPT", filepath.Dir(b.DataDir): "$ROOT"}
+}
+
+// goldenEnv gives the agent a fixed environment for the rest of t, so a
+// launch that inherits it (childEnv) is the same on every machine: the
+// whole environment is cleared and these set, and restored after. With
+// TMPDIR cleared, call it after t's temporary directories are made.
+func goldenEnv(t *testing.T) {
+ t.Helper()
+ t.Setenv("PATH", "/agent/bin") // and t may not run in parallel
+ saved := os.Environ()
+ t.Cleanup(func() {
+ os.Clearenv()
+ for _, kv := range saved {
+ if k, v, ok := strings.Cut(kv, "="); ok {
+ os.Setenv(k, v)
+ }
+ }
+ })
+ os.Clearenv()
+ for _, kv := range [][2]string{{"PATH", "/agent/bin"}, {"HOME", "/agent"}, {"LANG", "C.UTF-8"}, {"CARLOS_AGENT_ONLY", "stripped"}} {
+ os.Setenv(kv[0], kv[1])
+ }
+}
+
+// goldenControl is fakeControl with the binary verbs that name a build or
+// a limit recorded in full: Cmd, CmdExe, StartGenExe and StopGen.
+type goldenControl struct {
+ fakeGenControl
+ mu sync.Mutex
+ verbs []string
+}
+
+func newGoldenControl(ctl *fakeControl) *goldenControl {
+ return &goldenControl{fakeGenControl: fakeGenControl{ctl}}
+}
+
+func (g *goldenControl) note(s string) {
+ g.mu.Lock()
+ g.verbs = append(g.verbs, s)
+ g.mu.Unlock()
+}
+
+// record is the verbs recorded in full, then every call fakeControl itself
+// recorded, so a call this file does not expect shows too.
+func (g *goldenControl) record() string {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return strings.Join(g.verbs, "\n") + "\n--- fakeControl\n" + strings.Join(g.callList(), "\n") + "\n"
+}
+
+func (g *goldenControl) Cmd(ctx context.Context, host string, max int64) (string, error) {
+ g.note(fmt.Sprintf("Cmd host=%s memory_max=%d", host, max))
+ return g.fakeControl.Cmd(ctx, host, max)
+}
+
+func (g *goldenControl) CmdExe(_ context.Context, host string, max int64, x instancectl.StagedExe) (string, error) {
+ g.note(fmt.Sprintf("CmdExe host=%s memory_max=%d exe=%+v", host, max, x))
+ return g.cmdInv, g.cmdErr
+}
+
+func (g *goldenControl) StartGenExe(ctx context.Context, host string, n uint64, max int64, x instancectl.StagedExe) (string, error) {
+ g.note(fmt.Sprintf("StartGenExe host=%s gen=%d memory_max=%d exe=%+v", host, n, max, x))
+ return g.fakeGenControl.StartGenExe(ctx, host, n, max, x)
+}
+
+func (g *goldenControl) StopGen(ctx context.Context, host string, n uint64, kill bool) error {
+ g.note(fmt.Sprintf("StopGen host=%s gen=%d kill=%v", host, n, kill))
+ return g.fakeGenControl.StopGen(ctx, host, n, kill)
+}
+
+// A binary nested row's StartCmd (cmdunit.go): launch.cmd.json's bytes and
+// the cmd start root is asked for, on the live link (Control.Cmd) and on
+// the serving generation's build (CmdExe).
+func TestBinaryStartCmdLaunchGolden(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ serving *instancectl.StagedExe
+ }{
+ {"live", nil},
+ {"serving", &instancectl.StagedExe{Path: "/opt/carlos/versions/v2/blog", Version: "v2", Digest: strings.Repeat("c", 64)}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ ctl := &fakeControl{cmdInv: "inv1"}
+ b, rt := nestedBackend(t, ctl, &fakeUnit{})
+ gc := newGoldenControl(ctl)
+ b.Control = gc
+ b.layoutFn = func(registry.Route) (Layout, string) { return LayoutNested, "" }
+ dir := filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), CmdRunDirName, "run_a")
+ goldenEnv(t) // after the backend's temporary directories are made
+ u, err := b.StartCmd(context.Background(), rt, CmdSpec{RunID: "run_a", Args: []string{"import", "--dry-run"}, RunDir: dir,
+ Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, serving: c.serving,
+ genEnv: map[string]string{"CARLOS_ADMIN_TOKEN": "tok", "CARLOS_CONTROL_SOCKET": "/x", "SHOP_MODE": "live"}})
+ if err != nil {
+ t.Fatalf("StartCmd: %v", err)
+ }
+ cu := u.(*cmdUnit)
+ cu.out.Close()
+ cu.errs.Close()
+ raw, err := os.ReadFile(filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), "launch.cmd.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkBinaryGolden(t, "start_cmd_"+c.name+".launch.cmd.json", goldenPaths(raw, nestedRoots(b)))
+ checkBinaryGolden(t, "start_cmd_"+c.name+".calls", []byte(gc.record()))
+ })
+ }
+}
+
+// StartStaged (genbackend.go) on a binary nested row and a binary flat row:
+// the returned Gen, and the start root is asked for (nested) or the argv
+// the staged executable ran with (flat, which asks root nothing).
+func TestBinaryStartStagedGolden(t *testing.T) {
+ t.Run("nested", func(t *testing.T) {
+ ctl := &fakeControl{inv: "inv1"}
+ unit := &fakeUnit{}
+ unit.set("active", "inv1", true, true)
+ ctl.stopHook = func(string, instancectl.Role) { unit.set("inactive", "inv1", false, false) }
+ b, rt := nestedBackend(t, ctl, unit)
+ b.GenContainment = true
+ gc := newGoldenControl(ctl)
+ b.Control = gc
+ g, proc, err := b.StartStaged(context.Background(), rt, Gen{N: 7, Build: "v2", StagedPath: "/opt/carlos/versions/v2/blog", Digest: strings.Repeat("c", 64)})
+ if err != nil {
+ t.Fatalf("StartStaged: %v", err)
+ }
+ calls := gc.record()
+ if err := proc.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ raw, err := json.MarshalIndent(g, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkBinaryGolden(t, "start_staged_nested.gen.json", append(goldenPaths(raw, nestedRoots(b)), '\n'))
+ checkBinaryGolden(t, "start_staged_nested.calls", []byte(calls))
+ })
+ t.Run("flat", func(t *testing.T) {
+ b := testExecBackend(t)
+ b.RunDirOverride = t.TempDir()
+ host := "blog.example.com"
+ stageLive(t, b, host, "v1")
+ marker := filepath.Join(t.TempDir(), "argv")
+ v2 := filepath.Join(b.OptDir, "versions", "v2", "app")
+ if err := os.MkdirAll(filepath.Dir(v2), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(v2, []byte("#!/bin/sh\nprintf '%s\\n' \"$0\" \"$@\" > '"+marker+"'\nexec sleep 30\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ rt := registry.Route{Host: host, Kind: "instance", DBPath: filepath.Join(b.DataDir, host+".db"),
+ Socket: filepath.Join(b.RunDirOverride, host+".sock")}
+ g, proc, err := b.StartStaged(context.Background(), rt, Gen{N: 5, Build: "v2", StagedPath: v2})
+ if err != nil {
+ t.Fatalf("StartStaged: %v", err)
+ }
+ defer proc.Stop(context.Background()) //nolint:errcheck
+ argv := waitForFile(t, marker, 2*time.Second)
+ roots := map[string]string{b.OptDir: "$OPT", b.DataDir: "$DATA", b.RunDirOverride: "$RUN"}
+ raw, err := json.MarshalIndent(g, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkBinaryGolden(t, "start_staged_flat.gen.json", append(goldenPaths(raw, roots), '\n'))
+ checkBinaryGolden(t, "start_staged_flat.argv", goldenPaths([]byte(argv), roots))
+ })
+}
+
+// serveAfter binds sock after delay and answers 200 from then on.
+func serveAfter(t *testing.T, sock string, delay time.Duration) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(sock), 0o750); err != nil {
+ t.Fatal(err)
+ }
+ stop := make(chan struct{})
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ select {
+ case <-time.After(delay):
+ case <-stop:
+ return
+ }
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ return
+ }
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })}
+ go func() { <-stop; srv.Close() }()
+ srv.Serve(ln) //nolint:errcheck
+ }()
+ t.Cleanup(func() { close(stop); <-done })
+}
+
+// genHealthy (swap.go) and verdictFloorGate (wakeplan.go) bound a binary
+// generation's health by spawnHealthTimeout, 30 s. With the bound shrunk,
+// a socket that answers after it fails and one that answers before passes,
+// and the first wake's verdict window is the bound.
+func TestGenHealthyBoundBinary(t *testing.T) {
+ var out strings.Builder
+ fmt.Fprintf(&out, "spawnHealthTimeout %s\n", spawnHealthTimeout)
+ oldBound, oldFloor := spawnHealthTimeout, firstWakeMinVerdict
+ spawnHealthTimeout, firstWakeMinVerdict = time.Second, 50*time.Millisecond
+ t.Cleanup(func() { spawnHealthTimeout, firstWakeMinVerdict = oldBound, oldFloor })
+ dir, err := os.MkdirTemp("", "gh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ a := &Service{}
+ for _, c := range []struct {
+ name string
+ delay time.Duration
+ }{{"answers before the bound", 50 * time.Millisecond}, {"answers after the bound", 2500 * time.Millisecond}} {
+ sock := filepath.Join(dir, fmt.Sprintf("g%d.sock", c.delay.Milliseconds()))
+ serveAfter(t, sock, c.delay)
+ err := a.genHealthy(context.Background(), Gen{N: 7, Socket: sock, Control: sock + ".control"})
+ verdict := "healthy"
+ if err != nil {
+ verdict = "not healthy"
+ }
+ fmt.Fprintf(&out, "genHealthy, %s: %s\n", c.name, verdict)
+ }
+ var left time.Duration
+ gate := verdictFloorGate(func() error { return nil }, time.Now().Add(time.Hour), &left)
+ err = gate()
+ window := "bounded by spawnHealthTimeout"
+ if err != nil || left > spawnHealthTimeout || left < spawnHealthTimeout-100*time.Millisecond {
+ window = fmt.Sprintf("%s (err %v)", left, err)
+ }
+ fmt.Fprintf(&out, "verdictFloorGate window, health due in an hour: %s\n", window)
+ checkBinaryGolden(t, "gen_healthy_bound.txt", []byte(out.String()))
+}
+
+// KillHost and EmptyHost (genbackend.go) on a binary row. What a unit test
+// reaches: no delegation; a delegated root that is not cgroup v2 (the
+// proof refused, never nil); and through EmptyHost's open seam an absent
+// cgroup (nil), a kernel without cgroup.kill (the leader-only proof) and
+// an open that fails. Killing a populated cgroup needs a real delegated
+// cgroup v2: TestClaimContainmentCleanupRespawn's KillHost leg proves it
+// under CARLOS_CLAIM_SPAWN_KERNEL=1.
+func TestKillHostBinaryGolden(t *testing.T) {
+ var out strings.Builder
+ rt := registry.Route{Host: "blog.example.com", Kind: "instance"}
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ answer := func(err error) string {
+ if err == nil {
+ return "nil"
+ }
+ for _, s := range []struct {
+ name string
+ err error
+ }{{"ErrNoDelegation", cgroup.ErrNoDelegation}, {"ErrNoKill", cgroup.ErrNoKill}, {"ErrStrictUnsupported", cgroup.ErrStrictUnsupported}, {"ErrNoCgroup", cgroup.ErrNoCgroup}} {
+ if errors.Is(err, s.err) {
+ return s.name
+ }
+ }
+ return "error"
+ }
+ plain := testExecBackend(t)
+ fmt.Fprintf(&out, "KillHost, no delegation: %s\n", answer(plain.KillHost(ctx, rt)))
+ fmt.Fprintf(&out, "EmptyHost, no delegation: %s\n", answer(plain.EmptyHost(ctx, rt)))
+ for _, c := range []struct {
+ host string
+ present bool
+ }{{"absent.example.com", false}, {"present.example.com", true}} {
+ b, parent := delegatedBackend(t, c.host)
+ if !c.present {
+ if err := os.RemoveAll(parent); err != nil {
+ t.Fatal(err)
+ }
+ }
+ frt := registry.Route{Host: c.host, Kind: "instance"}
+ fmt.Fprintf(&out, "KillHost, delegated fixture root, host cgroup present=%v: %s\n", c.present, answer(b.KillHost(ctx, frt)))
+ fmt.Fprintf(&out, "EmptyHost, delegated fixture root, host cgroup present=%v: %s\n", c.present, answer(b.EmptyHost(ctx, frt)))
+ }
+ for _, c := range []struct {
+ name string
+ open error
+ }{
+ {"absent cgroup", cgroup.ErrNoCgroup},
+ {"no cgroup.kill", fmt.Errorf("%w: open cgroup.kill: no such file or directory", cgroup.ErrNoKill)},
+ {"open fails", errors.New("permission denied")},
+ } {
+ b := testExecBackend(t)
+ var opened []string
+ b.openHostCleanup = func(host string) (*cgroup.Cleanup, error) {
+ opened = append(opened, host)
+ return nil, c.open
+ }
+ err := b.EmptyHost(ctx, rt)
+ fmt.Fprintf(&out, "EmptyHost, %s: %s (opened %v)\n", c.name, answer(err), opened)
+ }
+ checkBinaryGolden(t, "kill_host.txt", []byte(out.String()))
+}
+
+// HasSidecar (backend_exec.go) on a binary row, flat and nested: a planted
+// <host>-sidecar.env in the row's data directory answers true, none false.
+func TestHasSidecarBinaryGolden(t *testing.T) {
+ var out strings.Builder
+ flat := testExecBackend(t)
+ nested, nrt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
+ for _, c := range []struct {
+ name string
+ b *ExecBackend
+ rt registry.Route
+ }{{"flat", flat, testRoute("bots.example.com")}, {"nested", nested, nrt}} {
+ fmt.Fprintf(&out, "%s, none planted: %v\n", c.name, c.b.HasSidecar(c.rt))
+ dir := c.b.pathsFor(c.rt).dataDir
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, c.rt.Host+"-sidecar.env"), []byte("CARLOS_BASE=x\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ fmt.Fprintf(&out, "%s, %s-sidecar.env planted: %v\n", c.name, c.rt.Host, c.b.HasSidecar(c.rt))
+ }
+ checkBinaryGolden(t, "has_sidecar.txt", []byte(out.String()))
+}
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go
new file mode 100644
index 000000000..52ebd26e8
--- /dev/null
+++ b/internal/activator/rootfs_invariants_test.go
@@ -0,0 +1,699 @@
+package activator
+
+// Rootfs apps Plan 3's invariant guards (plan, "Invariants"). Each passes
+// on main and fails on a violation, and every later task keeps it green:
+//
+// - INV-1, structural: TestRootfsFilesNameNoBinaryVerb. No rootfs file of
+// this package names a binary verb, the host cgroup's kill or childEnv.
+// - INV-1, behaviour: TestEveryRootfsProofNamesTheRootfsUnit. Each rootfs
+// handle stops, polls and proves its own rootfs unit, through the
+// runtime dispatch in the shared files the structural guard does not
+// read (cmdunit.go, unitproc.go).
+// - INV-2: TestRootfsRemovalOwnersUnchanged. Root's removal allowlists
+// never grow.
+// - INV-4: TestRootfsRefusalsAreNotBuildFailures. Every rootfs refusal is
+// an ownership end, never the build's failure.
+// - INV-5: TestRootfsLaunchFilesCarryOnlyComposedEnv. A rootfs launch
+// file carries the composed environment and nothing of the agent's.
+//
+// The tables only grow. A later task adds its handle, its process or its
+// sentinel as a row; it never removes a row, an entry of a refused list or
+// a fixture, and never adds an allowance.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "golang.org/x/tools/go/packages"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// ---- INV-1, structural -------------------------------------------------
+
+// rootfsBinaryVerbs are the binary unit's verbs a rootfs file never names:
+// interface -> its methods. A selection is refused when its method has one
+// of these names and either its receiver implements the interface (so an
+// alias, an embedding or the concrete *instancectl.Client is caught) or
+// its signature is the verb's (so an anonymous interface holding only the
+// verb is caught). A *unitProc's Stop has neither, and passes.
+var rootfsBinaryVerbs = map[string][]string{
+ "Control": {"Stop", "Cmd", "CmdStatus"},
+ "GenControl": {"StopGen"},
+ "cmdExeStarter": {"CmdExe"},
+}
+
+// rootfsRefusedNames are names a rootfs file never refers to, as a call, a
+// value or a type: this package's childEnv (the agent's environment) and
+// the binary host cgroup's interfaces, and every method named KillHost or
+// EmptyHost, whatever its receiver.
+var (
+ rootfsRefusedObjects = []string{"childEnv", "hostKiller", "hostEmptier"}
+ rootfsRefusedMethods = []string{"KillHost", "EmptyHost"}
+ // rootfsRefusedFields: type -> field. ExecBackend's openHostCleanup is
+ // EmptyHost's open of the host cgroup.
+ rootfsRefusedFields = map[string]string{"ExecBackend": "openHostCleanup"}
+ // rootfsRefusedForeign: import path -> type -> method. The host
+ // cgroup's open (what a Cgroups field's OpenCleanup reaches).
+ rootfsRefusedForeign = map[string]map[string]string{
+ "github.com/carlosframework/platform/internal/cgroup": {"Manager": "OpenCleanup"},
+ }
+)
+
+// isRootfsFile is the files the structural guard reads: every non-test
+// rootfs*.go of this package and backend_rootfs.go.
+func isRootfsFile(name string) bool {
+ base := filepath.Base(name)
+ if strings.HasSuffix(base, "_test.go") || !strings.HasSuffix(base, ".go") {
+ return false
+ }
+ return strings.HasPrefix(base, "rootfs") || base == "backend_rootfs.go"
+}
+
+const verbGuardFixtureDir = "testdata/rootfs_verb_guard"
+
+// verbGuardFixturePrefix names a fixture inside the loaded package. It does
+// not start with "rootfs", so no fixture is read as a real rootfs file.
+const verbGuardFixturePrefix = "zz_verb_guard_fixture_"
+
+// loadVerbGuardPackage type-checks this package's non-test files once,
+// with every fixture of verbGuardFixtureDir laid over it as a file of the
+// package (go list's overlay), so a fixture resolves exactly as a real
+// rootfs file would.
+var loadVerbGuardPackage = sync.OnceValues(func() (*packages.Package, error) {
+ dir, err := os.Getwd()
+ if err != nil {
+ return nil, err
+ }
+ fixtures, err := filepath.Glob(filepath.Join(verbGuardFixtureDir, "*.go"))
+ if err != nil {
+ return nil, err
+ }
+ overlay := map[string][]byte{}
+ for _, f := range fixtures {
+ src, err := os.ReadFile(f)
+ if err != nil {
+ return nil, err
+ }
+ overlay[filepath.Join(dir, verbGuardFixturePrefix+filepath.Base(f))] = src
+ }
+ cfg := &packages.Config{Dir: dir, Overlay: overlay,
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports}
+ pkgs, err := packages.Load(cfg, ".")
+ if err != nil {
+ return nil, err
+ }
+ if len(pkgs) != 1 {
+ return nil, fmt.Errorf("loaded %d packages, want this one", len(pkgs))
+ }
+ if len(pkgs[0].Errors) > 0 {
+ return nil, fmt.Errorf("type errors: %v", pkgs[0].Errors)
+ }
+ return pkgs[0], nil
+})
+
+// verbGuard is the refused objects and verbs, resolved in the loaded
+// package.
+type verbGuard struct {
+ info *types.Info
+ fset *token.FileSet
+ refused map[types.Object]string
+ verbs []binaryVerb
+}
+
+type binaryVerb struct {
+ iface *types.Interface
+ name string // Iface.Method
+ method *types.Func
+}
+
+func newVerbGuard(t *testing.T, pkg *packages.Package) *verbGuard {
+ t.Helper()
+ g := &verbGuard{info: pkg.TypesInfo, fset: pkg.Fset, refused: map[types.Object]string{}}
+ scope := pkg.Types.Scope()
+ lookup := func(name string) types.Object {
+ obj := scope.Lookup(name)
+ if obj == nil {
+ t.Fatalf("the guard names %s, which this package no longer declares", name)
+ }
+ return obj
+ }
+ for _, name := range rootfsRefusedObjects {
+ g.refused[lookup(name)] = name
+ }
+ for typ, field := range rootfsRefusedFields {
+ obj, _, _ := types.LookupFieldOrMethod(lookup(typ).Type(), true, pkg.Types, field)
+ if obj == nil {
+ t.Fatalf("the guard names %s.%s, which no longer exists", typ, field)
+ }
+ g.refused[obj] = typ + "." + field
+ }
+ for path, methods := range rootfsRefusedForeign {
+ imp := pkg.Imports[path]
+ if imp == nil {
+ t.Fatalf("the guard names %s, which this package no longer imports", path)
+ }
+ for typ, method := range methods {
+ tn := imp.Types.Scope().Lookup(typ)
+ if tn == nil {
+ t.Fatalf("the guard names %s.%s, which no longer exists", path, typ)
+ }
+ obj, _, _ := types.LookupFieldOrMethod(tn.Type(), true, imp.Types, method)
+ if obj == nil {
+ t.Fatalf("the guard names %s.%s.%s, which no longer exists", path, typ, method)
+ }
+ g.refused[obj] = imp.Name + "." + typ + "." + method
+ }
+ }
+ ifaces := make([]string, 0, len(rootfsBinaryVerbs))
+ for name := range rootfsBinaryVerbs {
+ ifaces = append(ifaces, name)
+ }
+ sort.Strings(ifaces)
+ for _, name := range ifaces {
+ iface, ok := lookup(name).Type().Underlying().(*types.Interface)
+ if !ok {
+ t.Fatalf("%s is no longer an interface", name)
+ }
+ for _, m := range rootfsBinaryVerbs[name] {
+ obj, _, _ := types.LookupFieldOrMethod(iface, false, pkg.Types, m)
+ fn, ok := obj.(*types.Func)
+ if !ok {
+ t.Fatalf("%s has no method %s", name, m)
+ }
+ g.verbs = append(g.verbs, binaryVerb{iface: iface, name: name + "." + m, method: fn})
+ }
+ }
+ return g
+}
+
+// scan judges one file: every selection of a method and every identifier
+// it uses, function bodies, closures and package-level values alike.
+func (g *verbGuard) scan(f *ast.File) []string {
+ var problems []string
+ at := func(n ast.Node) string { return g.fset.Position(n.Pos()).String() }
+ ast.Inspect(f, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.SelectorExpr:
+ sel := g.info.Selections[x]
+ if sel == nil || sel.Kind() == types.FieldVal {
+ return true
+ }
+ fn, ok := sel.Obj().(*types.Func)
+ if !ok {
+ return true
+ }
+ for _, v := range g.verbs {
+ if fn.Name() == v.method.Name() && (implements(sel.Recv(), v.iface) || types.Identical(fn.Type(), v.method.Type())) {
+ problems = append(problems, at(x)+": binary verb "+v.name+" (on "+sel.Recv().String()+") in a rootfs file")
+ }
+ }
+ case *ast.Ident:
+ obj := g.info.Uses[x]
+ if obj == nil {
+ return true
+ }
+ if name, ok := g.refused[obj]; ok {
+ problems = append(problems, at(x)+": "+name+" in a rootfs file")
+ }
+ if fn, ok := obj.(*types.Func); ok && slices.Contains(rootfsRefusedMethods, fn.Name()) {
+ if sig, ok := fn.Type().(*types.Signature); ok && sig.Recv() != nil {
+ problems = append(problems, at(x)+": "+fn.Name()+" (on "+sig.Recv().Type().String()+") in a rootfs file")
+ }
+ }
+ }
+ return true
+ })
+ return problems
+}
+
+// implements reports whether t, or a pointer to it, implements iface.
+func implements(t types.Type, iface *types.Interface) bool {
+ if types.Implements(t, iface) {
+ return true
+ }
+ if _, isPtr := t.(*types.Pointer); !isPtr && !types.IsInterface(t) {
+ return types.Implements(types.NewPointer(t), iface)
+ }
+ return false
+}
+
+func TestRootfsFilesNameNoBinaryVerb(t *testing.T) {
+ pkg, err := loadVerbGuardPackage()
+ if err != nil {
+ t.Fatal(err)
+ }
+ g := newVerbGuard(t, pkg)
+ byName := map[string]*ast.File{}
+ for _, f := range pkg.Syntax {
+ byName[filepath.Base(pkg.Fset.Position(f.Package).Filename)] = f
+ }
+ var scanned []string
+ for name, f := range byName {
+ if !isRootfsFile(name) {
+ continue
+ }
+ scanned = append(scanned, name)
+ for _, p := range g.scan(f) {
+ t.Error(p)
+ }
+ }
+ // rootfs.go is Plan 2's agent start; a guard that reads nothing proves
+ // nothing.
+ if !slices.Contains(scanned, "rootfs.go") {
+ t.Fatalf("the guard read %v, not rootfs.go", scanned)
+ }
+ for fixture, want := range map[string][]string{
+ "clean.go": nil,
+ "direct.go": {"binary verb Control.Stop"},
+ "methodvalue.go": {"binary verb Control.CmdStatus", "binary verb GenControl.StopGen"},
+ "alias.go": {"binary verb Control.Stop (on github.com/carlosframework/platform/internal/activator.Control)", "binary verb Control.Cmd (on interface{Cmd"},
+ "childenv.go": {"childEnv in a rootfs file"},
+ "killhost.go": {"KillHost (on *github.com/carlosframework/platform/internal/activator.SplitBackend)"},
+ "others.go": {"binary verb cmdExeStarter.CmdExe", "binary verb Control.Stop (on *github.com/carlosframework/platform/internal/instancectl.Client)",
+ "cgroup.Manager.OpenCleanup in a rootfs file", "ExecBackend.openHostCleanup in a rootfs file",
+ "hostEmptier in a rootfs file", "hostKiller in a rootfs file", "EmptyHost (on github.com/carlosframework/platform/internal/activator.hostEmptier)"},
+ } {
+ t.Run(fixture, func(t *testing.T) {
+ f := byName[verbGuardFixturePrefix+fixture]
+ if f == nil {
+ t.Fatalf("fixture %s was not loaded", fixture)
+ }
+ got := g.scan(f)
+ for _, w := range want {
+ if !slices.ContainsFunc(got, func(p string) bool { return strings.Contains(p, w) }) {
+ t.Errorf("the guard did not report %q; it reported:\n%s", w, strings.Join(got, "\n"))
+ }
+ }
+ if want == nil && len(got) > 0 {
+ t.Errorf("the guard refused a clean source:\n%s", strings.Join(got, "\n"))
+ }
+ })
+ }
+}
+
+// ---- INV-1, behaviour ----------------------------------------------------
+
+// rootfsProofRig is a production-wired rootfs backend (nestedBackend under
+// newRootfsBackend, with fakeControl and its generation verbs, so a binary
+// stop would be answered and recorded) whose unit evidence is a cgroup
+// fixture the test sets. No answer names a binary unit: systemd reports
+// none loaded and its cgroup is absent, which reads as empty, so a proof
+// of the wrong unit would wrongly succeed. Every rootfs unit's group is
+// populated until the test empties it.
+type rootfsProofRig struct {
+ b *ExecBackend
+ ctl *fakeControl
+ rt registry.Route
+ mu sync.Mutex
+ unit map[string][2]string // rootfs unit -> ActiveState, InvocationID
+}
+
+func newRootfsProofRig(t *testing.T) *rootfsProofRig {
+ t.Helper()
+ b, ctl := newRootfsBackend(t)
+ r := &rootfsProofRig{b: b, ctl: ctl, rt: rootfsRoute(b), unit: map[string][2]string{}}
+ b.Control = fakeGenControl{ctl}
+ b.GenContainment = true
+ b.CgroupEvents = nil
+ b.CgroupRoot = t.TempDir()
+ slice := instancectl.SliceName(r.rt.Host)
+ b.ControlGroup = func(_ context.Context, unit string) (string, error) {
+ if r.isRootfsUnit(unit) {
+ return "/carlos.slice/carlos-instances.slice/" + slice + "/" + unit, nil
+ }
+ return "", nil
+ }
+ b.UnitState = func(_ context.Context, unit string) (string, string, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if s, ok := r.unit[unit]; ok {
+ return s[0], s[1], nil
+ }
+ return "inactive", "", nil // not loaded: no binary unit exists
+ }
+ // Every stop verb leaves the unit inactive with its invocation: only
+ // the cgroup proof stands between a stop and its completion.
+ ctl.stopHook = func(string, instancectl.Role) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for u, s := range r.unit {
+ r.unit[u] = [2]string{"inactive", s[1]}
+ }
+ }
+ for _, u := range []string{instancectl.RootfsUnitName(instancectl.RoleRun, r.rt.Host), instancectl.RootfsGenUnitName(r.rt.Host, 7),
+ instancectl.RootfsUnitName(instancectl.RoleCmd, r.rt.Host)} {
+ r.unit[u] = [2]string{"active", "inv1"}
+ r.setPopulated(t, u, true)
+ }
+ return r
+}
+
+func (r *rootfsProofRig) isRootfsUnit(unit string) bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ _, ok := r.unit[unit]
+ return ok
+}
+
+func (r *rootfsProofRig) setPopulated(t *testing.T, unit string, populated bool) {
+ t.Helper()
+ dir := filepath.Join(r.b.CgroupRoot, "carlos.slice", "carlos-instances.slice", instancectl.SliceName(r.rt.Host), unit)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ body := "populated 0\nfrozen 0\n"
+ if populated {
+ body = "populated 1\nfrozen 0\n"
+ }
+ if err := os.WriteFile(filepath.Join(dir, "cgroup.events"), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// noBinaryVerb fails t if any call so far went to a binary unit's verb.
+func (r *rootfsProofRig) noBinaryVerb(t *testing.T) {
+ t.Helper()
+ noCallStarts(t, r.ctl, "start "+r.rt.Host, "stop "+r.rt.Host, "stopgen", "startgen", "cmd "+r.rt.Host, "cmdstatus "+r.rt.Host)
+}
+
+// rootfsProofHandles: one row per rootfs handle, each asserting its stop,
+// poll and kill go to its rootfs unit and stay unproven while that unit's
+// group is populated. N1, Task 12, R1 and W1 add their handles' rows.
+var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){
+ "web generation unitProc": func(t *testing.T, r *rootfsProofRig) {
+ id := stagedRootfsIdentity(t, r.b, "v2")
+ sock := nestedGenSocketIn(r.b.pathsFor(r.rt).runDir, 7)
+ r.ctl.onStart = serveHealthy(t, sock)
+ p, _, err := r.b.StartGenExe(context.Background(), r.rt, 7, true, id)
+ if err != nil {
+ t.Fatalf("StartGenExe: %v", err)
+ }
+ unit := instancectl.RootfsGenUnitName(r.rt.Host, 7)
+ t.Cleanup(func() {
+ r.setPopulated(t, unit, false)
+ waitFor(t, "the generation to exit once its group is empty", p.Exited)
+ })
+ if up := p.(*unitProc); up.unit != unit {
+ t.Fatalf("the handle watches %q, want %q", up.unit, unit)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+ if err := p.Stop(ctx); !errors.Is(err, ErrStillRunning) {
+ t.Fatalf("Stop with %s's group populated = %v, want ErrStillRunning", unit, err)
+ }
+ if p.Exited() {
+ t.Fatal("the generation read as exited while its rootfs unit's group is populated")
+ }
+ r.ctl.mustHaveCallPrefix(t, "stop-rootfs "+r.rt.Host+" role=run gen=7 worker= kill=false")
+ r.noBinaryVerb(t)
+ if _, err := os.Stat(filepath.Join(r.b.pathsFor(r.rt).dataDir, instancectl.GenLaunchFileName(7))); err != nil {
+ t.Errorf("the unproven generation's launch file: %v, want it kept", err)
+ }
+ },
+ "rootfs cmdUnit": func(t *testing.T, r *rootfsProofRig) {
+ old := roleEmptyBound
+ roleEmptyBound = 100 * time.Millisecond
+ t.Cleanup(func() { roleEmptyBound = old })
+ r.ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdRunning}
+ r.ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdGone} // the binary unit's answer
+ u := &cmdUnit{b: r.b, rt: r.rt, inv: "inv-r", out: emptyCmdStream(t), errs: emptyCmdStream(t)}
+ st, err := u.Poll(context.Background())
+ if err != nil || st.State != instancectl.CmdRunning {
+ t.Fatalf("Poll = %+v, %v; want running, from the rootfs cmd unit", st, err)
+ }
+ r.ctl.mustHaveCallPrefix(t, "cmdstatus-rootfs "+r.rt.Host+" inv-r")
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, r.rt.Host)
+ if err := u.StopAndSettle(context.Background()); err == nil {
+ t.Fatalf("StopAndSettle proved the cmd unit gone while %s's group is populated", unit)
+ }
+ r.ctl.mustHaveCallPrefix(t, "stop-rootfs "+r.rt.Host+" role=cmd gen=0")
+ r.noBinaryVerb(t)
+ r.setPopulated(t, unit, false)
+ if err := u.StopAndSettle(context.Background()); err != nil {
+ t.Fatalf("StopAndSettle once %s's group is empty: %v", unit, err)
+ }
+ r.noBinaryVerb(t)
+ },
+}
+
+// stagedRootfsIdentity stages acme/shop at ver as root's staging leaves it
+// and names it as a recorded build.
+func stagedRootfsIdentity(t *testing.T, b *ExecBackend, ver string) release.StagedIdentity {
+ t.Helper()
+ sum := stageRootfsImage(t, b, ver, release.KindRootfs)
+ return release.StagedIdentity{Version: ver, StagedPath: release.VersionPath(b.OptDir, rootfsTestAcct, ver, rootfsTestApp), Digest: sum}
+}
+
+// Not parallel: rows shrink package bounds (roleEmptyBound).
+func TestEveryRootfsProofNamesTheRootfsUnit(t *testing.T) {
+ for name, row := range rootfsProofHandles {
+ t.Run(name, func(t *testing.T) { row(t, newRootfsProofRig(t)) })
+ }
+}
+
+// ---- INV-2 ---------------------------------------------------------------
+
+// The removal guard's allowlists as they stood at Plan 3 Task 1. Plan 3
+// adds no removal owner on root's side; the claims cleanup may take some
+// away, so the guard checks each list is a subset of its pin.
+var (
+ pinnedRootfsRemovalOwners = []string{"startRootfs", "startRootfsCmd", "stopRootfs", "cleanCmdExe", "handleSweep", "sweepGenLeftover"}
+ pinnedRawRemovalOwners = []string{
+ "removeRootfsExe", "removeWorkerFiles", "removeRootfsGenFiles", "removeJITDropIn",
+ "removeGenFiles", "removeSharedKeyDir", "removeEntry", "removeTree",
+ "removeCmdExe", "ensureExeAs", "replaceLink",
+ "writeFileExcl", "BuildProbeImage", "bindControlSocket",
+ "prepareExecGate", "clearLaunch",
+ }
+)
+
+const removalGuardPath = "../instancectl/rootfs_removal_guard_test.go"
+
+func TestRootfsRemovalOwnersUnchanged(t *testing.T) {
+ for _, p := range removalOwnerProblems(t, removalGuardPath) {
+ t.Error(p)
+ }
+ for fixture, want := range map[string]string{
+ "added.go": `rawRemovalOwners names "x"`,
+ "shrunk.go": "",
+ "missing.go": "rootfsRemovalOwners not found",
+ } {
+ t.Run(fixture, func(t *testing.T) {
+ got := removalOwnerProblems(t, filepath.Join("testdata", "rootfs_removal_owners", fixture))
+ if want == "" {
+ if len(got) > 0 {
+ t.Errorf("refused a shrunk allowlist:\n%s", strings.Join(got, "\n"))
+ }
+ return
+ }
+ if !slices.ContainsFunc(got, func(p string) bool { return strings.Contains(p, want) }) {
+ t.Errorf("did not report %q; reported:\n%s", want, strings.Join(got, "\n"))
+ }
+ })
+ }
+}
+
+// removalOwnerProblems parses path and checks the keys of its two
+// package-level allowlists against their pins.
+func removalOwnerProblems(t *testing.T, path string) []string {
+ t.Helper()
+ f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.SkipObjectResolution)
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := map[string][]string{}
+ for _, decl := range f.Decls {
+ gd, ok := decl.(*ast.GenDecl)
+ if !ok || gd.Tok != token.VAR {
+ continue
+ }
+ for _, spec := range gd.Specs {
+ vs := spec.(*ast.ValueSpec)
+ for i, id := range vs.Names {
+ if i >= len(vs.Values) {
+ continue
+ }
+ lit, ok := vs.Values[i].(*ast.CompositeLit)
+ if !ok {
+ continue
+ }
+ keys := []string{}
+ for _, el := range lit.Elts {
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
+ if bl, ok := kv.Key.(*ast.BasicLit); ok && bl.Kind == token.STRING {
+ keys = append(keys, strings.Trim(bl.Value, `"`))
+ }
+ }
+ }
+ found[id.Name] = keys
+ }
+ }
+ }
+ var problems []string
+ for name, pinned := range map[string][]string{"rootfsRemovalOwners": pinnedRootfsRemovalOwners, "rawRemovalOwners": pinnedRawRemovalOwners} {
+ keys, ok := found[name]
+ if !ok {
+ problems = append(problems, path+": "+name+" not found: the guard cannot vouch for an allowlist it cannot read")
+ continue
+ }
+ for _, k := range keys {
+ if !slices.Contains(pinned, k) {
+ problems = append(problems, fmt.Sprintf("%s: %s names %q, which Plan 3 Task 1 did not pin: root gains no removal owner (INV-2)", path, name, k))
+ }
+ }
+ }
+ sort.Strings(problems)
+ return problems
+}
+
+// ---- INV-4 ---------------------------------------------------------------
+
+// rootfsRefusals are today's rootfs refusals, each wrapped as the code
+// wraps it. Task 7, Task 12 and Group R add theirs (R1's release results
+// through classifyRelease).
+var rootfsRefusals = []struct {
+ name string
+ err error
+}{
+ {"refuseRootfs (a gate's refusal)", refuseRootfs(errors.New("x"))},
+ {"errRootfsRefused", errRootfsRefused},
+ {"errRootfsBinaryLaunch", errRootfsBinaryLaunch},
+ {"errNoRootfsControl", errNoRootfsControl},
+ {"root's 403 (ErrStagedImage)", fmt.Errorf("%w: x", instancectl.ErrStagedImage)},
+ {"root's pre-start refusal (ErrStartRefused, marked)", refuseRootfs(fmt.Errorf("%w: x", instancectl.ErrStartRefused))},
+ {"errBuildStateUnwritten", errBuildStateUnwritten},
+}
+
+func TestRootfsRefusalsAreNotBuildFailures(t *testing.T) {
+ t.Parallel()
+ for _, c := range rootfsRefusals {
+ if v := verdictOf(c.err); v != gateNoOwnership {
+ t.Errorf("%s: verdictOf = %d, want gateNoOwnership: %v", c.name, v, c.err)
+ }
+ if s := classifyStep(nil, c.err); s != stepStale {
+ t.Errorf("%s: classifyStep = %d, want stepStale (never stepFailed): %v", c.name, s, c.err)
+ }
+ }
+}
+
+// ---- INV-5 ---------------------------------------------------------------
+
+// rootfsLaunchRows: process -> a start through the production backend that
+// returns the launch file it wrote and the variables the start composed.
+// Task 6 and Task 12, R1 and W1 add their processes (run, release, worker).
+var rootfsLaunchRows = map[string]func(t *testing.T) (instancectl.Launch, map[string]string){
+ "web": func(t *testing.T) (instancectl.Launch, map[string]string) {
+ b, ctl := newRootfsBackend(t)
+ b.GenContainment = true
+ rt := rootfsRoute(b)
+ writeInstanceEnv(t, b, rt, "SHOP_MODE=live\n")
+ id := stagedRootfsIdentity(t, b, "v2")
+ sock := nestedGenSocketIn(b.pathsFor(rt).runDir, 7)
+ ctl.onStart = serveHealthy(t, sock)
+ p, _, err := b.StartGenExe(context.Background(), rt, 7, true, id)
+ if err != nil {
+ t.Fatalf("StartGenExe: %v", err)
+ }
+ t.Cleanup(func() { p.Stop(context.Background()) }) //nolint:errcheck
+ l := readLaunchNamed(t, b, rt, instancectl.GenLaunchFileName(7))
+ // What startRootfs composed: the file environment the generation
+ // launched with (its handle keeps it), the agent-owned variables,
+ // then the socket and the database.
+ vars := rootfsVars(b.agentOwnedVars(rt, sock+".control", p.(*unitProc).LaunchEnv(), true), sock, b.pathsFor(rt).dbPath)
+ if vars["SHOP_MODE"] != "live" {
+ t.Fatalf("the instance's file did not reach the composed variables: %v", vars)
+ }
+ return l, vars
+ },
+}
+
+// Not parallel: it sets the agent's own PATH and HOME.
+func TestRootfsLaunchFilesCarryOnlyComposedEnv(t *testing.T) {
+ t.Setenv("PATH", "/agent/bin")
+ t.Setenv("HOME", "/agent")
+ for process, row := range rootfsLaunchRows {
+ t.Run(process, func(t *testing.T) {
+ l, vars := row(t)
+ if l.Schema != instancectl.LaunchSchemaRootfs || len(l.Argv) != 0 {
+ t.Errorf("launch schema %d with argv %q, want schema %d and no argv", l.Schema, l.Argv, instancectl.LaunchSchemaRootfs)
+ }
+ if want := rootfsLaunchEnv(vars); !slices.Equal(l.Env, want) {
+ t.Errorf("launch env:\n%s\nwant rootfsLaunchEnv of the composed variables:\n%s", strings.Join(l.Env, "\n"), strings.Join(want, "\n"))
+ }
+ for _, kv := range l.Env {
+ if strings.HasPrefix(kv, "PATH=") || strings.HasPrefix(kv, "HOME=") {
+ t.Errorf("the agent's %s reached the launch file", kv)
+ }
+ }
+ })
+ }
+}
+
+// ---- the tables only grow ----------------------------------------------
+
+// rootfsInvariantFloor is every row and refused name the guards above had
+// at Plan 3 Task 1. A later task adds to the tables and never takes one of
+// these away; this floor makes a removal a second, visible edit.
+var rootfsInvariantFloor = map[string][]string{
+ "rootfsBinaryVerbs": {"Control.Cmd", "Control.CmdStatus", "Control.Stop", "GenControl.StopGen", "cmdExeStarter.CmdExe"},
+ "rootfsRefusedObjects": {"childEnv", "hostEmptier", "hostKiller"},
+ "rootfsRefusedMethods": {"EmptyHost", "KillHost"},
+ "rootfsRefusedFields": {"ExecBackend.openHostCleanup"},
+ "rootfsRefusedForeign": {"github.com/carlosframework/platform/internal/cgroup.Manager.OpenCleanup"},
+ "rootfsProofHandles": {"rootfs cmdUnit", "web generation unitProc"},
+ "rootfsRefusals": {"errBuildStateUnwritten", "errNoRootfsControl", "errRootfsBinaryLaunch", "errRootfsRefused",
+ "refuseRootfs (a gate's refusal)", "root's 403 (ErrStagedImage)", "root's pre-start refusal (ErrStartRefused, marked)"},
+ "rootfsLaunchRows": {"web"},
+}
+
+func TestRootfsInvariantTablesOnlyGrow(t *testing.T) {
+ t.Parallel()
+ have := map[string][]string{}
+ for iface, methods := range rootfsBinaryVerbs {
+ for _, m := range methods {
+ have["rootfsBinaryVerbs"] = append(have["rootfsBinaryVerbs"], iface+"."+m)
+ }
+ }
+ have["rootfsRefusedObjects"] = rootfsRefusedObjects
+ have["rootfsRefusedMethods"] = rootfsRefusedMethods
+ for typ, field := range rootfsRefusedFields {
+ have["rootfsRefusedFields"] = append(have["rootfsRefusedFields"], typ+"."+field)
+ }
+ for path, methods := range rootfsRefusedForeign {
+ for typ, m := range methods {
+ have["rootfsRefusedForeign"] = append(have["rootfsRefusedForeign"], path+"."+typ+"."+m)
+ }
+ }
+ for name := range rootfsProofHandles {
+ have["rootfsProofHandles"] = append(have["rootfsProofHandles"], name)
+ }
+ for _, c := range rootfsRefusals {
+ have["rootfsRefusals"] = append(have["rootfsRefusals"], c.name)
+ }
+ for name := range rootfsLaunchRows {
+ have["rootfsLaunchRows"] = append(have["rootfsLaunchRows"], name)
+ }
+ for table, floor := range rootfsInvariantFloor {
+ for _, row := range floor {
+ if !slices.Contains(have[table], row) {
+ t.Errorf("%s lost %q: the invariant tables only grow", table, row)
+ }
+ }
+ }
+}
diff --git a/internal/activator/testdata/binary_golden/gen_healthy_bound.txt b/internal/activator/testdata/binary_golden/gen_healthy_bound.txt
new file mode 100644
index 000000000..ea566c3eb
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/gen_healthy_bound.txt
@@ -0,0 +1,4 @@
+spawnHealthTimeout 30s
+genHealthy, answers before the bound: healthy
+genHealthy, answers after the bound: not healthy
+verdictFloorGate window, health due in an hour: bounded by spawnHealthTimeout
diff --git a/internal/activator/testdata/binary_golden/has_sidecar.txt b/internal/activator/testdata/binary_golden/has_sidecar.txt
new file mode 100644
index 000000000..a90b79f29
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/has_sidecar.txt
@@ -0,0 +1,4 @@
+flat, none planted: false
+flat, bots.example.com-sidecar.env planted: true
+nested, none planted: false
+nested, h.example.com-sidecar.env planted: true
diff --git a/internal/activator/testdata/binary_golden/kill_host.txt b/internal/activator/testdata/binary_golden/kill_host.txt
new file mode 100644
index 000000000..c3e16bd06
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/kill_host.txt
@@ -0,0 +1,9 @@
+KillHost, no delegation: ErrNoDelegation
+EmptyHost, no delegation: ErrNoDelegation
+KillHost, delegated fixture root, host cgroup present=false: ErrStrictUnsupported
+EmptyHost, delegated fixture root, host cgroup present=false: ErrStrictUnsupported
+KillHost, delegated fixture root, host cgroup present=true: ErrStrictUnsupported
+EmptyHost, delegated fixture root, host cgroup present=true: ErrStrictUnsupported
+EmptyHost, absent cgroup: nil (opened [blog.example.com])
+EmptyHost, no cgroup.kill: ErrNoDelegation (opened [blog.example.com])
+EmptyHost, open fails: error (opened [blog.example.com])
diff --git a/internal/activator/testdata/binary_golden/start_cmd_live.calls b/internal/activator/testdata/binary_golden/start_cmd_live.calls
new file mode 100644
index 000000000..39fc009bd
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_cmd_live.calls
@@ -0,0 +1,3 @@
+Cmd host=h.example.com memory_max=536870912
+--- fakeControl
+cmd h.example.com
diff --git a/internal/activator/testdata/binary_golden/start_cmd_live.launch.cmd.json b/internal/activator/testdata/binary_golden/start_cmd_live.launch.cmd.json
new file mode 100644
index 000000000..2f4437aca
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_cmd_live.launch.cmd.json
@@ -0,0 +1,20 @@
+{
+ "schema": 1,
+ "host": "h.example.com",
+ "argv": [
+ "$OPT/live/h.example.com",
+ "import",
+ "--dry-run"
+ ],
+ "env": [
+ "PATH=/agent/bin",
+ "HOME=/agent",
+ "LANG=C.UTF-8",
+ "CARLOS_ADMIN_TOKEN=tok",
+ "CARLOS_DB=$ROOT/data/instances/h.example.com/h.example.com.db",
+ "CARLOS_HOST=h.example.com",
+ "CARLOS_RUN_DIR=$ROOT/data/instances/h.example.com/.carlos-run/run_a",
+ "CARLOS_RUN_ID=run_a",
+ "SHOP_MODE=live"
+ ]
+}
diff --git a/internal/activator/testdata/binary_golden/start_cmd_serving.calls b/internal/activator/testdata/binary_golden/start_cmd_serving.calls
new file mode 100644
index 000000000..7421f9424
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_cmd_serving.calls
@@ -0,0 +1,3 @@
+CmdExe host=h.example.com memory_max=536870912 exe={Path:/opt/carlos/versions/v2/blog Version:v2 Digest:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc}
+--- fakeControl
+
diff --git a/internal/activator/testdata/binary_golden/start_cmd_serving.launch.cmd.json b/internal/activator/testdata/binary_golden/start_cmd_serving.launch.cmd.json
new file mode 100644
index 000000000..2f4437aca
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_cmd_serving.launch.cmd.json
@@ -0,0 +1,20 @@
+{
+ "schema": 1,
+ "host": "h.example.com",
+ "argv": [
+ "$OPT/live/h.example.com",
+ "import",
+ "--dry-run"
+ ],
+ "env": [
+ "PATH=/agent/bin",
+ "HOME=/agent",
+ "LANG=C.UTF-8",
+ "CARLOS_ADMIN_TOKEN=tok",
+ "CARLOS_DB=$ROOT/data/instances/h.example.com/h.example.com.db",
+ "CARLOS_HOST=h.example.com",
+ "CARLOS_RUN_DIR=$ROOT/data/instances/h.example.com/.carlos-run/run_a",
+ "CARLOS_RUN_ID=run_a",
+ "SHOP_MODE=live"
+ ]
+}
diff --git a/internal/activator/testdata/binary_golden/start_staged_flat.argv b/internal/activator/testdata/binary_golden/start_staged_flat.argv
new file mode 100644
index 000000000..373b0fbc8
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_staged_flat.argv
@@ -0,0 +1,5 @@
+$OPT/versions/v2/app
+--socket
+$RUN/g/5/blog.example.com.sock
+--db
+$DATA/blog.example.com.db
diff --git a/internal/activator/testdata/binary_golden/start_staged_flat.gen.json b/internal/activator/testdata/binary_golden/start_staged_flat.gen.json
new file mode 100644
index 000000000..e47a00e75
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_staged_flat.gen.json
@@ -0,0 +1,13 @@
+{
+ "N": 5,
+ "Socket": "$RUN/g/5/blog.example.com.sock",
+ "Control": "$RUN/g/5/blog.example.com.sock.control",
+ "Build": "v2",
+ "StagedPath": "$OPT/versions/v2/app",
+ "Digest": "",
+ "Demand": "",
+ "Tier": {
+ "MemoryMax": 536870912
+ },
+ "Worker": false
+}
diff --git a/internal/activator/testdata/binary_golden/start_staged_nested.calls b/internal/activator/testdata/binary_golden/start_staged_nested.calls
new file mode 100644
index 000000000..96d1e0d6c
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_staged_nested.calls
@@ -0,0 +1,3 @@
+StartGenExe host=h.example.com gen=7 memory_max=536870912 exe={Path:/opt/carlos/versions/v2/blog Version:v2 Digest:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc}
+--- fakeControl
+startgen h.example.com 7 536870912
diff --git a/internal/activator/testdata/binary_golden/start_staged_nested.gen.json b/internal/activator/testdata/binary_golden/start_staged_nested.gen.json
new file mode 100644
index 000000000..7e55e7d66
--- /dev/null
+++ b/internal/activator/testdata/binary_golden/start_staged_nested.gen.json
@@ -0,0 +1,13 @@
+{
+ "N": 7,
+ "Socket": "$ROOT/run/instances/h.example.com/g7/app.sock",
+ "Control": "$ROOT/run/instances/h.example.com/g7/app.sock.control",
+ "Build": "v2",
+ "StagedPath": "/opt/carlos/versions/v2/blog",
+ "Digest": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "Demand": "",
+ "Tier": {
+ "MemoryMax": 536870912
+ },
+ "Worker": false
+}
diff --git a/internal/activator/testdata/rootfs_removal_owners/added.go b/internal/activator/testdata/rootfs_removal_owners/added.go
new file mode 100644
index 000000000..64fe0c816
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/added.go
@@ -0,0 +1,18 @@
+// The removal guard's two allowlists as instancectl pins them, with one
+// raw removal owner added: TestRootfsRemovalOwnersUnchanged refuses "x".
+package instancectl
+
+var (
+ rootfsRemovalOwners = map[string]bool{
+ "startRootfs": true, "startRootfsCmd": true, "stopRootfs": true, "cleanCmdExe": true,
+ "handleSweep": true, "sweepGenLeftover": true,
+ }
+ rawRemovalOwners = map[string]bool{
+ "removeRootfsExe": true, "removeWorkerFiles": true, "removeRootfsGenFiles": true, "removeJITDropIn": true,
+ "removeGenFiles": true, "removeSharedKeyDir": true, "removeEntry": true, "removeTree": true,
+ "removeCmdExe": true, "ensureExeAs": true, "replaceLink": true,
+ "writeFileExcl": true, "BuildProbeImage": true, "bindControlSocket": true,
+ "prepareExecGate": true, "clearLaunch": true,
+ "x": true,
+ }
+)
diff --git a/internal/activator/testdata/rootfs_removal_owners/missing.go b/internal/activator/testdata/rootfs_removal_owners/missing.go
new file mode 100644
index 000000000..46ae406c8
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/missing.go
@@ -0,0 +1,13 @@
+// rootfsRemovalOwners renamed away: TestRootfsRemovalOwnersUnchanged
+// refuses a file in which it cannot find a pinned allowlist, rather than
+// passing over nothing.
+package instancectl
+
+var (
+ removalOwners = map[string]bool{
+ "startRootfs": true,
+ }
+ rawRemovalOwners = map[string]bool{
+ "removeRootfsExe": true,
+ }
+)
diff --git a/internal/activator/testdata/rootfs_removal_owners/shrunk.go b/internal/activator/testdata/rootfs_removal_owners/shrunk.go
new file mode 100644
index 000000000..4a130b06f
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/shrunk.go
@@ -0,0 +1,16 @@
+// The removal guard's two allowlists with entries taken out, as the claims
+// cleanup may leave them: TestRootfsRemovalOwnersUnchanged accepts it.
+package instancectl
+
+var (
+ rootfsRemovalOwners = map[string]bool{
+ "startRootfs": true, "startRootfsCmd": true, "stopRootfs": true, "cleanCmdExe": true,
+ "handleSweep": true, "sweepGenLeftover": true,
+ }
+ rawRemovalOwners = map[string]bool{
+ "removeRootfsExe": true, "removeWorkerFiles": true, "removeRootfsGenFiles": true, "removeJITDropIn": true,
+ "removeGenFiles": true, "removeSharedKeyDir": true, "removeEntry": true, "removeTree": true,
+ "removeCmdExe": true, "ensureExeAs": true, "replaceLink": true,
+ "writeFileExcl": true, "BuildProbeImage": true, "bindControlSocket": true,
+ }
+)
diff --git a/internal/activator/testdata/rootfs_verb_guard/alias.go b/internal/activator/testdata/rootfs_verb_guard/alias.go
new file mode 100644
index 000000000..3b6fb6a29
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/alias.go
@@ -0,0 +1,24 @@
+// The binary verbs through a local variable: ctl := b.Control, then a
+// method value of it; and an anonymous interface holding only Cmd, caught
+// by the verb's signature.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardAlias(ctx context.Context, rt registry.Route) error {
+ ctl := b.Control
+ f := ctl.Stop
+ if err := f(ctx, rt.Host, instancectl.RoleCmd); err != nil {
+ return err
+ }
+ var starter interface {
+ Cmd(ctx context.Context, host string, memoryMax int64) (string, error)
+ } = b.Control
+ _, err := starter.Cmd(ctx, rt.Host, 0)
+ return err
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/childenv.go b/internal/activator/testdata/rootfs_verb_guard/childenv.go
new file mode 100644
index 000000000..9cb41352b
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/childenv.go
@@ -0,0 +1,14 @@
+// childEnv in a rootfs launch: the agent's own environment would reach the
+// tenant's process.
+package activator
+
+import (
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func (b *ExecBackend) verbGuardChildEnv(rt registry.Route, vars map[string]string) error {
+ p := b.pathsFor(rt)
+ return b.writeRootfsLaunchFor(p, instancectl.RoleRun, 7, rt.Host, release.ProcessWeb, childEnv(vars))
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/clean.go b/internal/activator/testdata/rootfs_verb_guard/clean.go
new file mode 100644
index 000000000..81c86d700
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/clean.go
@@ -0,0 +1,32 @@
+// A rootfs file's own verbs, which the guard accepts: a *unitProc's Stop
+// (resolution is by type, so it is not the binary Control's), its method
+// value, RootfsControl's verbs, rootfsLaunchEnv and the rootfs unit's
+// cgroup proof.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardClean(ctx context.Context, rt registry.Route, up *unitProc) error {
+ if err := up.Stop(ctx); err != nil {
+ return err
+ }
+ stop := up.Stop
+ _ = stop
+ rc, err := b.rootfsControl()
+ if err != nil {
+ return err
+ }
+ _ = rootfsLaunchEnv(map[string]string{"SHOP_MODE": "live"})
+ if _, err := rc.CmdStatusRootfs(ctx, rt.Host, "inv"); err != nil {
+ return err
+ }
+ if err := rc.StopRootfs(ctx, rt.Host, instancectl.RoleRun, 7, "", false); err != nil {
+ return err
+ }
+ return b.waitUnitCgroupEmpty(ctx, rt, unitNameFor(rt, instancectl.RoleRun, 7))
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/direct.go b/internal/activator/testdata/rootfs_verb_guard/direct.go
new file mode 100644
index 000000000..9e6a9abd9
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/direct.go
@@ -0,0 +1,13 @@
+// A direct call of the binary Control's Stop.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardDirect(ctx context.Context, rt registry.Route) error {
+ return b.Control.Stop(ctx, rt.Host, instancectl.RoleRun)
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/killhost.go b/internal/activator/testdata/rootfs_verb_guard/killhost.go
new file mode 100644
index 000000000..f1ac51237
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/killhost.go
@@ -0,0 +1,13 @@
+// KillHost on a SplitBackend: the binary host cgroup's kill, which proves
+// nothing about a rootfs unit.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func verbGuardKillHost(ctx context.Context, sb *SplitBackend, rt registry.Route) error {
+ return sb.KillHost(ctx, rt)
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/methodvalue.go b/internal/activator/testdata/rootfs_verb_guard/methodvalue.go
new file mode 100644
index 000000000..492f110bd
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/methodvalue.go
@@ -0,0 +1,22 @@
+// Method values of the binary verbs: Control.CmdStatus, and GenControl's
+// StopGen reached through genControl.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardMethodValue(ctx context.Context, rt registry.Route) error {
+ poll := b.Control.CmdStatus
+ if _, err := poll(ctx, rt.Host, "inv"); err != nil {
+ return err
+ }
+ gc, err := b.genControl()
+ if err != nil {
+ return err
+ }
+ stop := gc.StopGen
+ return stop(ctx, rt.Host, 7, true)
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/others.go b/internal/activator/testdata/rootfs_verb_guard/others.go
new file mode 100644
index 000000000..05625c76e
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/others.go
@@ -0,0 +1,33 @@
+// The rest of the refused names: cmdExeStarter's CmdExe, a method
+// expression on the concrete client, the host cgroup's own open
+// (Cgroups.OpenCleanup and its openHostCleanup seam), EmptyHost and the
+// hostEmptier and hostKiller interfaces.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardOthers(ctx context.Context, rt registry.Route, c *instancectl.Client) error {
+ if cs, ok := b.Control.(cmdExeStarter); ok {
+ if _, err := cs.CmdExe(ctx, rt.Host, 0, instancectl.StagedExe{}); err != nil {
+ return err
+ }
+ }
+ stop := (*instancectl.Client).Stop
+ if err := stop(c, ctx, rt.Host, instancectl.RoleRun); err != nil {
+ return err
+ }
+ if _, err := b.Cgroups.OpenCleanup(rt.Host); err != nil {
+ return err
+ }
+ open := b.openHostCleanup
+ _ = open
+ var empty hostEmptier = b
+ var kill hostKiller = b
+ _ = kill
+ return empty.EmptyHost(ctx, rt)
+}
diff --git a/plan3_groups_test.go b/plan3_groups_test.go
new file mode 100644
index 000000000..64982509c
--- /dev/null
+++ b/plan3_groups_test.go
@@ -0,0 +1,303 @@
+// plan3_groups_test.go
+package main
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// Rootfs apps Plan 3 builds in three groups (plan, "Task order and
+// review"): A (web and carlos run), R (the release command) and W
+// (workers). R and W merge after A, each on its own, so until a group has
+// started nothing of it may reach the code: neither its copy nor its
+// machinery. This file is the inventory that holds that (Astra R3 6):
+//
+// - TestPlan3CopyGroups: the three copy sets are disjoint, their union
+// is exactly the deck's live RFS-3 rows, a landed group's rows are all
+// built, and no row of a group not started is;
+// - TestPlan3MachineryInventory: no name declared in internal/activator
+// matches the release or the worker inventory unless that group has
+// started, beyond the two pinned allowances.
+//
+// Group A is the base group: Task 1 is its first task, so it counts as
+// started from here on and is never listed in plan3GroupsStarted. The
+// first task of Group R adds "R" to plan3GroupsStarted and the R gate adds
+// it to plan3GroupsLanded; Group W does the same with "W". Gate A may add
+// "A" to plan3GroupsLanded. Nothing else changes these lists.
+
+// The three copy sets, pinned. RFS-3-C13 is struck (pre-flight 3.1) and
+// in no set.
+var (
+ plan3CopyA = plan3IDs(11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28)
+ plan3CopyR = plan3IDs(1, 2, 3, 4, 5, 6, 7, 29)
+ plan3CopyW = plan3IDs(8, 9, 10)
+)
+
+// plan3GroupsStarted and plan3GroupsLanded: "R" and "W" (and "A" in
+// landed), each added by the task the file comment names.
+var (
+ plan3GroupsStarted = []string{}
+ plan3GroupsLanded = []string{}
+)
+
+// The release and the worker machinery, by declared name (plan Task 1).
+var (
+ plan3ReleaseInventory = regexp.MustCompile(`(?i)release(Op|Due|Timeout|Passed|BeforeSwap|Env|Backend)|runRelease|classifyRelease|leaseWatch|ReleaseError|errRelease|wakeCeiling|StartRelease`)
+ plan3WorkerInventory = regexp.MustCompile(`(?i)rootfsWorker|RootfsWorker|LaunchRootfsWorker|workerGate|workerWakeGate|startRootfsWorkers|stopRootfsWorkers|handOverRootfsWorkers|WorkerReport|prepareWorker|writeRootfsWorkerLaunch|rootfsUnitFor`)
+)
+
+// plan3MachineryBaseline is every declaration in internal/activator's
+// non-test files that matched either inventory on main at a912a342, read
+// once at Task 1: Plan 2's worker verb on RootfsControl and the binary
+// sidecar worker's WorkerReportedVersion, whose name happens to match.
+// Keyed by kind and owner, so the same name declared anywhere else is
+// judged afresh.
+var plan3MachineryBaseline = map[string]bool{
+ "method RootfsControl.StartRootfsWorker": true, // control.go: Plan 2's worker verb
+ "method Service.WorkerReportedVersion": true, // workerbuild.go: the binary sidecar worker's build
+}
+
+// plan3SharedSeams are Group A's own seams: names that look like release or
+// worker machinery but belong to A (plan Task 1), so A's tasks may declare
+// them before either group starts.
+var plan3SharedSeams = map[string]bool{
+ "Processes": true, "ProcessReader": true, "rootfsProcessesHook": true, "superviseRootfsLocked": true,
+ "startCmdUnit": true, "stagedImageOf": true, "stagedIdentityOf": true, "rootfsCmdVars": true,
+ "residentFailure": true,
+}
+
+func plan3IDs(ns ...int) []string {
+ ids := make([]string, len(ns))
+ for i, n := range ns {
+ ids[i] = fmt.Sprintf("RFS-3-C%02d", n)
+ }
+ return ids
+}
+
+func plan3GroupStarted(g string) bool { return g == "A" || slices.Contains(plan3GroupsStarted, g) }
+
+func TestPlan3CopyGroups(t *testing.T) {
+ groups := map[string][]string{"A": plan3CopyA, "R": plan3CopyR, "W": plan3CopyW}
+ for _, g := range plan3GroupsStarted {
+ if g != "R" && g != "W" {
+ t.Errorf("plan3GroupsStarted names %q: only R and W are started by a task (A is the base group)", g)
+ }
+ }
+ for _, g := range plan3GroupsLanded {
+ if groups[g] == nil {
+ t.Errorf("plan3GroupsLanded names %q, not a group", g)
+ } else if !plan3GroupStarted(g) {
+ t.Errorf("group %s landed but never started", g)
+ }
+ }
+ owner := map[string]string{}
+ for _, g := range []string{"A", "R", "W"} {
+ for _, id := range groups[g] {
+ if o, dup := owner[id]; dup {
+ t.Errorf("%s is in both group %s and group %s", id, o, g)
+ }
+ owner[id] = g
+ }
+ }
+ live := map[string]bool{}
+ for _, r := range mustParseRootfsRecord(t) {
+ if strings.HasPrefix(r.ID, "RFS-3-") && r.Status != "struck" {
+ live[r.ID] = true
+ }
+ }
+ for id := range live {
+ if owner[id] == "" {
+ t.Errorf("the deck's live row %s is in no group", id)
+ }
+ }
+ for id, g := range owner {
+ if !live[id] {
+ t.Errorf("group %s names %s, which is not a live row of the deck", g, id)
+ }
+ }
+ built := map[string]bool{}
+ for _, id := range rootfsCopyBuilt {
+ built[id] = true
+ }
+ for _, g := range plan3GroupsLanded {
+ for _, id := range groups[g] {
+ if !built[id] {
+ t.Errorf("group %s has landed but %s is not in rootfsCopyBuilt", g, id)
+ }
+ }
+ }
+ for g, ids := range groups {
+ if plan3GroupStarted(g) {
+ continue
+ }
+ for _, id := range ids {
+ if built[id] {
+ t.Errorf("%s is built but group %s has not started", id, g)
+ }
+ }
+ }
+}
+
+func TestPlan3MachineryInventory(t *testing.T) {
+ files, err := filepath.Glob(filepath.Join("internal", "activator", "*.go"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sources []string
+ for _, f := range files {
+ if !strings.HasSuffix(f, "_test.go") {
+ sources = append(sources, f)
+ }
+ }
+ if len(sources) < 50 {
+ t.Fatalf("found %d sources in internal/activator: the inventory reads the wrong directory", len(sources))
+ }
+ problems, seen := plan3InventoryProblems(t, sources)
+ for _, p := range problems {
+ t.Error(p)
+ }
+ // A baseline name that no longer exists is a stale allowance: drop it,
+ // so a later declaration of the same name is judged afresh.
+ for key := range plan3MachineryBaseline {
+ if !seen[key] {
+ t.Errorf("plan3MachineryBaseline lists %s, which internal/activator no longer declares: drop it", key)
+ }
+ }
+}
+
+// The fixture declares a release name, a worker name and the baseline's
+// StartRootfsWorker on another owner beside a shared seam and a binary
+// name: the inventory must refuse exactly the first three.
+func TestPlan3MachineryInventoryFixture(t *testing.T) {
+ problems, _ := plan3InventoryProblems(t, []string{filepath.Join("testdata", "plan3_inventory", "added.go")})
+ want := []string{"func runRelease: release machinery before group R has started",
+ "type rootfsWorkerState: worker machinery before group W has started",
+ "method Service.StartRootfsWorker: worker machinery before group W has started"}
+ if len(problems) != len(want) {
+ t.Fatalf("the inventory reported %d problems, want %d:\n%s", len(problems), len(want), strings.Join(problems, "\n"))
+ }
+ for _, w := range want {
+ if !slices.ContainsFunc(problems, func(p string) bool { return strings.Contains(p, w) }) {
+ t.Errorf("the inventory did not report %q; it reported:\n%s", w, strings.Join(problems, "\n"))
+ }
+ }
+}
+
+// plan3InventoryProblems judges every declaration in sources, and reports
+// which baseline keys it saw.
+func plan3InventoryProblems(t *testing.T, sources []string) (problems []string, seen map[string]bool) {
+ t.Helper()
+ seen = map[string]bool{}
+ fset := token.NewFileSet()
+ for _, src := range sources {
+ f, err := parser.ParseFile(fset, src, nil, parser.SkipObjectResolution)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range plan3Declarations(f) {
+ key := d.kind + " " + d.qualified
+ if plan3MachineryBaseline[key] {
+ seen[key] = true
+ continue
+ }
+ if plan3SharedSeams[d.name] {
+ continue
+ }
+ at := fset.Position(d.pos).String() + ": " + key + ": "
+ if plan3ReleaseInventory.MatchString(d.name) && !plan3GroupStarted("R") {
+ problems = append(problems, at+"release machinery before group R has started")
+ }
+ if plan3WorkerInventory.MatchString(d.name) && !plan3GroupStarted("W") {
+ problems = append(problems, at+"worker machinery before group W has started")
+ }
+ }
+ }
+ sort.Strings(problems)
+ return problems, seen
+}
+
+type plan3Decl struct {
+ kind, name, qualified string
+ pos token.Pos
+}
+
+// plan3Declarations is every package-level name f declares: functions,
+// methods, types, vars and consts, and the struct fields and interface
+// methods of its types, each field or method with its owner.
+func plan3Declarations(f *ast.File) []plan3Decl {
+ var out []plan3Decl
+ add := func(kind, owner string, id *ast.Ident) {
+ if id == nil || id.Name == "_" {
+ return
+ }
+ q := id.Name
+ if owner != "" {
+ q = owner + "." + id.Name
+ }
+ out = append(out, plan3Decl{kind: kind, name: id.Name, qualified: q, pos: id.Pos()})
+ }
+ members := func(owner string, typ ast.Expr) {
+ ast.Inspect(typ, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.StructType:
+ for _, fl := range x.Fields.List {
+ for _, id := range fl.Names {
+ add("field", owner, id)
+ }
+ }
+ case *ast.InterfaceType:
+ for _, m := range x.Methods.List {
+ for _, id := range m.Names {
+ add("method", owner, id)
+ }
+ }
+ }
+ return true
+ })
+ }
+ for _, decl := range f.Decls {
+ switch d := decl.(type) {
+ case *ast.FuncDecl:
+ if d.Recv != nil && len(d.Recv.List) > 0 {
+ add("method", receiverName(d.Recv.List[0].Type), d.Name)
+ } else {
+ add("func", "", d.Name)
+ }
+ case *ast.GenDecl:
+ for _, spec := range d.Specs {
+ switch sp := spec.(type) {
+ case *ast.TypeSpec:
+ add("type", "", sp.Name)
+ members(sp.Name.Name, sp.Type)
+ case *ast.ValueSpec:
+ for _, id := range sp.Names {
+ add(d.Tok.String(), "", id)
+ }
+ }
+ }
+ }
+ }
+ return out
+}
+
+func receiverName(e ast.Expr) string {
+ switch x := e.(type) {
+ case *ast.StarExpr:
+ return receiverName(x.X)
+ case *ast.IndexExpr:
+ return receiverName(x.X)
+ case *ast.IndexListExpr:
+ return receiverName(x.X)
+ case *ast.Ident:
+ return x.Name
+ }
+ return "?"
+}
diff --git a/testdata/plan3_inventory/added.go b/testdata/plan3_inventory/added.go
new file mode 100644
index 000000000..48a26b669
--- /dev/null
+++ b/testdata/plan3_inventory/added.go
@@ -0,0 +1,20 @@
+// The inventory's fixture (plan3_groups_test.go): a release name and a
+// worker name, which it refuses before their groups start; the baseline's
+// StartRootfsWorker declared on another owner, which the baseline does not
+// cover; and a shared seam of group A and a binary name that matches
+// neither inventory, which pass.
+package activator
+
+type Service struct{}
+
+func runRelease() {}
+
+type rootfsWorkerState struct{}
+
+func (s *Service) StartRootfsWorker() {}
+
+func startCmdUnit() {}
+
+func (s *Service) residentFailure(error) bool { return false }
+
+func releaseBuild() {}