Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Address review: rollback, Homebrew path, load failures, heartbeat scope

shukieshah3e935bbfe4bf
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index 9f1a6d9b..1b98d97d 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -572,6 +572,9 @@ func writeInventorySnapshotEvents(cfg endpointconfig.Config, settings endpointco
"snapshot_digest": digest,
"previous_snapshot_digest": previousDigest,
"counts": counts,
+ // Metadata only (mode and hashes). It is what distinguishes a liveness heartbeat written
+ // with nobody at the console from one for an unchanged inventory.
+ "user_scope": result.UserScope,
}
if previousDigest == "" {
inventoryMeta["change_reason"] = "initial"
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.go
index a72760b5..5a730a63 100644
--- a/cli/beacon/cmd/endpoint_test.go
+++ b/cli/beacon/cmd/endpoint_test.go
@@ -1216,6 +1216,9 @@ func TestScheduledHeartbeatInSystemModeScansTheConsoleUsersHome(t *testing.T) {
if strings.Count(string(data), "inventory.heartbeat") != 2 || strings.Count(string(data), "inventory.snapshot") != 1 {
t.Fatalf("expected a second heartbeat and no second snapshot: %s", data)
}
+ if !strings.Contains(string(data), `"mode":"no_console_user"`) {
+ t.Fatalf("the liveness heartbeat must say nobody was at the console: %s", data)
+ }
stateAfter, _ := endpointinventory.ReadState(endpointinventory.StatePathForLog(logPath, false))
// last_emitted_at has second resolution, so only the digest is a reliable assertion here.
if stateAfter.LastSnapshotDigest != stateBefore.LastSnapshotDigest || stateAfter.LastEmittedAt == "" {
diff --git a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
index 7c8ab9d2..9e1f965b 100644
--- a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
+++ b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
@@ -1,6 +1,7 @@
package lifecycle
import (
+ "errors"
"os"
"path/filepath"
"runtime"
@@ -16,26 +17,37 @@ type recordingInventoryJob struct {
calls *[]string
supported bool
unitPath string
+ loadErr error
}
func (r recordingInventoryJob) Supported() bool { return r.supported }
func (r recordingInventoryJob) UnsupportedReason() string { return "no scheduler in this test" }
func (r recordingInventoryJob) UnitPath() (string, error) { return r.unitPath, nil }
+func (r recordingInventoryJob) UnitPaths() []string {
+ return []string{r.unitPath, r.unitPath + ".service"}
+}
func (r recordingInventoryJob) WriteUnit(program, logPath string) (string, error) {
*r.calls = append(*r.calls, "write "+program+" "+logPath)
return r.unitPath, nil
}
-func (r recordingInventoryJob) Load() error { *r.calls = append(*r.calls, "load"); return nil }
+func (r recordingInventoryJob) Load() error {
+ *r.calls = append(*r.calls, "load")
+ return r.loadErr
+}
func (r recordingInventoryJob) Unload() error { *r.calls = append(*r.calls, "unload"); return nil }
func (r recordingInventoryJob) RemoveUnits() { *r.calls = append(*r.calls, "remove") }
func (r recordingInventoryJob) Status() service.Status { return service.Status{} }
func installFakeInventoryJob(t *testing.T, supported bool) *[]string {
+ return installFakeInventoryJobWithLoadError(t, supported, nil)
+}
+
+func installFakeInventoryJobWithLoadError(t *testing.T, supported bool, loadErr error) *[]string {
t.Helper()
calls := &[]string{}
old := newInventoryJob
newInventoryJob = func(userMode bool, kind service.Kind) inventoryJobController {
- return recordingInventoryJob{calls: calls, supported: supported, unitPath: "/fake/" + InventoryUnitName(userMode)}
+ return recordingInventoryJob{calls: calls, supported: supported, unitPath: "/fake/" + InventoryUnitName(userMode), loadErr: loadErr}
}
t.Cleanup(func() { newInventoryJob = old })
return calls
@@ -238,3 +250,58 @@ func TestUninstallRemovesTheInventoryJobForTheMode(t *testing.T) {
t.Fatalf("uninstall should remove the user-mode inventory job once, got %v", removedFor)
}
}
+
+// A job that was loaded by an install that then fails must be unloaded by the rollback, or the
+// scheduler keeps a unit registered against config that no longer exists.
+func TestRollbackUnloadsALoadedInventoryJob(t *testing.T) {
+ calls := &[]string{}
+ job := recordingInventoryJob{calls: calls, supported: true, unitPath: filepath.Join(t.TempDir(), "x.plist")}
+ tx := newInstallRollback(service.Manager{UserMode: true, Kind: service.KindSupervised})
+ tx.InventoryJob = job
+ tx.InventoryLoaded = true
+ tx.Rollback(Manifest{})
+ if strings.Join(*calls, ",") != "unload" {
+ t.Fatalf("rollback calls = %q, want unload", *calls)
+ }
+ *calls = nil
+ tx.InventoryLoaded = false
+ tx.Rollback(Manifest{})
+ if len(*calls) != 0 {
+ t.Fatalf("rollback must not unload a job it never loaded: %q", *calls)
+ }
+}
+
+func TestReconcileSurfacesARefusedLoad(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ installFakeInventoryJobWithLoadError(t, true, errors.New("enable --now refused"))
+ result, err := ReconcileInventoryJob(InventoryJobOptions{UserMode: true, Program: "/usr/local/bin/beacon", Load: true})
+ if err == nil || result.Loaded {
+ t.Fatalf("a refused load must surface: result=%+v err=%v", result, err)
+ }
+}
+
+func TestStableProgramPathPrefersTheLinkedHomebrewBinary(t *testing.T) {
+ prefix := t.TempDir()
+ keg := filepath.Join(prefix, "Cellar", "beacon", "1.3.11", "bin", "beacon")
+ linked := filepath.Join(prefix, "bin", "beacon")
+ for _, p := range []string{keg, linked} {
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if got := stableProgramPath(keg); got != linked {
+ t.Fatalf("stableProgramPath(keg) = %q, want the linked %q", got, linked)
+ }
+ if got := stableProgramPath("/opt/beacon/bin/beacon"); got != "/opt/beacon/bin/beacon" {
+ t.Fatalf("non-Homebrew path must pass through, got %q", got)
+ }
+ if err := os.Remove(linked); err != nil {
+ t.Fatal(err)
+ }
+ if got := stableProgramPath(keg); got != keg {
+ t.Fatalf("without a linked binary the keg path stays, got %q", got)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 17950838..ef3f5197 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -48,6 +48,7 @@ type inventoryJobController interface {
Supported() bool
UnsupportedReason() string
UnitPath() (string, error)
+ UnitPaths() []string
WriteUnit(program, logPath string) (string, error)
Load() error
Unload() error
@@ -131,10 +132,7 @@ func inventoryEnabledFromConfigFile(path string) bool {
// package postinstall that is /opt/beacon/bin/beacon; under Homebrew it is the keg's binary.
func DefaultInventoryJobProgram(userMode bool) string {
if exe, err := os.Executable(); err == nil {
- if resolved, err := filepath.EvalSymlinks(exe); err == nil {
- return resolved
- }
- return exe
+ return stableProgramPath(exe)
}
if !userMode {
return selfupdate.SystemBeaconPath()
@@ -142,6 +140,19 @@ func DefaultInventoryJobProgram(userMode bool) string {
return "beacon"
}
+// stableProgramPath keeps the scheduled unit pointing at a path that survives upgrades. A
+// Homebrew binary reports its versioned Cellar keg, which `brew upgrade` deletes; the linked
+// `<prefix>/bin/beacon` is the path that keeps resolving, so that is what the unit records.
+func stableProgramPath(exe string) string {
+ if idx := strings.Index(exe, string(filepath.Separator)+"Cellar"+string(filepath.Separator)); idx > 0 {
+ linked := filepath.Join(exe[:idx], "bin", filepath.Base(exe))
+ if _, err := os.Stat(linked); err == nil {
+ return linked
+ }
+ }
+ return exe
+}
+
// InventoryHeartbeatStatus is the status view of the scheduled inventory job.
type InventoryHeartbeatStatus struct {
Enabled bool `json:"enabled"`
@@ -283,8 +294,12 @@ type serviceController interface {
}
type installRollback struct {
- Manager serviceController
- ServiceLoaded bool
+ // InventoryJob and InventoryLoaded let a failed install unload the scheduled inventory job
+ // it started, so the scheduler is not left registered against rolled-back config.
+ InventoryJob inventoryJobController
+ InventoryLoaded bool
+ Manager serviceController
+ ServiceLoaded bool
// ServiceWasRunning records whether a collector was already up when this install began.
//
// It decides what rollback owes the machine. Unloading is right for a service this transaction
@@ -332,6 +347,9 @@ func (r *installRollback) Rollback(manifest Manifest) {
if r.ServiceLoaded {
_ = r.Manager.Unload()
}
+ if r.InventoryLoaded && r.InventoryJob != nil {
+ _ = r.InventoryJob.Unload()
+ }
restoreBackups(manifest.Backups)
for i := len(r.files) - 1; i >= 0; i-- {
@@ -424,9 +442,10 @@ func Install(opts InstallOptions) (InstallResult, error) {
// tracked for rollback but kept out of the manifest, like the updater's, and a host with no
// scheduler does not fail the install: it is reported and the endpoint still collects.
inventoryJob := newInventoryJob(cfg.UserMode, opts.ServiceKind)
- if path, err := inventoryJob.UnitPath(); err == nil {
+ for _, path := range inventoryJob.UnitPaths() {
tx.Track(path)
}
+ tx.InventoryJob = inventoryJob
inventoryResult, inventoryErr := reconcileInventoryJobWith(inventoryJob, InventoryJobOptions{
UserMode: cfg.UserMode,
Kind: opts.ServiceKind,
@@ -434,9 +453,12 @@ func Install(opts InstallOptions) (InstallResult, error) {
LogPath: cfg.LogPath,
Load: opts.StartService,
})
+ tx.InventoryLoaded = inventoryResult.Loaded
inventoryDetail := inventoryResult.Skipped
if inventoryErr != nil {
- inventoryDetail = inventoryErr.Error()
+ // Written but not enabled is not installed: report the failure, not the unit path.
+ inventoryResult.UnitPath = ""
+ inventoryDetail = "scheduled inventory job: " + inventoryErr.Error()
}
harnessPaths, err := configureHarnesses(cfg)