carlos / platform Public

boxself: the self record expires unless the agent rewrites it (#898)

Fix round 2 (Astra, finding 1 not addressed): with the monitor
directory unwritable, neither the new self.json nor the old one's
removal lands, so round 1's withdrawal left the old identity readable.

Per the controller's ruling the record is now self-expiring: Self
carries At, Write refuses a zero At, and the agent rewrites the record
every 5 minutes on every box (from lease.CurrentSelf) until run
returns, waiting for the rewriter to stop. ReadFresh refuses with
ErrStale a record older than maxAge, more than a minute ahead, or
with no time; Task 5's drill reads through it with 15 minutes. The
round-1 remove-on-failure stays.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9b66dd45811fdef63f144883969b2377402816de parent 038807e
5 files changed, +232 −23
  • internal/boxself/boxself.go +41 −7
  • internal/boxself/boxself_test.go +112 −7
  • internal/host/agententry.go +42 −6
  • internal/host/boxself_census_linux_test.go +1 −1
  • internal/host/verifyassign_test.go +36 −2

CI failed — run details

Intent

Attributed to this commit: 13.0 g CO₂e (1,648,731 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on member-backups-2a, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/boxself/boxself.go b/internal/boxself/boxself.go
index ba700965b..f51ae52ef 100644
--- a/internal/boxself/boxself.go
+++ b/internal/boxself/boxself.go
@@ -41,8 +41,20 @@ type Self struct {
// Group is a box its region's group launched (CARLOS_BOX_REFERENCE
// is group): its drill tests only the hosts its assignment names.
Group bool
+ // At is when the agent wrote it. The agent rewrites the record every
+ // few minutes, so a record that stops being rewritten (a write that
+ // fails and cannot withdraw the old one either) goes stale rather
+ // than standing in for this box (ReadFresh).
+ At time.Time
}
+// ErrStale is ReadFresh's refusal of a record too old, from the future,
+// or with no time.
+var ErrStale = errors.New("boxself: the agent's record of this box is not fresh")
+
+// futureSkew is how far ahead of now a record's time may be.
+const futureSkew = time.Minute
+
// Assignment is a group box's view of which box drills each HA host.
type Assignment struct {
// At is when the agent computed it.
@@ -60,9 +72,10 @@ func SelfPath(dataDir string) string { return filepath.Join(dataDir, dirName, se
func AssignmentPath(dataDir string) string { return filepath.Join(dataDir, dirName, assignName) }
type selfDoc struct {
- V int `json:"v"`
- Ref string `json:"ref"`
- Group bool `json:"group"`
+ V int `json:"v"`
+ Ref string `json:"ref"`
+ Group bool `json:"group"`
+ At time.Time `json:"at"`
}
type assignDoc struct {
@@ -88,7 +101,7 @@ func ValidRef(ref string) bool {
}
// Write records s as this box's self, replacing any earlier record. It
-// refuses a reference ValidRef refuses. A write that fails, refused or
+// refuses a reference ValidRef refuses and a zero At. A write that fails, refused or
// not, also removes any earlier record, so Read finds none rather than a
// reference or group mode this box no longer has; the error then says
// if that removal failed too.
@@ -97,7 +110,7 @@ func Write(dataDir string, s Self) error {
if err == nil {
return nil
}
- if rerr := os.Remove(SelfPath(dataDir)); rerr != nil && !errors.Is(rerr, os.ErrNotExist) {
+ if rerr := remove(SelfPath(dataDir)); rerr != nil && !errors.Is(rerr, os.ErrNotExist) {
return errors.Join(err, fmt.Errorf("boxself: the earlier record could not be removed either: %w", rerr))
}
return err
@@ -107,7 +120,10 @@ func writeSelf(dataDir string, s Self) error {
if !ValidRef(s.Ref) {
return fmt.Errorf("boxself: %q is not a box reference", s.Ref)
}
- body, err := json.Marshal(selfDoc{V: 1, Ref: s.Ref, Group: s.Group})
+ if s.At.IsZero() {
+ return errors.New("boxself: a record with no time")
+ }
+ body, err := json.Marshal(selfDoc{V: 1, Ref: s.Ref, Group: s.Group, At: s.At.UTC()})
if err != nil {
return err
}
@@ -128,7 +144,22 @@ func Read(dataDir string) (Self, error) {
if !ValidRef(d.Ref) {
return Self{}, fmt.Errorf("boxself: %s names %q, which is not a box reference", SelfPath(dataDir), d.Ref)
}
- return Self{Ref: d.Ref, Group: d.Group}, nil
+ return Self{Ref: d.Ref, Group: d.Group, At: d.At}, nil
+}
+
+// ReadFresh is Read, refusing with ErrStale a record whose time is zero,
+// more than maxAge before now, or more than a minute after it. The drill
+// reads its box's self through it: a record the agent has stopped
+// rewriting names no box.
+func ReadFresh(dataDir string, now time.Time, maxAge time.Duration) (Self, error) {
+ s, err := Read(dataDir)
+ if err != nil {
+ return Self{}, err
+ }
+ if s.At.IsZero() || now.Sub(s.At) > maxAge || s.At.Sub(now) > futureSkew {
+ return Self{}, fmt.Errorf("%w: %s was written at %s, now is %s, the limit %s", ErrStale, SelfPath(dataDir), s.At.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), maxAge)
+ }
+ return s, nil
}
// WriteAssignment records a, replacing any earlier assignment. It refuses
@@ -194,6 +225,9 @@ func checkAssignment(a Assignment) error {
return nil
}
+// remove is os.Remove; a test makes it fail.
+var remove = os.Remove
+
// readStrict decodes the one JSON value at path into v, refusing unknown
// fields, a wrong type and anything after the value.
func readStrict(path string, v any) error {
diff --git a/internal/boxself/boxself_test.go b/internal/boxself/boxself_test.go
index e4d5fe34a..b10944343 100644
--- a/internal/boxself/boxself_test.go
+++ b/internal/boxself/boxself_test.go
@@ -2,22 +2,28 @@ package boxself
import (
"errors"
+ "fmt"
"os"
"path/filepath"
"reflect"
+ "runtime"
"strings"
"testing"
"time"
)
+var selfAt = time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC)
+
+func sameSelf(a, b Self) bool { return a.Ref == b.Ref && a.Group == b.Group && a.At.Equal(b.At) }
+
func TestBoxSelfRoundTrip(t *testing.T) {
- for _, s := range []Self{{Ref: "jolly-otter"}, {Ref: "g-0123456789abcdef0123", Group: true}} {
+ for _, s := range []Self{{Ref: "jolly-otter", At: selfAt}, {Ref: "g-0123456789abcdef0123", Group: true, At: selfAt}} {
dir := t.TempDir()
if err := Write(dir, s); err != nil {
t.Fatal(err)
}
got, err := Read(dir)
- if err != nil || got != s {
+ if err != nil || !sameSelf(got, s) {
t.Fatalf("read %+v, %v; want %+v", got, err, s)
}
fi, err := os.Stat(filepath.Join(dir, "monitor", "self.json"))
@@ -36,7 +42,7 @@ func TestBoxSelfRoundTrip(t *testing.T) {
if err := Write(dir, s); err != nil {
t.Fatal(err)
}
- if got, _ := Read(dir); got != s {
+ if got, _ := Read(dir); !sameSelf(got, s) {
t.Fatalf("rewrite read %+v, want %+v", got, s)
}
entries, _ := os.ReadDir(filepath.Join(dir, "monitor"))
@@ -58,13 +64,16 @@ func TestBoxSelfReadMissing(t *testing.T) {
func TestBoxSelfRefusesEmpty(t *testing.T) {
for _, ref := range []string{"", " ", "a/b", "..", ".", "a b", "a\nb", "a\\b", strings.Repeat("x", 129)} {
dir := t.TempDir()
- if err := Write(dir, Self{Ref: ref}); err == nil {
+ if err := Write(dir, Self{Ref: ref, At: selfAt}); err == nil {
t.Fatalf("wrote ref %q", ref)
}
if _, err := os.Stat(filepath.Join(dir, "monitor", "self.json")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("ref %q left a file: %v", ref, err)
}
}
+ if err := Write(t.TempDir(), Self{Ref: "jolly-otter"}); err == nil {
+ t.Fatal("wrote a record with no time")
+ }
for name, body := range map[string]string{
"empty ref": `{"v":1,"ref":""}`,
"bad ref": `{"v":1,"ref":"a/b"}`,
@@ -148,16 +157,16 @@ func TestAssignmentRoundTrip(t *testing.T) {
// self to read, never the previous one, so the drill refuses rather than
// publish under an old reference or the old group mode.
func TestBoxSelfFailedWriteWithdrawsTheOldSelf(t *testing.T) {
- old := Self{Ref: "g-0123456789abcdef0123", Group: true}
+ old := Self{Ref: "g-0123456789abcdef0123", Group: true, At: selfAt}
for name, fail := range map[string]func(dir string) Self{
// The new reference is refused before anything is written.
- "refused ref": func(string) Self { return Self{Ref: ""} },
+ "refused ref": func(string) Self { return Self{Ref: "", At: selfAt} },
// The scratch file cannot be created: a directory holds its name.
"scratch blocked": func(dir string) Self {
if err := os.MkdirAll(filepath.Join(SelfPath(dir)+".tmp", "x"), 0o755); err != nil {
t.Fatal(err)
}
- return Self{Ref: "jolly-otter"}
+ return Self{Ref: "jolly-otter", At: selfAt}
},
} {
t.Run(name, func(t *testing.T) {
@@ -174,3 +183,99 @@ func TestBoxSelfFailedWriteWithdrawsTheOldSelf(t *testing.T) {
})
}
}
+
+func TestBoxSelfReadFresh(t *testing.T) {
+ now := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC)
+ for _, tc := range []struct {
+ name string
+ at time.Time
+ fresh bool
+ }{
+ {"a minute old", now.Add(-time.Minute), true},
+ {"at the limit", now.Add(-15 * time.Minute), true},
+ {"past the limit", now.Add(-15*time.Minute - time.Second), false},
+ {"twenty minutes old", now.Add(-20 * time.Minute), false},
+ {"a minute ahead", now.Add(time.Minute), true},
+ {"more than a minute ahead", now.Add(time.Minute + time.Second), false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ want := Self{Ref: "jolly-otter", At: tc.at}
+ if err := Write(dir, want); err != nil {
+ t.Fatal(err)
+ }
+ got, err := ReadFresh(dir, now, 15*time.Minute)
+ if tc.fresh && (err != nil || !sameSelf(got, want)) {
+ t.Fatalf("ReadFresh = %+v, %v; want %+v", got, err, want)
+ }
+ if !tc.fresh && (!errors.Is(err, ErrStale) || got != (Self{})) {
+ t.Fatalf("ReadFresh = %+v, %v; want ErrStale", got, err)
+ }
+ })
+ }
+ // A record with no time is stale; a missing one is still missing.
+ dir := t.TempDir()
+ _ = os.MkdirAll(filepath.Join(dir, "monitor"), 0o755)
+ if err := os.WriteFile(SelfPath(dir), []byte(`{"v":1,"ref":"jolly-otter"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ReadFresh(dir, now, 15*time.Minute); !errors.Is(err, ErrStale) {
+ t.Fatalf("no time: %v, want ErrStale", err)
+ }
+ if _, err := ReadFresh(t.TempDir(), now, 15*time.Minute); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("missing: %v, want os.ErrNotExist", err)
+ }
+}
+
+// TestBoxSelfStaleWhenWriteAndRemovalFail: when the monitor directory
+// takes no write, neither the new record nor the old one's removal
+// lands, and the old record stays readable. It is stale by then, so the
+// drill (ReadFresh) refuses it.
+func TestBoxSelfStaleWhenWriteAndRemovalFail(t *testing.T) {
+ now := time.Now()
+ old := Self{Ref: "g-0123456789abcdef0123", Group: true, At: now.Add(-20 * time.Minute)}
+ check := func(t *testing.T, dir string, writeErr error) {
+ t.Helper()
+ if writeErr == nil {
+ t.Fatal("the replacement write succeeded")
+ }
+ if s, err := ReadFresh(dir, now, 15*time.Minute); !errors.Is(err, ErrStale) {
+ t.Fatalf("ReadFresh = %+v, %v; want ErrStale", s, err)
+ }
+ }
+ t.Run("unwritable directory", func(t *testing.T) {
+ if os.Geteuid() == 0 || runtime.GOOS == "windows" {
+ t.Skip("root, or Windows, writes through a 0555 directory; the seam case covers it")
+ }
+ dir := t.TempDir()
+ if err := Write(dir, old); err != nil {
+ t.Fatal(err)
+ }
+ mon := filepath.Join(dir, "monitor")
+ if err := os.Chmod(mon, 0o555); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.Chmod(mon, 0o755) })
+ err := Write(dir, Self{Ref: "jolly-otter", At: now})
+ if !strings.Contains(fmt.Sprint(err), "could not be removed") {
+ t.Fatalf("write error %v does not report the failed removal", err)
+ }
+ if s, rerr := Read(dir); rerr != nil || !sameSelf(s, old) {
+ t.Fatalf("the old record should still be there for this case to mean anything: %+v %v", s, rerr)
+ }
+ check(t, dir, err)
+ })
+ t.Run("removal fails through the seam", func(t *testing.T) {
+ dir := t.TempDir()
+ if err := Write(dir, old); err != nil {
+ t.Fatal(err)
+ }
+ was := remove
+ remove = func(string) error { return errors.New("read-only file system") }
+ t.Cleanup(func() { remove = was })
+ if err := os.MkdirAll(filepath.Join(SelfPath(dir)+".tmp", "x"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ check(t, dir, Write(dir, Self{Ref: "jolly-otter", At: now}))
+ })
+}
diff --git a/internal/host/agententry.go b/internal/host/agententry.go
index 3ae2123c5..1085f735c 100644
--- a/internal/host/agententry.go
+++ b/internal/host/agententry.go
@@ -35,7 +35,8 @@ func groupReferenceBackoff(n int) time.Duration {
// this process writes belongs to (lease.SetSelf with identity's answer,
// read after the wait so a group box's reference is resolved), and starts
// the agent (run). Beside the lease's self it records the same reference
-// for the nightly restore drill (boxself.Write).
+// for the nightly restore drill (boxself.Write), and rewrites it every
+// boxSelfEvery until run returns.
func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration,
logf func(string, ...any), identity func() hafresh.Self, run func()) {
if groupReferenced(getenv) {
@@ -50,13 +51,48 @@ func agentEntry(getenv func(string) string, resolve func() (string, error), back
lease.SetSelf(self)
logf("agent: lease locks name this box %s", hafresh.OwnerFor(self, os.Getpid(), false))
// The nightly restore drill publishes under this same reference and
- // cannot work it out itself (boxself). A failed write is logged and
- // removes any earlier record, so the drill finds none and refuses to
- // run rather than publish under a reference this box no longer has.
- if err := boxself.Write(dataDirFrom(getenv), boxself.Self{Ref: self.Ref, Group: groupReferenced(getenv)}); err != nil {
+ // cannot work it out itself (boxself). The record is written now and
+ // every boxSelfEvery while the agent runs, so one that can no longer
+ // be written goes stale and the drill (boxself.ReadFresh) refuses it;
+ // a failed write also removes the earlier record where it can.
+ selfCtx, stopSelf := context.WithCancel(context.Background())
+ publish := func() { publishBoxSelf(dataDirFrom(getenv), groupReferenced(getenv), time.Now(), logf) }
+ publish()
+ rewriting := make(chan struct{})
+ go func() {
+ defer close(rewriting)
+ everyTick(selfCtx, boxSelfEvery, publish)
+ }()
+ defer func() {
+ stopSelf()
+ <-rewriting
+ }()
+ run()
+}
+
+// boxSelfEvery is how often the agent rewrites its record for the drill.
+var boxSelfEvery = 5 * time.Minute
+
+// publishBoxSelf records the reference the lease names now (lease.
+// CurrentSelf) for the drill, logging a failure.
+func publishBoxSelf(dataDir string, group bool, now time.Time, logf func(string, ...any)) {
+ if err := boxself.Write(dataDir, boxself.Self{Ref: lease.CurrentSelf().Ref, Group: group, At: now}); err != nil {
logf("agent: the restore drill's record of this box could not be written: %v", err)
}
- run()
+}
+
+// everyTick calls f every d until ctx ends.
+func everyTick(ctx context.Context, d time.Duration, f func()) {
+ t := time.NewTicker(d)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ f()
+ }
+ }
}
// awaitGroupReference asks resolve until it answers, waiting backoff(n)
diff --git a/internal/host/boxself_census_linux_test.go b/internal/host/boxself_census_linux_test.go
index 14599c0d5..c4ac30ad8 100644
--- a/internal/host/boxself_census_linux_test.go
+++ b/internal/host/boxself_census_linux_test.go
@@ -19,7 +19,7 @@ import (
// files, so a claim census over the data dir does not refuse them.
func TestBoxSelfFilesInClaimCensus(t *testing.T) {
data, opt, units := t.TempDir(), t.TempDir(), t.TempDir()
- if err := boxself.Write(data, boxself.Self{Ref: "g-0123456789abcdef0123", Group: true}); err != nil {
+ if err := boxself.Write(data, boxself.Self{Ref: "g-0123456789abcdef0123", Group: true, At: time.Now()}); err != nil {
t.Fatal(err)
}
if err := boxself.WriteAssignment(data, boxself.Assignment{At: time.Now(), Hosts: map[string]string{"shop.example.com": "g-0123456789abcdef0123"}}); err != nil {
diff --git a/internal/host/verifyassign_test.go b/internal/host/verifyassign_test.go
index 99693dfe0..b38283dfd 100644
--- a/internal/host/verifyassign_test.go
+++ b/internal/host/verifyassign_test.go
@@ -54,7 +54,7 @@ func TestAgentWritesSelfRefEqualToLeaseRef(t *testing.T) {
if !ran {
t.Fatal("the agent did not start")
}
- got, err := boxself.Read(dir)
+ got, err := boxself.ReadFresh(dir, time.Now(), 15*time.Minute)
if err != nil {
t.Fatal(err)
}
@@ -71,12 +71,13 @@ func TestAgentWritesSelfRefEqualToLeaseRef(t *testing.T) {
// to publish under.
func TestAgentFailedSelfRefLeavesNoIdentity(t *testing.T) {
dir := t.TempDir()
- if err := boxself.Write(dir, boxself.Self{Ref: "g-0123456789abcdef0123", Group: true}); err != nil {
+ if err := boxself.Write(dir, boxself.Self{Ref: "g-0123456789abcdef0123", Group: true, At: time.Now()}); err != nil {
t.Fatal(err)
}
var lines []string
logf := func(f string, args ...any) { lines = append(lines, fmt.Sprintf(f, args...)) }
// An identity with no reference: the write is refused.
+ lease.SetSelf(hafresh.Self{})
agentEntry(groupEnv(map[string]string{"CARLOS_DATA_DIR": dir}), resolveGroupBoxReference, nil, logf, func() hafresh.Self { return hafresh.Self{} }, func() {})
if s, err := boxself.Read(dir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("after a failed write Read = %+v, %v; want os.ErrNotExist", s, err)
@@ -86,6 +87,39 @@ func TestAgentFailedSelfRefLeavesNoIdentity(t *testing.T) {
}
}
+// TestAgentRewritesSelfRefUntilItStops: the record is rewritten on every
+// tick while the agent runs, so it stays fresh, and no longer once run
+// returns.
+func TestAgentRewritesSelfRefUntilItStops(t *testing.T) {
+ was := boxSelfEvery
+ boxSelfEvery = 10 * time.Millisecond
+ t.Cleanup(func() { boxSelfEvery = was })
+ dir := t.TempDir()
+ at := func() time.Time {
+ s, err := boxself.Read(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s.At
+ }
+ agentEntry(groupEnv(map[string]string{"CARLOS_DATA_DIR": dir}), resolveGroupBoxReference, nil, func(string, ...any) {},
+ func() hafresh.Self { return hafresh.Self{Ref: "jolly-otter"} }, func() {
+ first := at()
+ deadline := time.Now().Add(5 * time.Second)
+ for !at().After(first) {
+ if time.Now().After(deadline) {
+ t.Fatal("the record was not rewritten")
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ })
+ last := at()
+ time.Sleep(50 * time.Millisecond)
+ if !at().Equal(last) {
+ t.Fatal("the record was rewritten after the agent stopped")
+ }
+}
+
func TestComputeAssignment(t *testing.T) {
now := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC)
serving := func(refs ...string) []boxchoice.Candidate {