//go:build linux // The launchd service reconciler (install, uninstall, start through Connect, // stop, status) runs here on Linux against a fake launchd and fake daemons, // over generated histories that mix CLI commands with crashes, launchd's // relaunches and spawns, upgrades, standalone daemons, foreign and declared // registrations, disabled overrides, drift, a missing GUI domain, and launchd // output the CLI cannot interpret, each command with an optional fault on one // launchctl call. loginservice.UseLaunchctl makes daemon units launchd jobs on // this platform, so the macOS code paths run in the Linux gate. // // Every step checks the reconciler's invariants: one daemon at most, every // live daemon named by daemon.json, an owned plist that is a generated one, // untouched foreign and declared files, disabled overrides never changed, // launchctl verbs within each command's allowance (no enable, disable, or // kickstart -k; bootstrap and bootout only of the CLI's own label), shutdowns // only of daemons running when the command began, no bootout of a ready // daemon the command did not shut down over HTTP, no direct launch beside a // registration or unknown manager state, no mutation after the file or the // loaded definition changed under the command, the expected verdict for the // world, and a faulted command that a plain retry completes. A real launchd // is exercised only by the manual test/manual/service_darwin.py. package entrypoint import ( "bytes" "context" "io" "maps" "os" "path/filepath" "slices" "strings" "testing" "time" "albedo/cli/internal/localdaemon" "albedo/cli/internal/loginservice" "albedo/cli/internal/property" "albedo/cli/internal/terminal" "albedo/cli/internal/testwire" "pgregory.net/rapid" ) // launchdAllowedVerbs bounds what each command may ask of launchd. Nothing // changes a disabled override, install never boots out, uninstall never // starts, and stopping is always an HTTP shutdown of an observed instance. var launchdAllowedVerbs = map[string][]string{ "install": {"print", "print-disabled", "bootstrap"}, "uninstall": {"print", "print-disabled", "bootout"}, "connect": {"print", "print-disabled", "bootstrap", "kickstart"}, "stop": {"print", "print-disabled"}, "status": {"print", "print-disabled"}, } // launchdFaultVerbs weights the verbs a fault lands on toward the mutations. var launchdFaultVerbs = map[string][]string{ "install": {"print", "print", "print-disabled", "bootstrap", "bootstrap"}, "uninstall": {"print", "print", "print-disabled", "bootout", "bootout"}, "connect": {"print", "print", "print-disabled", "bootstrap", "kickstart", "kickstart"}, "stop": {"print", "print-disabled"}, } // launchdChanges are what can change outside the CLI as a faulted call // replies; the first is none. var launchdChanges = []string{"", "external edit", "concurrent install", "loaded change", "daemon dies at shutdown", "disable"} type launchdWorld struct { t tester rt *rapid.T // draws; nil when a test drives the world without generating manager *fakeLaunchd killed map[*fakeDaemon]bool tally map[string]int home string // launcher is the ALBEDO_DAEMON the CLI captures. launcher string owned string // the CLI's label ownedPath string declared string declPath string // declTarget is where the declaration's symlink points, as home-manager // links its generated plist. declTarget string // changed is the alongside change that fired during the last command, // and changedAt its index in the call log. changed string // foreign holds the bytes, or the link target, of a file at the CLI's // plist path that the CLI does not own. foreign []byte // companion is a regular file under the declared name, not a declaration. companion []byte // commandFile is the CLI's plist when the command began. commandFile []byte // changedFile is what an edit alongside wrote to the CLI's plist. changedFile []byte changedAt int // commandStart is the call log's length when the command began. commandStart int foreignLink bool isDeclared bool declMissing bool // the declaration's file was removed while it stays loaded declDrift bool // the loaded declaration serves another home replace bool // another client starts a run as the daemon drains // changedAfterPublish: a loaded change came after install rewrote the // plist. changedAfterPublish bool // changedInReply: the call that made the change already reported it. changedInReply bool } func launchdTestEnvironment(t *testing.T) { for _, key := range []string{"HOME", "XDG_CONFIG_HOME", "ALBEDO_DAEMON", "ALBEDO_ROOT", "ALBEDO_LAUNCHCTL", "ALBEDO_SYSTEMCTL", "ALBEDO_APPIMAGE_DAEMON", "APPIMAGE"} { t.Setenv(key, "") } // The fake daemons report this build, so no restart is offered. t.Setenv("ALBEDO_BUILD", "fake-build") t.Setenv("ALBEDO_STANDBY", "0") } func TestDaemonServiceLaunchdReconcilerModel(t *testing.T) { checker, err := testwire.NewChecker() if err != nil { t.Fatal(err) } launchdTestEnvironment(t) tally := map[string]int{} property.Check(t, func(rt *rapid.T) { world := newLaunchdWorld(t, rt, rt, rt.Cleanup, checker, tally) defer world.manager.close() world.manager.lingering = rapid.Bool().Draw(rt, "lingering bootout") // Histories begin from an empty home, a home-manager declaration, an // installed agent, one the user booted out, one beside an independent // daemon or a client that restarts it, one launchd will relaunch, or // one whose plist the user removed. opening := rapid.SampledFrom([]string{"empty", "declared", "installed", "installed", "unloaded", "unloaded", "holder", "replacing", "retrying", "fileless"}).Draw(rt, "opening") switch opening { case "declared": world.event("declare") case "installed": world.command("install") case "unloaded", "fileless": world.open(opening) case "holder": world.open("idle") world.event("standalone") case "replacing": world.open("running") world.event("replacement") case "retrying": world.open("idle") world.event("refusal") } for range rapid.IntRange(1, 40).Draw(rt, "steps") { world.step() } for _, failure := range checker.Failures() { rt.Fatalf("OpenAPI: %v", failure) } }) // The generator must keep reaching the interactions the invariants are about. requireReached(t, tally, "install new", "install refresh running", "install refresh idle", "install refresh retrying", "install refused before contact", "install refused", "install refused disabled", "install left drift", "uninstall ok", "uninstall nothing", "uninstall refused", "uninstall beside holder", "uninstall finished removal", "connect bootstrapped", "connect kickstarted", "connect attached", "connect awaited relaunch", "connect refused", "connect refused drift", "connect refused disabled", "connect retry failed", "direct launch", "declared start", "stop ok", "stop refused", "stop refused retrying", "replacement survived", "retry ok", "fault cancel", "crash relaunch", "change preserved", ) } // Every fault one install, uninstall or start can meet on its launchd // mutation and the observations around it, from an empty home and an idle // and a running agent, goes through the same checks as the generated // histories, with each change that can happen alongside. func TestDaemonServiceLaunchdFaultMatrix(t *testing.T) { checker, err := testwire.NewChecker() if err != nil { t.Fatal(err) } launchdTestEnvironment(t) tally := map[string]int{} // Each mutation fails once; print fails at every one of the command's // prints of its own label, which come first in each observation, so odd. cases := []struct{ command, opening, verb string }{ {"install", "empty", "bootstrap"}, {"install", "empty", "print"}, {"install", "empty", "print-disabled"}, {"install", "unloaded", "bootstrap"}, {"install", "idle", "print"}, {"install", "running", "print"}, {"uninstall", "running", "bootout"}, {"uninstall", "running", "print"}, {"uninstall", "idle", "bootout"}, {"uninstall", "idle", "print"}, {"uninstall", "fileless", "bootout"}, {"uninstall", "fileless", "print"}, {"connect", "idle", "kickstart"}, {"connect", "idle", "print"}, {"connect", "unloaded", "bootstrap"}, {"connect", "unloaded", "print"}, {"stop", "running", "print"}, } for _, c := range cases { reached := true for nth := 1; reached; nth += 2 { reached = false if c.verb != "print" && nth > 1 { break } for mode := launchdFaultBefore; mode <= launchdFaultQuiet; mode++ { // print has no effect, so failing it after the effect is // failing it before. if mode == launchdFaultAfter && strings.HasPrefix(c.verb, "print") { continue } changes := []string{""} if mode == launchdFaultQuiet { changes = quietChanges(c.command, nth) } for _, change := range changes { var cleanups []func() world := newLaunchdWorld(t, t, nil, func(f func()) { cleanups = append(cleanups, f) }, checker, tally) world.open(c.opening) // The removal poll after a bootout costs a real interval; // only the bootout faults need it. world.manager.lingering = c.verb == "bootout" if c.command == "install" && c.opening != "empty" { setenv(t, "ALBEDO_ROOT", "/opt/albedo-b") } f := &launchdFault{verb: c.verb, nth: nth, mode: mode} f.alongside = world.alongside(change) t.Logf("%s %s with %v %s", c.opening, c.command, f, change) world.execute(c.command, f, change) // A quiet print the command reaches means a later one // may be reached too. reached = reached || mode == launchdFaultQuiet && world.manager.fired world.checkAlways() world.manager.close() for _, cleanup := range cleanups { cleanup() } } } } } for _, failure := range checker.Failures() { t.Errorf("OpenAPI: %v", failure) } for _, event := range []string{"retry ok", "change preserved", "shutdown failed kept registration", "fault cancel", "uninstall finished removal"} { if tally[event] == 0 { t.Errorf("no matrix case reached %q", event) } } } // quietChanges are the changes a quietly answered call meets in the fault // matrix, without those that cannot differ from another case: a daemon // armed to die at its shutdown dies there whichever call armed it, and only // stop and uninstall shut one down; a disabled override changes nothing for // commands that never start the agent. func quietChanges(command string, nth int) []string { var changes []string for _, change := range launchdChanges[1:] { switch change { case "daemon dies at shutdown": if nth != 1 || command != "uninstall" && command != "stop" { continue } case "disable": if command != "install" && command != "connect" { continue } } changes = append(changes, change) } return changes } func newLaunchdWorld(t *testing.T, tt tester, rt *rapid.T, cleanup func(func()), checker *testwire.Checker, tally map[string]int) *launchdWorld { root, err := os.MkdirTemp(t.TempDir(), "case") if err != nil { tt.Fatal(err) } // The default home, so a declared registration can serve it, under a // user home whose name needs escaping in a plist. userHome := filepath.Join(root, "user with % and $ & <") home := filepath.Join(userHome, ".albedo") bin := filepath.Join(root, "bin") for _, dir := range []string{home, bin} { if err = os.MkdirAll(dir, 0700); err != nil { tt.Fatal(err) } } // A direct launch only records that it happened. launcher := filepath.Join(bin, "albedo-daemon") if err = os.WriteFile(launcher, []byte("#!/bin/sh\ntouch \"$ALBEDO_HOME/direct-launch\"\nexit 1\n"), 0700); err != nil { tt.Fatal(err) } setenv(tt, "HOME", userHome) setenv(tt, "ALBEDO_DAEMON", launcher) setenv(tt, "ALBEDO_ROOT", "/opt/albedo-a") world := &launchdWorld{t: tt, rt: rt, home: home, launcher: launcher, declared: "systems.albedo.daemon", declTarget: filepath.Join(root, "declared.plist"), killed: map[*fakeDaemon]bool{}, tally: tally} // Daemon units are launchd jobs from here on, so ForDaemon names the // LaunchAgent. var manager *fakeLaunchd cleanup(loginservice.UseLaunchctl(func(ctx context.Context, args ...string) (string, string, error) { return manager.run(ctx, args...) })) unit, err := loginservice.ForDaemon(home) if err != nil { tt.Fatal(err) } if !strings.HasSuffix(unit.Path(), filepath.Join("Library", "LaunchAgents", unit.Name()+".plist")) { tt.Fatalf("daemon unit is not a LaunchAgent: %s", unit.Path()) } world.owned, world.ownedPath = unit.Name(), unit.Path() world.declPath = filepath.Join(filepath.Dir(unit.Path()), world.declared+".plist") manager = newFakeLaunchd(checker, home, map[string]string{world.owned: world.ownedPath, world.declared: world.declPath}) world.manager = manager return world } // open prepares a world for the fault matrix without faults. func (w *launchdWorld) open(opening string) { switch opening { case "empty": return case "fileless": // The user removed the plist of a running agent. w.execute("install", nil, "") if err := os.Remove(w.ownedPath); err != nil { w.t.Fatal(err) } return case "unloaded": // The user booted out an idle agent. w.execute("install", nil, "") w.execute("stop", nil, "") w.manager.mu.Lock() *w.manager.job(w.owned) = launchdJob{} w.manager.mu.Unlock() return } w.execute("install", nil, "") if opening == "idle" { w.execute("stop", nil, "") } } // wanted is the plist the CLI should install from the current environment, // worked out from the documented capture rules. func (w *launchdWorld) wanted() (string, map[string]string) { executable, err := os.Executable() if err != nil { w.t.Fatal(err) } return executable, map[string]string{"ALBEDO_HOME": w.home, "PATH": os.Getenv("PATH"), "ALBEDO_ROOT": os.Getenv("ALBEDO_ROOT"), "ALBEDO_DAEMON": os.Getenv("ALBEDO_DAEMON")} } func (w *launchdWorld) matchesWanted(data []byte) bool { document, ok := parsePlist(data) executable, environment := w.wanted() return ok && document.label == w.owned && slices.Equal(document.arguments, []string{executable, "daemon", "--serve"}) && maps.Equal(document.environment, environment) } // generated reports a plist in the CLI's generated shape for its label. func (w *launchdWorld) generated(data []byte) bool { document, ok := parsePlist(data) return ok && document.label == w.owned && len(document.arguments) == 3 && document.arguments[1] == "daemon" && document.arguments[2] == "--serve" && document.environment["ALBEDO_HOME"] == w.home && bytes.Contains(data, []byte("")) } func (w *launchdWorld) step() { commands := []string{"install", "install", "uninstall", "connect", "connect", "connect", "stop", "stop", "status"} events := []string{ "upgrade", "upgrade", "crash", "crash", "standalone", "foreign", "declare", "declared drift", "declaration removed", "unblock", "unblock", "unblock", "disable", "enable", "enable", "drift", "file removed", "spawn", "refusal", "booted out", "booted out", "replacement", "replacement", "replacement", "elsewhere", "no gui", "broken", } choices := commands if rapid.IntRange(0, 2).Draw(w.rt, "event") == 0 { choices = events } kind := rapid.SampledFrom(choices).Draw(w.rt, "operation") if slices.Contains(commands, kind) { w.command(kind) } else { w.event(kind) } w.checkAlways() } // event changes the world the way the user, launchd, or another owner would // between commands. func (w *launchdWorld) event(kind string) { m := w.manager switch kind { case "upgrade": setenv(w.t, "ALBEDO_ROOT", rapid.SampledFrom([]string{"/opt/albedo-a", "/opt/albedo-b"}).Draw(w.rt, "root")) return case "standalone": m.mu.Lock() defer m.mu.Unlock() if len(m.live()) == 0 { if _, err := m.startDaemon(); err != nil { w.t.Fatal(err) } } return case "foreign": if w.foreign != nil || readOptional(w.ownedPath) != nil { return } if err := os.MkdirAll(filepath.Dir(w.ownedPath), 0700); err != nil { w.t.Fatal(err) } if w.foreignLink = rapid.Bool().Draw(w.rt, "symlink"); w.foreignLink { w.foreign = []byte(filepath.Join(w.home, "missing-target")) if err := os.Symlink(string(w.foreign), w.ownedPath); err != nil { w.t.Fatal(err) } } else { w.foreign = []byte("Label" + w.owned + "\n") if err := os.WriteFile(w.ownedPath, w.foreign, 0600); err != nil { w.t.Fatal(err) } } return case "declare": if w.isDeclared || w.companion != nil { return } m.mu.Lock() noDomain := m.noDomain m.mu.Unlock() if noDomain { return } data := w.declaration() if err := os.MkdirAll(filepath.Dir(w.declPath), 0700); err != nil { w.t.Fatal(err) } if err := os.WriteFile(w.declTarget, data, 0600); err != nil { w.t.Fatal(err) } if err := os.Symlink(w.declTarget, w.declPath); err != nil { w.t.Fatal(err) } // home-manager bootstraps its agent at activation. m.mu.Lock() *m.job(w.declared) = launchdJob{loaded: data, path: w.declPath} if !m.disabled[w.declared] && rapid.Bool().Draw(w.rt, "declaration running") { if len(m.live()) == 0 { if err := m.spawn(m.job(w.declared)); err != nil { w.t.Fatal(err) } } } m.mu.Unlock() w.isDeclared = true return case "unblock": // Whoever owns an external registration or state removes it. if w.foreign != nil { _ = os.Remove(w.ownedPath) w.foreign = nil } if w.companion != nil { _ = os.Remove(w.declPath) w.companion = nil } m.mu.Lock() if w.isDeclared && !m.job(w.declared).main.isAlive() { _ = os.Remove(w.declPath) *m.job(w.declared) = launchdJob{} w.isDeclared, w.declMissing, w.declDrift = false, false, false } if owned := m.job(w.owned); owned.loaded != nil && (owned.path != w.ownedPath || readOptional(w.ownedPath) == nil) && !owned.main.isAlive() { // The user boots out a registration the CLI cannot change. *owned = launchdJob{} } m.broken, m.noDomain, w.replace = "", false, false m.mu.Unlock() return } m.mu.Lock() defer m.mu.Unlock() owned, declared := m.job(w.owned), m.job(w.declared) switch kind { case "crash": for _, label := range []string{w.owned, w.declared} { job := m.job(label) if !job.main.isAlive() { continue } w.killed[job.main] = true relaunch := rapid.SampledFrom([]int{0, 2, 3}).Draw(w.rt, "relaunch") recovers := rapid.Bool().Draw(w.rt, "recovers") job.resetRuns = recovers && rapid.Bool().Draw(w.rt, "reset runs") m.crash(label, relaunch, recovers) if relaunch == 0 { w.tally["crash relaunch"]++ } } for _, d := range m.live() { if (owned.main != d && declared.main != d) && rapid.Bool().Draw(w.rt, "crash standalone") { w.killed[d] = true d.exit(true) } } case "refusal": // A run launchd began on its own refused the home. if owned.loaded != nil && !owned.main.isAlive() && owned.relaunch == 0 && !m.disabled[w.owned] { owned.runs++ refused := 75 owned.exit, owned.signal = &refused, nil owned.relaunch = 2 owned.recovers = rapid.Bool().Draw(w.rt, "recovers") owned.resetRuns = owned.recovers && rapid.Bool().Draw(w.rt, "reset runs") } case "spawn": // launchd starts an idle job on its own, as at login. for _, label := range []string{w.owned, w.declared} { job := m.job(label) if job.loaded != nil && !job.main.isAlive() && job.spawning == 0 && job.relaunch == 0 && len(m.live()) == 0 && !m.disabled[label] && job.path == m.labels[label] { if err := m.beginSpawn(job, rapid.IntRange(1, 3).Draw(w.rt, "spawning")); err != nil { w.t.Fatal(err) } break } } case "disable", "enable": label := rapid.SampledFrom([]string{w.owned, w.owned, w.declared}).Draw(w.rt, "override label") m.disabled[label] = kind == "disable" case "declared drift": // The loaded declaration serves another home than this one. if w.isDeclared && declared.loaded != nil { w.declDrift = true declared.loaded = bytes.Replace(declared.loaded, []byte("ALBEDO_HOME\n\t\t"), []byte("ALBEDO_HOME\n\t\t/elsewhere"), 1) } case "declaration removed": if w.isDeclared && !w.declMissing { _ = os.Remove(w.declPath) w.declMissing = true } case "drift": // The loaded definition names a root the file no longer does. if owned.loaded != nil && owned.path == w.ownedPath { owned.loaded = bytes.Replace(owned.loaded, []byte("ALBEDO_ROOT"), []byte("ALBEDO_ROOT/drifted"), 1) } case "file removed": // The user deletes the plist of a loaded agent. if w.foreign == nil && owned.loaded != nil { _ = os.Remove(w.ownedPath) } case "replacement": w.replace = true case "booted out": // The user boots out an idle agent, leaving its plist. if owned.loaded != nil && !owned.main.isAlive() && owned.spawning == 0 { *owned = launchdJob{} } case "elsewhere": // launchd holds this label from a plist the CLI does not own. if owned.loaded == nil && readOptional(w.ownedPath) == nil && w.foreign == nil && !m.noDomain { executable, _ := w.wanted() *owned = launchdJob{loaded: w.plist(executable, ""), path: "/Library/LaunchAgents/" + w.owned + ".plist"} } case "no gui": // Without a GUI session the domain holds no jobs. if owned.loaded == nil && declared.loaded == nil { m.noDomain = true } case "broken": m.broken = rapid.SampledFrom([]string{"status", "malformed"}).Draw(w.rt, "broken") } } // plist renders a LaunchAgent for the CLI's label, independently of the // production renderer, with root as its ALBEDO_ROOT. func (w *launchdWorld) plist(executable, root string) []byte { return []byte("\n\nLabel" + w.owned + "\nProgramArguments" + xmlEscape(executable) + "daemon--serve\nEnvironmentVariablesALBEDO_HOME" + xmlEscape(w.home) + "ALBEDO_ROOT" + root + "PATH" + xmlEscape(os.Getenv("PATH")) + "\n\n") } func xmlEscape(value string) string { return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(value) } // declaration renders the home-manager sample for this home. func (w *launchdWorld) declaration() []byte { executable, _ := w.wanted() sample, err := os.ReadFile("../loginservice/testdata/home-manager/daemon.plist") if err != nil { w.t.Fatal(err) } return []byte(strings.NewReplacer("@HOME@", xmlEscape(w.home), "@EXECUTABLE@", xmlEscape(executable), "@PATH@", xmlEscape(os.Getenv("PATH")), "@LABEL@", w.declared).Replace(string(sample))) } // launchdState is the model's view of the world when a command begins. type launchdState struct { ownedMain, declMain *fakeDaemon shutdowns map[*fakeDaemon]int disabled map[string]bool file, loaded, declLoaded []byte live []*fakeDaemon calls int lock bool registered bool // the CLI's label has a file or a loaded job declFile bool // a file sits under the declared name foreign bool // a file the CLI does not own sits at a name it checks // unknown: launchd answers what the CLI cannot interpret, or holds a // registration for this home it cannot own. unknown bool noDomain bool elsewhere bool fileless bool // the CLI's label is loaded without its file drifted bool // the CLI's loaded job differs from its file retrying bool // the selected job waits for a relaunch recovers bool // relaunching: some job's scheduled relaunch will serve the home. relaunching bool spawning bool replace bool declaredOK bool // a supported declaration is selected // selectedDisabled: the registration a start would use is disabled. selectedDisabled bool } func (w *launchdWorld) state() launchdState { m := w.manager m.mu.Lock() defer m.mu.Unlock() owned, declared := m.job(w.owned), m.job(w.declared) m.settle(owned) m.settle(declared) s := launchdState{file: readOptional(w.ownedPath), loaded: owned.loaded, declLoaded: declared.loaded, live: m.live(), calls: len(m.calls), disabled: maps.Clone(m.disabled), replace: w.replace} if owned.main.isAlive() { s.ownedMain = owned.main } if declared.main.isAlive() { s.declMain = declared.main } _, lockErr := os.Stat(filepath.Join(w.home, "launcher.lock")) s.lock = lockErr == nil s.shutdowns = map[*fakeDaemon]int{} for _, d := range m.daemons { d.mu.Lock() s.shutdowns[d] = d.shutdowns d.mu.Unlock() } _, declErr := os.Lstat(w.declPath) s.declFile = declErr == nil s.foreign = w.foreign != nil || w.companion != nil s.elsewhere = owned.loaded != nil && owned.path != w.ownedPath s.registered = s.file != nil || owned.loaded != nil s.noDomain = m.noDomain declaredRegistered := s.declFile || declared.loaded != nil // Without a GUI domain launchd answers every print alike, so broken // output only shows with one. s.unknown = m.broken != "" && !m.noDomain || s.elsewhere || w.declDrift && declared.loaded != nil || m.noDomain && (s.file != nil || s.declFile) s.fileless = w.foreign == nil && s.file == nil && owned.loaded != nil s.drifted = owned.loaded != nil && s.file != nil && w.foreign == nil && !bytes.Equal(owned.loaded, s.file) selected := owned selectedLabel := w.owned if !s.registered && declaredRegistered { selected, selectedLabel = declared, w.declared s.declaredOK = s.declFile && declared.loaded != nil && w.companion == nil } s.retrying = selected.loaded != nil && selected.relaunch > 0 && !selected.main.isAlive() s.recovers = selected.recovers // Any job launchd is starting on its own may finish during a command. s.spawning = owned.spawning > 0 || declared.spawning > 0 s.relaunching = owned.relaunch > 0 && owned.recovers || declared.relaunch > 0 && declared.recovers s.selectedDisabled = m.disabled[selectedLabel] return s } // unsupported reports a world where the CLI refuses lifecycle changes. func (s launchdState) unsupported() bool { return s.blocked() || s.fileless } // blocked reports a world where even uninstall refuses: everything // unsupported except the CLI's own agent loaded without its plist, whose // removal uninstall finishes. func (s launchdState) blocked() bool { conflict := s.registered && (s.declFile || s.declLoaded != nil) declaredBroken := !s.registered && (s.declFile || s.declLoaded != nil) && !s.declaredOK return s.unknown || s.foreign || conflict || declaredBroken } func (w *launchdWorld) run(command string, f *launchdFault) error { m := w.manager ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() m.mu.Lock() m.fault, m.fired, m.cancel, m.counts, m.patient = f, false, cancel, map[string]int{}, command == "connect" replace := w.replace live := m.live() m.mu.Unlock() for _, d := range live { d.mu.Lock() d.replaceOnDrain = replace d.mu.Unlock() } defer func() { m.mu.Lock() m.fault, m.cancel, m.patient = nil, nil, false m.mu.Unlock() }() // Each command is a fresh CLI process. c := &connector{options: localdaemon.LocalOptions{HomeDir: w.home}, term: &terminal.Service{In: strings.NewReader(""), Out: io.Discard, Err: io.Discard}} switch command { case "install": _, err := c.Install(ctx) return err case "uninstall": _, err := c.Uninstall(ctx) return err case "stop": return c.Stop(ctx, false) case "status": _, err := c.Status(ctx) return err case "connect": connection, err := c.Connect(ctx) if err == nil { connection.HTTPClient().CloseIdleConnections() } return err } panic(command) } // alongside is what changes outside the CLI as a faulted call replies. func (w *launchdWorld) alongside(change string) func() { m := w.manager return func() { owned := m.job(w.owned) applied := false switch change { case "external edit": if data := readOptional(w.ownedPath); data != nil && w.foreign == nil { w.changedFile = append(data, "\n"...) applied = os.WriteFile(w.ownedPath, w.changedFile, 0600) == nil } case "concurrent install": // Another install writes its own valid definition. if data := readOptional(w.ownedPath); data != nil && w.foreign == nil { w.changedFile = bytes.Replace(data, []byte("ALBEDO_ROOT"), []byte("ALBEDO_ROOT/concurrent"), 1) applied = os.WriteFile(w.ownedPath, w.changedFile, 0600) == nil } case "loaded change": // A change the command's first print of its label already // shows is where the command starts, not a change under it. ownedPrint := func(call []string) bool { return call[0] == "print" && strings.HasSuffix(call[len(call)-1], "/"+w.owned) } seen := slices.ContainsFunc(m.calls[w.commandStart:len(m.calls)-1], ownedPrint) // A quiet fault changes the world before its print answers. w.changedInReply = m.fault.mode == launchdFaultQuiet && ownedPrint(m.calls[len(m.calls)-1]) if owned.loaded != nil && seen { w.changedAfterPublish = !bytes.Equal(readOptional(w.ownedPath), w.commandFile) owned.loaded = bytes.Replace(owned.loaded, []byte("ALBEDO_ROOT"), []byte("ALBEDO_ROOT/changed"), 1) applied = true } case "daemon dies at shutdown": // The daemon dies once the CLI has accepted it and asks it to stop. if main := owned.main; main.isAlive() { main.mu.Lock() main.dieAtShutdown = func() { m.mu.Lock() defer m.mu.Unlock() w.killed[main] = true if m.job(w.owned).main == main { m.crash(w.owned, 3, false) } else { main.exit(true) } } main.mu.Unlock() applied = true } case "disable": applied = !m.disabled[w.owned] m.disabled[w.owned] = true } if applied { w.changed, w.changedAt = change, len(m.calls) } } } func (w *launchdWorld) command(command string) { var f *launchdFault change := "" if command != "status" && rapid.IntRange(0, 2).Draw(w.rt, "faulted") == 0 { f = &launchdFault{ verb: rapid.SampledFrom(launchdFaultVerbs[command]).Draw(w.rt, "fault verb"), nth: rapid.SampledFrom([]int{1, 1, 2, 3, 4, 5}).Draw(w.rt, "fault call"), mode: rapid.IntRange(launchdFaultBefore, launchdFaultQuiet).Draw(w.rt, "fault mode"), } change = rapid.SampledFrom(launchdChanges).Draw(w.rt, "alongside") if f.mode == launchdFaultQuiet && change == "" { f.mode = launchdFaultAfter } f.alongside = w.alongside(change) } w.execute(command, f, change) } // execute runs a command with a fault, if any, and checks the outcome. func (w *launchdWorld) execute(command string, f *launchdFault, change string) { w.changed, w.changedFile = "", nil before := w.state() w.commandStart, w.commandFile, w.changedAfterPublish, w.changedInReply = before.calls, before.file, false, false err := w.run(command, f) w.manager.mu.Lock() fired := w.manager.fired for _, d := range w.manager.daemons { d.mu.Lock() d.dieAtShutdown = nil d.mu.Unlock() } w.manager.mu.Unlock() w.t.Logf("%s fault=%v %s fired=%v: %v", command, f, change, fired, err) w.checkCommand(command, before) if !fired { w.checkVerdict(command, before, err) return } if f.mode == launchdFaultCancel { w.tally["fault cancel"]++ } w.checkFaulted(command, before, err, f) w.adoptExternalChange() if err != nil && w.verdict(command, w.state()) == expectOK { // A failed verb leaves state a plain retry completes. again := w.state() retryErr := w.run(command, nil) w.checkCommand(command, again) if retryErr != nil { w.t.Fatalf("retry of %s after %v %s: %v", command, f, change, retryErr) } w.tally["retry ok"]++ w.checkVerdict(command, again, nil) } } // adoptExternalChange records a change made alongside a fault as part of the // world, so later steps hold the CLI to it. func (w *launchdWorld) adoptExternalChange() { if w.changed == "external edit" { if data := readOptional(w.ownedPath); data != nil && bytes.HasSuffix(data, []byte("\n")) { w.foreign, w.foreignLink = data, false } } } // verdict is the model's expected outcome of a command without faults, // derived from the documented launchd service contract. func (w *launchdWorld) verdict(command string, s launchdState) verdict { switch command { case "status": return expectOK case "install", "uninstall": // A file under either name that the CLI does not own refuses before // the launcher lock or launchd is touched. if s.foreign || s.declFile { return expectRefusalBeforeContact } if command == "uninstall" { if !s.registered && s.declLoaded == nil && !s.unknown { return expectOK } if s.blocked() || s.noDomain { return expectRefusal } if s.replace && s.ownedMain != nil { return expectAny } return expectOK } if s.unsupported() || s.noDomain || s.disabled[w.owned] || s.loaded == nil && len(s.live) > 0 { return expectRefusal } return expectOK case "stop": if s.unsupported() { return expectRefusal } if s.retrying && len(s.live) == 0 { return expectRefusal } if s.replace && (s.ownedMain != nil || s.declMain != nil) { return expectRefusal } return expectOK case "connect": if len(s.live) > 0 { return expectOK } if s.unsupported() || s.selectedDisabled || s.drifted { if s.relaunching || s.spawning { // launchd's own relaunch or spawn may land before the // refusal; the CLI then attaches to it. return expectAny } return expectRefusal } if !s.registered && s.declLoaded == nil { // The test's launcher refuses a direct launch. return expectRefusal } if s.retrying && !s.recovers { return expectRefusal } return expectOK } panic(command) } func (w *launchdWorld) checkVerdict(command string, before launchdState, err error) { after := w.state() switch w.verdict(command, before) { case expectRefusalBeforeContact: if err == nil { w.t.Fatalf("%s accepted a registration the CLI does not own", command) } if after.calls != before.calls || !before.lock && after.lock { w.t.Fatalf("%s contacted launchd or took the launcher lock before refusing", command) } w.tally[command+" refused before contact"]++ return case expectRefusal: if err == nil { w.t.Fatalf("%s succeeded where the CLI must refuse", command) } w.tally[command+" refused"]++ verbs := w.callVerbs(before) if command == "connect" { if slices.Contains(verbs, "bootstrap") || slices.Contains(verbs, "kickstart") { if !before.retrying || before.recovers { w.t.Fatalf("connect started a service it could not prove safe: %v", verbs) } } switch { case before.drifted && !before.unsupported(): w.tally["connect refused drift"]++ case before.selectedDisabled && !before.unsupported(): w.tally["connect refused disabled"]++ case before.retrying && !before.recovers && !before.unsupported(): w.tally["connect retry failed"]++ } } if command == "install" && before.disabled[w.owned] && !before.unsupported() { w.tally["install refused disabled"]++ } if command == "stop" && before.retrying && !before.unsupported() { w.tally["stop refused retrying"]++ } if command == "stop" && before.replace && (before.ownedMain != nil || before.declMain != nil) { if len(after.live) == 1 && !slices.Contains(before.live, after.live[0]) { w.tally["replacement survived"]++ } return } if command != "connect" && !before.spawning && !slices.Equal(before.live, after.live) { w.t.Fatalf("refused %s changed the running daemons", command) } if command == "connect" && len(after.live) > 0 && (!before.retrying || before.recovers) { w.t.Fatal("refused connect left a daemon running") } if !bytes.Equal(before.file, after.file) { w.t.Fatalf("refused %s rewrote the plist", command) } if slices.ContainsFunc(verbs, func(verb string) bool { return verb == "bootout" || verb == "bootstrap" }) { w.t.Fatalf("refused %s changed the registration: %v", command, verbs) } return case expectAny: return } if err != nil { w.t.Fatalf("%s failed in a world the CLI owns: %v", command, err) } m := w.manager m.mu.Lock() owned := m.job(w.owned) ownedMain, ownedLoaded := owned.main, owned.loaded m.mu.Unlock() verbs := w.callVerbs(before) switch command { case "install": if !w.matchesWanted(after.file) { w.t.Fatalf("installed plist is not the wanted definition:\n%s", after.file) } if before.loaded == nil { w.tally["install new"]++ if !bytes.Equal(after.loaded, after.file) || !ownedMain.isAlive() || len(after.live) != 1 || after.live[0] != ownedMain { w.t.Fatal("a first installation did not leave its agent loaded and running the daemon") } } else { // launchd keeps what it loaded until the next bootstrap; a // refresh rewrites only the file. if !bytes.Equal(after.loaded, before.loaded) || slices.Contains(verbs, "bootstrap") { w.t.Fatal("refreshing the definition changed the loaded registration") } switch { case before.retrying: w.tally["install refresh retrying"]++ case before.spawning: // install waits for the run launchd began to settle. w.tally["install refresh spawning"]++ case len(before.live) > 0: w.tally["install refresh running"]++ if !slices.Equal(before.live, after.live) { w.t.Fatal("refreshing the definition replaced a running daemon") } default: w.tally["install refresh idle"]++ if len(after.live) != 0 { w.t.Fatal("refreshing the definition started a stopped agent") } } if !bytes.Equal(after.loaded, after.file) { w.tally["install left drift"]++ } } case "uninstall": if !before.registered { w.tally["uninstall nothing"]++ if len(verbs) > 0 && slices.ContainsFunc(verbs, func(verb string) bool { return verb == "bootout" }) { w.t.Fatal("uninstall booted out a label with nothing to remove") } return } w.tally["uninstall ok"]++ if before.fileless { w.tally["uninstall finished removal"]++ } if after.file != nil || ownedLoaded != nil || ownedMain.isAlive() { w.t.Fatal("uninstall left a registration or its daemon") } for _, d := range before.live { if d != before.ownedMain && !d.isAlive() && !w.killed[d] { w.t.Fatal("uninstall ended an independent daemon") } if d != before.ownedMain { w.tally["uninstall beside holder"]++ } } case "stop": w.tally["stop ok"]++ if len(after.live) != 0 { w.t.Fatal("stop left a daemon running") } if !bytes.Equal(before.loaded, after.loaded) || !bytes.Equal(before.declLoaded, after.declLoaded) { w.t.Fatal("stop changed a registration") } case "connect": if len(after.live) != 1 { w.t.Fatalf("connect left %d daemons", len(after.live)) } switch { case len(before.live) > 0: w.tally["connect attached"]++ if !slices.Equal(before.live, after.live) { w.t.Fatal("connect replaced a running daemon") } case before.retrying || before.spawning: w.tally["connect awaited relaunch"]++ if slices.Contains(verbs, "kickstart") || slices.Contains(verbs, "bootstrap") { w.t.Fatal("connect started a job launchd was already starting") } case slices.Contains(verbs, "bootstrap"): w.tally["connect bootstrapped"]++ case slices.Contains(verbs, "kickstart"): w.tally["connect kickstarted"]++ default: w.t.Fatalf("connect started a daemon without launchd: %v", verbs) } if len(before.live) == 0 && after.live[0] != ownedMain && !w.isDeclaredMain(after.live[0]) { w.t.Fatal("connect started a daemon outside the agent") } } } func (w *launchdWorld) isDeclaredMain(d *fakeDaemon) bool { m := w.manager m.mu.Lock() defer m.mu.Unlock() return m.job(w.declared).main == d } func (w *launchdWorld) callsSince(before launchdState) [][]string { m := w.manager m.mu.Lock() defer m.mu.Unlock() return slices.Clone(m.calls[before.calls:]) } func (w *launchdWorld) callVerbs(before launchdState) []string { var verbs []string for _, call := range w.callsSince(before) { verbs = append(verbs, call[0]) } return verbs } func lostShutdowns(d *fakeDaemon) int { d.mu.Lock() defer d.mu.Unlock() return d.lostShutdowns } // checkFaulted: a failed or cancelled change leaves the plist in place and is // never rolled back by deleting state, a failed shutdown is never followed by // a bootout, and a change made under the command stops every later mutation. func (w *launchdWorld) checkFaulted(command string, before launchdState, err error, f *launchdFault) { after := w.state() calls := w.callsSince(before) switch command { case "install": if err != nil && after.file == nil && before.file != nil { w.t.Fatalf("install failed at %v and removed the plist", f) } if err != nil && slices.ContainsFunc(calls, func(call []string) bool { return call[0] == "bootstrap" }) && after.file == nil { w.t.Fatalf("install removed its plist after submitting a bootstrap") } case "uninstall": bootouts := 0 for _, call := range calls { if call[0] == "bootout" { bootouts++ } } if err != nil && bootouts == 1 && after.file == nil && before.file != nil && w.changed == "" && f.verb == "bootout" { w.t.Fatal("uninstall removed the plist after a failed bootout") } if main := before.ownedMain; main != nil && lostShutdowns(main) > 0 { if bootouts > 0 { w.t.Fatal("uninstall booted out the agent after its daemon died before shutdown") } if err == nil { w.t.Fatal("uninstall reported success after a failed shutdown") } if after.file == nil && before.file != nil { w.t.Fatal("uninstall removed the plist after a failed shutdown") } if before.fileless && after.loaded == nil { w.t.Fatal("uninstall booted out an agent whose daemon's shutdown failed") } w.tally["shutdown failed kept registration"]++ } } switch w.changed { case "external edit", "concurrent install", "loaded change": // Connect decides under the launcher lock from a later observation, // which may already read another valid definition; start loads it. if command == "connect" && w.changed == "concurrent install" { break } // A file edit is caught by rereading the file before each mutation. // launchd's loaded definition is seen only through print, so the // window between the last print and a mutation stays open, as // documented; a change a later print showed must stop it. observed := w.changed != "loaded change" || w.changedInReply for _, call := range calls[min(len(calls), w.changedAt-before.calls):] { if call[0] == "print" && strings.HasSuffix(call[len(call)-1], "/"+w.owned) { observed = true } if observed && (call[0] == "bootstrap" || call[0] == "bootout" || call[0] == "kickstart" && w.changed != "loaded change") { w.t.Fatalf("%s submitted %v after a %s", command, call, w.changed) } } // An install that saw the registration change after it published // its plist reports it. For a running agent each observation ends // with an identity re-print whose answer the installer does not // compare; a change shown only there is the documented window. seenByInstall := observed && (before.ownedMain == nil || !w.changedInReply || w.changed != "loaded change") if command == "install" && w.changedAfterPublish && seenByInstall && err == nil { w.t.Fatal("install reported success although the loaded registration changed under it") } if w.changedFile != nil { if !bytes.Equal(after.file, w.changedFile) { w.t.Fatalf("%s overwrote or removed a plist changed during the command", command) } w.tally["change preserved"]++ } } } // checkCommand holds for every command in every world. func (w *launchdWorld) checkCommand(command string, before launchdState) { after := w.state() for _, call := range w.callsSince(before) { if !slices.Contains(launchdAllowedVerbs[command], call[0]) { w.t.Fatalf("%s asked launchd to %v", command, call) } target := call[len(call)-1] switch call[0] { case "bootstrap": if target != w.ownedPath { w.t.Fatalf("%s bootstrapped a plist the CLI does not own: %v", command, call) } case "bootout": if !strings.HasSuffix(target, "/"+w.owned) { w.t.Fatalf("%s booted out a label the CLI does not own: %v", command, call) } case "kickstart": if strings.HasSuffix(target, "/"+w.declared) { w.tally["declared start"]++ } if before.retrying { w.t.Fatalf("%s kickstarted a job launchd was about to relaunch", command) } } } // One label-level bootout at most: a second could end a replacement. bootouts := 0 for _, call := range w.callsSince(before) { if call[0] == "bootout" { bootouts++ } } if bootouts > 1 { w.t.Fatalf("%s booted out %d times", command, bootouts) } // Overrides belong to the user; only a change made alongside a fault // may differ. if w.changed != "disable" && !maps.Equal(before.disabled, after.disabled) { w.t.Fatalf("%s changed a disabled override: %v -> %v", command, before.disabled, after.disabled) } direct := filepath.Join(w.home, "direct-launch") if _, statErr := os.Stat(direct); statErr == nil { _ = os.Remove(direct) w.tally["direct launch"]++ if command != "connect" || before.registered || before.declFile || before.declLoaded != nil || before.unknown || len(before.live) > 0 { w.t.Fatalf("%s launched a daemon directly beside a registration, a daemon, or an unknown launchd state", command) } } for d, count := range after.shutdowns { // stop and uninstall may stop what a spawn they observed started. awaitedSpawn := (command == "stop" || command == "uninstall") && before.spawning if count > before.shutdowns[d] && !slices.Contains(before.live, d) && !awaitedSpawn { w.t.Fatalf("%s shut down %s, which started during the command", command, d.instance) } } // A ready daemon the agent ran is shut down over HTTP before any bootout, // so its kernels survive; bootout may end only a run that started after // the command's last check. if main := before.ownedMain; main != nil && !before.spawning && !main.isAlive() && !w.killed[main] && after.shutdowns[main] == before.shutdowns[main] { w.t.Fatalf("%s ended the agent's ready daemon without an HTTP shutdown", command) } } // checkAlways holds between any two steps. func (w *launchdWorld) checkAlways() { m := w.manager m.mu.Lock() violations := slices.Clone(m.violations) live := m.live() m.mu.Unlock() if len(violations) > 0 { w.t.Fatalf("launchd or daemon contract violated: %v", violations) } if len(live) > 1 { w.t.Fatalf("%d daemons serve one home", len(live)) } if len(live) == 1 { found, err := localdaemon.Discover(context.Background(), w.home) if err != nil || found.Snapshot.InstanceID != live[0].instance { w.t.Fatalf("the live daemon %s is not the one daemon.json names: %+v %v", live[0].instance, found.Snapshot, err) } } switch { case w.foreign != nil && w.foreignLink: if target, err := os.Readlink(w.ownedPath); err != nil || target != string(w.foreign) { w.t.Fatal("a foreign plist symlink changed") } case w.foreign != nil: if data, err := os.ReadFile(w.ownedPath); err != nil || !bytes.Equal(data, w.foreign) { w.t.Fatal("a plist the CLI does not own changed") } default: if data := readOptional(w.ownedPath); data != nil && !w.generated(data) { w.t.Fatalf("the CLI's plist is not a generated definition:\n%s", data) } } if w.companion != nil && !bytes.Equal(readOptional(w.declPath), w.companion) { w.t.Fatal("the companion registration changed") } if w.isDeclared && !w.declMissing { if target, err := os.Readlink(w.declPath); err != nil || target != w.declTarget { w.t.Fatal("the declared registration changed") } } entries, _ := os.ReadDir(filepath.Dir(w.ownedPath)) for _, entry := range entries { if strings.HasPrefix(entry.Name(), ".albedo-unit-") { w.t.Fatalf("a temporary plist was left behind: %s", entry.Name()) } } }