member backups 2a: box self ref and group drill assignment (#898)
The agent records, under <data>/monitor/, the reference its lease locks name (self.json, written in agentEntry beside lease.SetSelf, after the group-reference wait) and, on group boxes, a per-host drill assignment (verify-assign.json) recomputed every 5 minutes until the agent stops. The assignment is boxchoice.HRW over each HA host's Serving set from the same duty view the HA duties read: the SetDutyView closure is now the named dutyView, handed to both through armDutyView. boxchoice.HRW takes dutyHRW's body unchanged; dutyHRW is a one-line wrapper, pinned by golden values. The edge coverage test proves every host has at least one drilling box across steady, adopting, draining, stale, keyless, sidecar and quiet cases, and exactly one where the views agree. Both files are classified in the claim data census so a census over /data does not refuse them. Existing agentEntry tests now use a temp data dir.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/haduties.go+3 −18internal/activator/hrw_golden_test.go+38 −0internal/boxchoice/hrw.go+30 −0internal/boxchoice/hrw_test.go+56 −0internal/boxself/boxself.go+240 −0internal/boxself/boxself_test.go+145 −0internal/edge/drillassign_test.go+209 −0internal/host/agent.go+12 −13internal/host/agententry.go+9 −1internal/host/agententry_test.go+4 −1internal/host/boxself_census_linux_test.go+46 −0internal/host/claimcensus.go+5 −0internal/host/haself_test.go+1 −1internal/host/verifyassign.go+107 −0internal/host/verifyassign_test.go+190 −0
Intent
<task-notification> <task-id>a08fccece1d56a662</task-id> <tool-use-id>toolu_01JxrircCszxXdE3sF1h9Urm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a08fccece1d56a662.output</output-file> <status>completed</status> <summary>Agent "Implement slice 2a Task 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. Both functions are in, and `Agent.check` now calls `ConfirmIdentity` with no change in behaviour. Commit: 8a0dd368 on member-backups-2a, "dbreads: identity bracket as CaptureIdentity/ConfirmIdentity (#898)". Not pushed. Tests: the 3 new tests failed first (undefined names), then `go test ./internal/dbreads -run 'Identity|Agent|Read|Check'` passed (22 top-level tests), with the agent_test.go:31 recreation cases unchanged. gofmt, vet and `go build ./...` are clean. A mutation check (disabling the identity comparison) failed the old recreation case and 3 new cases. Concerns: - `internal/dbreads` is in the root binary's census scope; I left census testdata alone for Task 9. - `CaptureIdentity` returns an empty `Identity` for `record-changed`, so a caller can't bind a verdict to a refused record. - The sandbox's Go cache is read-only, so go commands ran with the sandbox off; `GOCACHE` stayed at its default. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-2a/.superpowers/sdd/2026-11-11-member-backups-slice2a/task-1-report.md</result> <usage><subagent_tokens>70196</subagent_tokens><tool_uses>17</tool_uses><duration_ms>341818</duration_ms></usage> </task-notification>
Attributed to this commit: 9.69 g CO₂e (1,210,352 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/activator/haduties.go b/internal/activator/haduties.go| index 2bdb63f29..669827e18 100644 |
| --- a/internal/activator/haduties.go |
| +++ b/internal/activator/haduties.go |
| @@ -1,9 +1,7 @@ |
| package activator |
| import ( |
| - "bytes" |
| "context" |
| - "crypto/sha256" |
| "slices" |
| "strconv" |
| "strings" |
| @@ -398,22 +396,9 @@ func (a *Service) rememberDutyRelease(ctx context.Context, rt registry.Route, m |
| _ = a.saveDuty(ctx, rt.Host, m.Lifetime, st, DutyState{Basis: DutyLocalRelease}) |
| } |
| -func dutyHRW(host string, refs []string) (string, bool) { |
| - best := "" |
| - var score [32]byte |
| - for _, ref := range refs { |
| - if ref == "" { |
| - continue |
| - } |
| - h := sha256.Sum256([]byte(host + "\x00" + ref)) |
| - cmp := bytes.Compare(h[:], score[:]) |
| - if best == "" || cmp > 0 || (cmp == 0 && ref < best) { |
| - best = ref |
| - score = h |
| - } |
| - } |
| - return best, best != "" |
| -} |
| +// dutyHRW is boxchoice.HRW, kept by this name for the duties' tests and |
| +// the two-box drain witness's linkname. |
| +func dutyHRW(host string, refs []string) (string, bool) { return boxchoice.HRW(host, refs) } |
| func (a *Service) dutyEpoch(ref, iid string) uint64 { |
| a.duties.mu.Lock() |
diff --git a/internal/activator/hrw_golden_test.go b/internal/activator/hrw_golden_test.go| new file mode 100644 |
| index 000000000..aa905485f |
| --- /dev/null |
| +++ b/internal/activator/hrw_golden_test.go |
| @@ -0,0 +1,38 @@ |
| +package activator |
| + |
| +import ( |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| +) |
| + |
| +// TestHRWMatchesDutyHRW pins boxchoice.HRW to the duties' choice: the |
| +// golden winners were taken from dutyHRW before its body moved to |
| +// boxchoice, so the nightly drill's assignment and the HA duties pick the |
| +// same box for a host from the same references. |
| +func TestHRWMatchesDutyHRW(t *testing.T) { |
| + for _, tc := range []struct { |
| + host string |
| + refs []string |
| + want string |
| + ok bool |
| + }{ |
| + {"shop.example.com", []string{"a", "b", "c"}, "c", true}, |
| + {"shop.example.com", []string{"g-0123456789abcdef0123", "g-fedcba9876543210fedc"}, "g-fedcba9876543210fedc", true}, |
| + {"api.example.org", []string{"g-0123456789abcdef0123", "g-fedcba9876543210fedc", "g-00000000000000000000"}, "g-fedcba9876543210fedc", true}, |
| + {"bot.shop.bab.sidecar.internal", []string{"annie", "sophie", "adi"}, "adi", true}, |
| + {"blog.example.net", []string{"", "x", "", "y"}, "y", true}, |
| + {"blog.example.net", []string{"y", "x"}, "y", true}, |
| + {"one.example.com", []string{"solo"}, "solo", true}, |
| + {"none.example.com", []string{""}, "", false}, |
| + {"none.example.com", nil, "", false}, |
| + } { |
| + got, ok := boxchoice.HRW(tc.host, tc.refs) |
| + if got != tc.want || ok != tc.ok { |
| + t.Fatalf("HRW(%q, %q) = %q, %v; want %q, %v", tc.host, tc.refs, got, ok, tc.want, tc.ok) |
| + } |
| + if d, dok := dutyHRW(tc.host, tc.refs); d != got || dok != ok { |
| + t.Fatalf("dutyHRW(%q, %q) = %q, %v; HRW says %q, %v", tc.host, tc.refs, d, dok, got, ok) |
| + } |
| + } |
| +} |
diff --git a/internal/boxchoice/hrw.go b/internal/boxchoice/hrw.go| new file mode 100644 |
| index 000000000..9a3503036 |
| --- /dev/null |
| +++ b/internal/boxchoice/hrw.go |
| @@ -0,0 +1,30 @@ |
| +package boxchoice |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| +) |
| + |
| +// HRW is rendezvous hashing over box references: the reference whose |
| +// sha256(host, NUL, ref) is highest, the smaller reference on a tie, and |
| +// false when refs holds no non-empty reference. The HA duties pick a |
| +// host's duty box with it (activator dutyHRW), and the nightly restore |
| +// drill picks the group box that tests a host with it, from the same |
| +// serving set, so the two agree. Removing a reference moves only the |
| +// hosts it won. |
| +func HRW(host string, refs []string) (string, bool) { |
| + best := "" |
| + var score [32]byte |
| + for _, ref := range refs { |
| + if ref == "" { |
| + continue |
| + } |
| + h := sha256.Sum256([]byte(host + "\x00" + ref)) |
| + cmp := bytes.Compare(h[:], score[:]) |
| + if best == "" || cmp > 0 || (cmp == 0 && ref < best) { |
| + best = ref |
| + score = h |
| + } |
| + } |
| + return best, best != "" |
| +} |
diff --git a/internal/boxchoice/hrw_test.go b/internal/boxchoice/hrw_test.go| new file mode 100644 |
| index 000000000..41aae0ea9 |
| --- /dev/null |
| +++ b/internal/boxchoice/hrw_test.go |
| @@ -0,0 +1,56 @@ |
| +package boxchoice |
| + |
| +import ( |
| + "fmt" |
| + "testing" |
| +) |
| + |
| +// TestHRWAssignsEachHostOnce: over one set of references every host has |
| +// exactly one winner, and removing a reference moves only the hosts it |
| +// won; every other host keeps its winner. |
| +func TestHRWAssignsEachHostOnce(t *testing.T) { |
| + refs := []string{"g-0123456789abcdef0123", "g-fedcba9876543210fedc", "g-00000000000000000000"} |
| + won := map[string]int{} |
| + before := map[string]string{} |
| + for n := range 1000 { |
| + host := fmt.Sprintf("host-%d.example.com", n) |
| + w, ok := HRW(host, refs) |
| + if !ok { |
| + t.Fatalf("%s: no winner", host) |
| + } |
| + // The order the references arrive in does not matter. |
| + if r, _ := HRW(host, []string{refs[2], refs[0], refs[1]}); r != w { |
| + t.Fatalf("%s: winner %s depends on order (%s)", host, w, r) |
| + } |
| + before[host] = w |
| + won[w]++ |
| + } |
| + for _, ref := range refs { |
| + if won[ref] < 250 { |
| + t.Fatalf("%s won %d of 1000 hosts: %v", ref, won[ref], won) |
| + } |
| + } |
| + gone := refs[1] |
| + moved := 0 |
| + for host, w := range before { |
| + after, ok := HRW(host, []string{refs[0], refs[2]}) |
| + if !ok { |
| + t.Fatalf("%s: no winner without %s", host, gone) |
| + } |
| + if w != gone && after != w { |
| + t.Fatalf("%s moved from %s to %s though %s left", host, w, after, gone) |
| + } |
| + if w == gone { |
| + moved++ |
| + } |
| + } |
| + if moved != won[gone] { |
| + t.Fatalf("moved %d, want %d", moved, won[gone]) |
| + } |
| + if _, ok := HRW("shop.example.com", []string{"", ""}); ok { |
| + t.Fatal("empty references have a winner") |
| + } |
| + if _, ok := HRW("shop.example.com", nil); ok { |
| + t.Fatal("no references have a winner") |
| + } |
| +} |
diff --git a/internal/boxself/boxself.go b/internal/boxself/boxself.go| new file mode 100644 |
| index 000000000..c02d88c6a |
| --- /dev/null |
| +++ b/internal/boxself/boxself.go |
| @@ -0,0 +1,240 @@ |
| +// Package boxself is what the long-running agent tells the box's other |
| +// processes about itself, through two small files under |
| +// <data>/monitor/: its own reference (self.json), the label its lease |
| +// locks name and its metrics publish under, and, on a group box, which box |
| +// of the group drills each HA host (verify-assign.json). The nightly |
| +// restore drill (carlos ops hibernate-verify) reads both; it cannot work |
| +// either out for itself. |
| +// |
| +// Both files are written whole (a temp file renamed into place), mode |
| +// 0644, so the drill, which runs as the same user, reads one or the other |
| +// version and never half of one. |
| +package boxself |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "time" |
| + "unicode" |
| +) |
| + |
| +const ( |
| + dirName = "monitor" |
| + selfName = "self.json" |
| + assignName = "verify-assign.json" |
| + // maxRead bounds a read: the assignment names every HA host once. |
| + maxRead = 16 << 20 |
| +) |
| + |
| +// Self is this box as the agent names it. |
| +type Self struct { |
| + // Ref is the box's reference: the label its metrics publish under, |
| + // which is the reference its lease locks name. |
| + Ref string |
| + // 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 |
| +} |
| + |
| +// Assignment is a group box's view of which box drills each HA host. |
| +type Assignment struct { |
| + // At is when the agent computed it. |
| + At time.Time |
| + // Hosts maps each HA host to the reference of the box that drills it. |
| + Hosts map[string]string |
| + // Unknown are the HA hosts whose serving view was not usable or named |
| + // no serving box, sorted. |
| + Unknown []string |
| +} |
| + |
| +// SelfPath and AssignmentPath are the two files under dataDir. |
| +func SelfPath(dataDir string) string { return filepath.Join(dataDir, dirName, selfName) } |
| + |
| +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"` |
| +} |
| + |
| +type assignDoc struct { |
| + V int `json:"v"` |
| + At time.Time `json:"at"` |
| + Hosts map[string]string `json:"hosts"` |
| + Unknown []string `json:"unknown"` |
| +} |
| + |
| +// ValidRef reports whether ref can be a box reference: non-empty, at most |
| +// 128 bytes, printable, with no space, slash or backslash, and not "." or |
| +// "..", so it is safe as one segment of a bucket key or a path. |
| +func ValidRef(ref string) bool { |
| + if ref == "" || len(ref) > 128 || ref == "." || ref == ".." { |
| + return false |
| + } |
| + for _, r := range ref { |
| + if r == '/' || r == '\\' || unicode.IsSpace(r) || !unicode.IsPrint(r) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// Write records s as this box's self, replacing any earlier record. It |
| +// refuses a reference ValidRef refuses, writing nothing. |
| +func Write(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 err != nil { |
| + return err |
| + } |
| + return writeAtomic(SelfPath(dataDir), body) |
| +} |
| + |
| +// Read is the self Write last recorded. An error wrapping os.ErrNotExist |
| +// means the agent has not written one; any other error is a record that |
| +// is not one (wrong version, a reference ValidRef refuses, not JSON). |
| +func Read(dataDir string) (Self, error) { |
| + var d selfDoc |
| + if err := readStrict(SelfPath(dataDir), &d); err != nil { |
| + return Self{}, err |
| + } |
| + if d.V != 1 { |
| + return Self{}, fmt.Errorf("boxself: %s is version %d, want 1", SelfPath(dataDir), d.V) |
| + } |
| + 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 |
| +} |
| + |
| +// WriteAssignment records a, replacing any earlier assignment. It refuses |
| +// an assignment with no time, an empty host or a winner ValidRef refuses. |
| +func WriteAssignment(dataDir string, a Assignment) error { |
| + if err := checkAssignment(a); err != nil { |
| + return err |
| + } |
| + hosts := a.Hosts |
| + if hosts == nil { |
| + hosts = map[string]string{} |
| + } |
| + unknown := slices.Clone(a.Unknown) |
| + if unknown == nil { |
| + unknown = []string{} |
| + } |
| + slices.Sort(unknown) |
| + body, err := json.Marshal(assignDoc{V: 1, At: a.At.UTC(), Hosts: hosts, Unknown: unknown}) |
| + if err != nil { |
| + return err |
| + } |
| + return writeAtomic(AssignmentPath(dataDir), body) |
| +} |
| + |
| +// ReadAssignment is the assignment WriteAssignment last recorded, with |
| +// os.ErrNotExist (wrapped) when there is none: a fixed box, or a group |
| +// box whose agent has not computed one yet. |
| +func ReadAssignment(dataDir string) (Assignment, error) { |
| + var d assignDoc |
| + if err := readStrict(AssignmentPath(dataDir), &d); err != nil { |
| + return Assignment{}, err |
| + } |
| + if d.V != 1 { |
| + return Assignment{}, fmt.Errorf("boxself: %s is version %d, want 1", AssignmentPath(dataDir), d.V) |
| + } |
| + a := Assignment{At: d.At, Hosts: d.Hosts, Unknown: d.Unknown} |
| + if a.Hosts == nil { |
| + a.Hosts = map[string]string{} |
| + } |
| + if err := checkAssignment(a); err != nil { |
| + return Assignment{}, fmt.Errorf("%s: %w", AssignmentPath(dataDir), err) |
| + } |
| + return a, nil |
| +} |
| + |
| +func checkAssignment(a Assignment) error { |
| + if a.At.IsZero() { |
| + return errors.New("boxself: an assignment with no time") |
| + } |
| + for host, ref := range a.Hosts { |
| + if strings.TrimSpace(host) == "" { |
| + return errors.New("boxself: an assignment for an empty host") |
| + } |
| + if !ValidRef(ref) { |
| + return fmt.Errorf("boxself: %s assigned to %q, which is not a box reference", host, ref) |
| + } |
| + } |
| + for _, host := range a.Unknown { |
| + if strings.TrimSpace(host) == "" { |
| + return errors.New("boxself: an empty unknown host") |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// 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 { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return err |
| + } |
| + defer f.Close() |
| + body, err := io.ReadAll(io.LimitReader(f, maxRead+1)) |
| + if err != nil { |
| + return err |
| + } |
| + if len(body) > maxRead { |
| + return fmt.Errorf("boxself: %s is over %d bytes", path, maxRead) |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(body)) |
| + dec.DisallowUnknownFields() |
| + if err := dec.Decode(v); err != nil { |
| + return fmt.Errorf("boxself: %s: %w", path, err) |
| + } |
| + if dec.More() { |
| + return fmt.Errorf("boxself: %s: more than one value", path) |
| + } |
| + return nil |
| +} |
| + |
| +// writeAtomic puts body at path through path+".tmp", synced and renamed, |
| +// mode 0644 whatever the umask, creating the directory (0755) if needed. |
| +// The scratch name is fixed so a crash leaves one known file, which the |
| +// next write replaces. |
| +func writeAtomic(path string, body []byte) error { |
| + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| + return err |
| + } |
| + tmp := path + ".tmp" |
| + f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = f.Write(body) |
| + if err == nil { |
| + err = f.Chmod(0o644) |
| + } |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err == nil { |
| + err = os.Rename(tmp, path) |
| + } |
| + if err != nil { |
| + os.Remove(tmp) |
| + return err |
| + } |
| + return nil |
| +} |
diff --git a/internal/boxself/boxself_test.go b/internal/boxself/boxself_test.go| new file mode 100644 |
| index 000000000..abf161d0f |
| --- /dev/null |
| +++ b/internal/boxself/boxself_test.go |
| @@ -0,0 +1,145 @@ |
| +package boxself |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestBoxSelfRoundTrip(t *testing.T) { |
| + for _, s := range []Self{{Ref: "jolly-otter"}, {Ref: "g-0123456789abcdef0123", Group: true}} { |
| + dir := t.TempDir() |
| + if err := Write(dir, s); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := Read(dir) |
| + if err != nil || got != s { |
| + t.Fatalf("read %+v, %v; want %+v", got, err, s) |
| + } |
| + fi, err := os.Stat(filepath.Join(dir, "monitor", "self.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if fi.Mode().Perm() != 0o644 { |
| + t.Fatalf("mode %v, want 0644", fi.Mode().Perm()) |
| + } |
| + body, _ := os.ReadFile(filepath.Join(dir, "monitor", "self.json")) |
| + if !strings.Contains(string(body), `"v":1`) { |
| + t.Fatalf("no version: %s", body) |
| + } |
| + // A second write replaces the first, leaving no scratch behind. |
| + s.Ref += "-2" |
| + if err := Write(dir, s); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := Read(dir); got != s { |
| + t.Fatalf("rewrite read %+v, want %+v", got, s) |
| + } |
| + entries, _ := os.ReadDir(filepath.Join(dir, "monitor")) |
| + if len(entries) != 1 { |
| + t.Fatalf("monitor holds %d entries, want 1", len(entries)) |
| + } |
| + } |
| +} |
| + |
| +func TestBoxSelfReadMissing(t *testing.T) { |
| + if _, err := Read(t.TempDir()); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("missing file: %v, want os.ErrNotExist", err) |
| + } |
| + if _, err := ReadAssignment(t.TempDir()); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("missing assignment: %v, want os.ErrNotExist", err) |
| + } |
| +} |
| + |
| +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 { |
| + 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) |
| + } |
| + } |
| + for name, body := range map[string]string{ |
| + "empty ref": `{"v":1,"ref":""}`, |
| + "bad ref": `{"v":1,"ref":"a/b"}`, |
| + "no ref": `{"v":1}`, |
| + "version": `{"v":2,"ref":"jolly-otter"}`, |
| + "no version": `{"ref":"jolly-otter"}`, |
| + "not json": `jolly-otter`, |
| + "trailing": `{"v":1,"ref":"jolly-otter"}{}`, |
| + "wrong group": `{"v":1,"ref":"jolly-otter","group":"yes"}`, |
| + "empty file": ``, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(dir, "monitor"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "monitor", "self.json"), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s, err := Read(dir); err == nil || errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("read %+v, %v; want a refusal", s, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAssignmentRoundTrip(t *testing.T) { |
| + dir := t.TempDir() |
| + at := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) |
| + a := Assignment{At: at, Hosts: map[string]string{"shop.example.com": "g-0123456789abcdef0123", "blog.example.com": "g-fedcba9876543210fedc"}, Unknown: []string{"cold.example.com"}} |
| + if err := WriteAssignment(dir, a); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := ReadAssignment(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !got.At.Equal(at) || !reflect.DeepEqual(got.Hosts, a.Hosts) || !reflect.DeepEqual(got.Unknown, a.Unknown) { |
| + t.Fatalf("read %+v, want %+v", got, a) |
| + } |
| + fi, err := os.Stat(filepath.Join(dir, "monitor", "verify-assign.json")) |
| + if err != nil || fi.Mode().Perm() != 0o644 { |
| + t.Fatalf("assignment file: %v %v", fi, err) |
| + } |
| + // An empty assignment round-trips as empty, not as a refusal. |
| + empty := Assignment{At: at} |
| + if err := WriteAssignment(dir, empty); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, err := ReadAssignment(dir); err != nil || len(got.Hosts) != 0 || len(got.Unknown) != 0 || !got.At.Equal(at) { |
| + t.Fatalf("empty assignment: %+v %v", got, err) |
| + } |
| + // A winner that is no reference is refused both ways. |
| + if err := WriteAssignment(dir, Assignment{At: at, Hosts: map[string]string{"shop.example.com": ""}}); err == nil { |
| + t.Fatal("wrote an empty winner") |
| + } |
| + if err := WriteAssignment(dir, Assignment{Hosts: map[string]string{}}); err == nil { |
| + t.Fatal("wrote an assignment with no time") |
| + } |
| + for name, body := range map[string]string{ |
| + "version": `{"v":2,"at":"2026-11-11T03:00:00Z","hosts":{}}`, |
| + "no time": `{"v":1,"hosts":{}}`, |
| + "bad winner": `{"v":1,"at":"2026-11-11T03:00:00Z","hosts":{"shop.example.com":"a/b"}}`, |
| + "empty host": `{"v":1,"at":"2026-11-11T03:00:00Z","hosts":{"":"jolly-otter"}}`, |
| + "not json": `[`, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + d := t.TempDir() |
| + _ = os.MkdirAll(filepath.Join(d, "monitor"), 0o755) |
| + if err := os.WriteFile(filepath.Join(d, "monitor", "verify-assign.json"), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a, err := ReadAssignment(d); err == nil { |
| + t.Fatalf("read %+v; want a refusal", a) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/edge/drillassign_test.go b/internal/edge/drillassign_test.go| new file mode 100644 |
| index 000000000..0d9374108 |
| --- /dev/null |
| +++ b/internal/edge/drillassign_test.go |
| @@ -0,0 +1,209 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// drillMap is wakeMap seen from the box self: the same edges files, folded |
| +// for that box. |
| +func drillMap(t *testing.T, self string, files ...map[string]any) *homeMap { |
| + t.Helper() |
| + m := wakeMap(t, files...) |
| + m.self = self |
| + m.snap.hosts, _ = foldHomes(m.snap.files, self, m.privateDial) |
| + return m |
| +} |
| + |
| +// drillView is the agent's duty view (internal/host dutyView) over a home |
| +// map at wakeNow: the sidecar projection for a sidecar, DutySnapshot's |
| +// otherwise. |
| +func drillView(m *homeMap, rt registry.Route) boxchoice.WakeSnapshot { |
| + if rt.IsSidecar() { |
| + return m.dutySnapshot(rt, wakeNow, provision.PlacementAny) |
| + } |
| + return m.wakeSnapshot(rt, wakeNow) |
| +} |
| + |
| +// drillers are the boxes whose nightly drill tests rt: those whose own |
| +// view is usable and whose HRW over its serving set names themselves. |
| +func drillers(boxes map[string]*homeMap, rt registry.Route) []string { |
| + var out []string |
| + for _, ref := range drillRefs { |
| + m := boxes[ref] |
| + if m == nil { |
| + continue |
| + } |
| + s := drillView(m, rt) |
| + if !s.Usable || len(s.Serving) == 0 { |
| + continue |
| + } |
| + var refs []string |
| + for _, c := range s.Serving { |
| + refs = append(refs, c.BoxID) |
| + } |
| + if w, ok := boxchoice.HRW(rt.Host, refs); ok && w == ref { |
| + out = append(out, ref) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +var drillRefs = []string{"g-0123456789abcdef0123", "g-fedcba9876543210fedc", "g-00000000000000000000"} |
| + |
| +// TestDrillAssignmentCoversEveryHost (F2-2, F2-5): three group boxes in |
| +// one region, each computing the drill assignment from its own fold of |
| +// the same edges files. Every host is drilled by at least one usable box, |
| +// and by exactly one in steady state. A box that counts itself before it |
| +// advertises a host, or that has no signing key to see its peers, may |
| +// double a host; none of the cases leaves a host undrilled. |
| +func TestDrillAssignmentCoversEveryHost(t *testing.T) { |
| + a, b, c := drillRefs[0], drillRefs[1], drillRefs[2] |
| + var routes []registry.Route |
| + hosts := map[string]any{} |
| + for n := range 60 { |
| + rt := registry.Route{Host: fmt.Sprintf("h%d.example.com", n), Account: release.OpsAccount, App: "shop", HA: true} |
| + routes = append(routes, rt) |
| + hosts[rt.Host] = map[string]any{"role": "home", "account": rt.Account, "app": rt.App} |
| + } |
| + var sidecars []registry.Route |
| + for n := range 30 { |
| + sidecars = append(sidecars, registry.Route{Host: fmt.Sprintf("bot%d.shop.bab.sidecar.internal", n), Account: "bab", App: "shop", Kind: provision.SidecarKind, Provisioned: true, HA: true}) |
| + } |
| + file := func(ref string) map[string]any { |
| + f := wakeFile(ref) |
| + f["hosts"] = hosts |
| + return f |
| + } |
| + sidecarFile := func(ref string) map[string]any { |
| + f := wakeFile(ref) |
| + delete(f, "placement") |
| + f["hosts"] = map[string]any{} |
| + f["served_pools"] = []string{""} |
| + return f |
| + } |
| + build := func(files map[string]map[string]any) map[string]*homeMap { |
| + all := []map[string]any{files[a], files[b], files[c]} |
| + out := map[string]*homeMap{} |
| + for _, ref := range drillRefs { |
| + out[ref] = drillMap(t, ref, all...) |
| + } |
| + return out |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + // mutate edits the files (and then the maps) before the check. |
| + mutate func(files map[string]map[string]any) |
| + mutateMap func(boxes map[string]*homeMap) |
| + routes []registry.Route |
| + file func(string) map[string]any |
| + // want is how many boxes drill rt, given the winner over all three. |
| + want func(all string) int |
| + // never drills nothing. |
| + never string |
| + }{ |
| + {name: "steady", want: func(string) int { return 1 }}, |
| + { |
| + // A box counts itself before it advertises a host |
| + // (TestWakeSnapshotSelfAdoptsBeforePublication); its peers |
| + // don't count it yet, so the host may be drilled twice. |
| + name: "own file not advertising yet", |
| + mutate: func(f map[string]map[string]any) { f[c]["hosts"] = map[string]any{} }, |
| + want: func(all string) int { |
| + if all == c { |
| + return 2 |
| + } |
| + return 1 |
| + }, |
| + }, |
| + { |
| + name: "draining box", |
| + mutate: func(f map[string]map[string]any) { f[c]["draining"] = true }, |
| + want: func(string) int { return 1 }, |
| + never: c, |
| + }, |
| + { |
| + name: "peer file older than 15 minutes", |
| + mutate: func(f map[string]map[string]any) { |
| + f[c]["generation"] = wakeNow.Add(-15*time.Minute - time.Second).Format(time.RFC3339Nano) |
| + }, |
| + want: func(string) int { return 1 }, |
| + never: c, |
| + }, |
| + { |
| + // Without a signing key a box sees no peer, so it names itself |
| + // for every host; its peers still count it. |
| + name: "box with no signing key", |
| + mutateMap: func(m map[string]*homeMap) { m[c].keyCurrent = nil }, |
| + want: func(all string) int { |
| + if all == c { |
| + return 1 |
| + } |
| + return 2 |
| + }, |
| + }, |
| + {name: "sidecar routes", routes: sidecars, file: sidecarFile, want: func(string) int { return 1 }}, |
| + { |
| + // An HA box rewrites its edges file every 5 minutes whether or |
| + // not its hosts changed (internal/host/edgesfile.go), so a quiet |
| + // box's file is at most about that old and still counts. |
| + name: "quiet box", |
| + mutate: func(f map[string]map[string]any) { |
| + f[c]["generation"] = wakeNow.Add(-5*time.Minute - 30*time.Second).Format(time.RFC3339Nano) |
| + }, |
| + want: func(string) int { return 1 }, |
| + }, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + mk := file |
| + if tc.file != nil { |
| + mk = tc.file |
| + } |
| + files := map[string]map[string]any{a: mk(a), b: mk(b), c: mk(c)} |
| + if tc.mutate != nil { |
| + tc.mutate(files) |
| + } |
| + boxes := build(files) |
| + if tc.mutateMap != nil { |
| + tc.mutateMap(boxes) |
| + } |
| + rts := routes |
| + if tc.routes != nil { |
| + rts = tc.routes |
| + } |
| + counts := map[int]int{} |
| + drilled := map[string]int{} |
| + for _, rt := range rts { |
| + all, _ := boxchoice.HRW(rt.Host, drillRefs) |
| + got := drillers(boxes, rt) |
| + if len(got) == 0 { |
| + t.Fatalf("%s: drilled by no box", rt.Host) |
| + } |
| + if want := tc.want(all); len(got) != want { |
| + t.Fatalf("%s: drilled by %v, want %d box(es) (winner over all three %s)", rt.Host, got, want, all) |
| + } |
| + counts[len(got)]++ |
| + for _, ref := range got { |
| + drilled[ref]++ |
| + if ref == tc.never { |
| + t.Fatalf("%s: drilled by %s, which must drill nothing", rt.Host, ref) |
| + } |
| + } |
| + } |
| + for _, ref := range drillRefs { |
| + if ref != tc.never && drilled[ref] == 0 { |
| + t.Fatalf("%s drilled no host: %v", ref, drilled) |
| + } |
| + } |
| + if tc.want(c) != tc.want(a) && counts[2] == 0 { |
| + t.Fatalf("no host was doubled, so the case is not exercised: %v", counts) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index c4f2449d2..82389ab8e 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -181,7 +181,6 @@ import ( |
| "github.com/carlosframework/platform/internal/apperr" |
| "github.com/carlosframework/platform/internal/applog" |
| "github.com/carlosframework/platform/internal/assetcache" |
| - "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/caps" |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/cliflag" |
| @@ -215,8 +214,11 @@ import ( |
| ) |
| // dataDir resolves the fleet data directory (CARLOS_DATA_DIR, default /data). |
| -func dataDir() string { |
| - if d := os.Getenv("CARLOS_DATA_DIR"); d != "" { |
| +func dataDir() string { return dataDirFrom(os.Getenv) } |
| + |
| +// dataDirFrom is dataDir read through getenv. |
| +func dataDirFrom(getenv func(string) string) string { |
| + if d := getenv("CARLOS_DATA_DIR"); d != "" { |
| return d |
| } |
| return "/data" |
| @@ -1249,6 +1251,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // signals the edge's held streams when a host may have become |
| // admissible. act is nil when hibernation is not armed; no route |
| // is held then. |
| + var setDutyView func(dutyViewFunc) |
| if act != nil { |
| act.SetHeldWakeHook(e.HeldWake) |
| if svc != nil { |
| @@ -1264,18 +1267,14 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| if admission != nil && admission.group { |
| driver.group = newDrainDriver(svc, e, boxDrain, groupStartFence.read) |
| } |
| - svc.SetDutyView(func(rt registry.Route) boxchoice.WakeSnapshot { |
| - if rt.IsSidecar() { |
| - entry, ok := boxLifetimes.Lookup(rt.Host) |
| - if !ok { |
| - return boxchoice.WakeSnapshot{LocalDenied: true} |
| - } |
| - return e.SidecarDutySnapshot(rt, entry.SidecarPlacement) |
| - } |
| - return e.DutySnapshot(rt) |
| - }) |
| + setDutyView = svc.SetDutyView |
| } |
| } |
| + // One view of each host's serving boxes for the HA duties and, on |
| + // a group box, the nightly drill's assignment (verifyassign.go). |
| + armDutyView(dutyView(e, boxLifetimes), setDutyView, groupReferenced(os.Getenv), func(view dutyViewFunc) { |
| + go verifyAssignLoop(agentCtx, reg.List, view, dd, log.Printf) |
| + }) |
| // The drain socket: on a group member for its drain verbs, and on a |
| // fixed box whose ingress drain is configured, for the drain unit |
| // and the root verbs (W6 §5.2). |
diff --git a/internal/host/agententry.go b/internal/host/agententry.go| index 16e269563..1ef84be14 100644 |
| --- a/internal/host/agententry.go |
| +++ b/internal/host/agententry.go |
| @@ -7,6 +7,7 @@ import ( |
| "syscall" |
| "time" |
| + "github.com/carlosframework/platform/internal/boxself" |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/lease" |
| ) |
| @@ -33,7 +34,8 @@ func groupReferenceBackoff(n int) time.Duration { |
| // box, whatever CARLOS_REGION_HA says, it names the box every lease lock |
| // 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). |
| +// the agent (run). Beside the lease's self it records the same reference |
| +// for the nightly restore drill (boxself.Write). |
| 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) { |
| @@ -47,6 +49,12 @@ func agentEntry(getenv func(string) string, resolve func() (string, error), back |
| self := identity() |
| 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; the |
| + // drill then refuses to run rather than guess. |
| + if err := boxself.Write(dataDirFrom(getenv), boxself.Self{Ref: self.Ref, Group: groupReferenced(getenv)}); err != nil { |
| + logf("agent: the restore drill's record of this box could not be written: %v", err) |
| + } |
| run() |
| } |
diff --git a/internal/host/agententry_test.go b/internal/host/agententry_test.go| index 976cb41c6..08af6dafa 100644 |
| --- a/internal/host/agententry_test.go |
| +++ b/internal/host/agententry_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| + "maps" |
| "strings" |
| "testing" |
| "time" |
| @@ -39,7 +40,9 @@ func TestAGroupBoxResolvesItsReferenceBeforeTheAgentStarts(t *testing.T) { |
| } |
| return "123456789012", "i-0a61f580df1acfa65", nil |
| } |
| - getenv := groupEnv(tc.env) |
| + env := map[string]string{"CARLOS_DATA_DIR": t.TempDir()} |
| + maps.Copy(env, tc.env) |
| + getenv := groupEnv(env) |
| var lines []string |
| logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) } |
| ranAt, label := -1, "" |
diff --git a/internal/host/boxself_census_linux_test.go b/internal/host/boxself_census_linux_test.go| new file mode 100644 |
| index 000000000..14599c0d5 |
| --- /dev/null |
| +++ b/internal/host/boxself_census_linux_test.go |
| @@ -0,0 +1,46 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/hostbox" |
| +) |
| + |
| +// TestBoxSelfFilesInClaimCensus: the drill records the agent writes on |
| +// every box, and the scratch a crashed write leaves, are classified box |
| +// 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 { |
| + t.Fatal(err) |
| + } |
| + if err := boxself.WriteAssignment(data, boxself.Assignment{At: time.Now(), Hosts: map[string]string{"shop.example.com": "g-0123456789abcdef0123"}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []string{boxself.SelfPath(data) + ".tmp", boxself.AssignmentPath(data) + ".tmp"} { |
| + if err := os.WriteFile(p, []byte("{"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + roots := map[string]string{"data": data, "opt": opt, "units": units} |
| + shared := map[string][]string{"data": claimDataCensus(data)} |
| + if err := hostbox.CheckMigrationRoots(t.Context(), roots, shared, nil); err != nil { |
| + t.Fatalf("census over the drill records: %v", err) |
| + } |
| + // Without their entries the census refuses them, as it refuses any |
| + // unclassified file. |
| + shared["data"] = slices.DeleteFunc(slices.Clone(shared["data"]), func(e string) bool { |
| + return e == hostbox.CensusFile(filepath.ToSlash(filepath.Join("monitor", "self.json"))) |
| + }) |
| + if err := hostbox.CheckMigrationRoots(t.Context(), roots, shared, nil); !errors.Is(err, hostbox.ErrTypedInventory) { |
| + t.Fatalf("census without self.json's entry: %v", err) |
| + } |
| +} |
diff --git a/internal/host/claimcensus.go b/internal/host/claimcensus.go| index 5081d0dba..c5b4eb465 100644 |
| --- a/internal/host/claimcensus.go |
| +++ b/internal/host/claimcensus.go |
| @@ -8,6 +8,7 @@ import ( |
| "slices" |
| "strings" |
| + "github.com/carlosframework/platform/internal/boxself" |
| "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -113,6 +114,10 @@ func claimBoxDataCensus(dataDir string) []string { |
| // geoipmirror.go's "current") and the metrics loop's alert state. |
| filepath.Join(dataDir, "carlos", "geoip", "current"), |
| filepath.Join(dataDir, "monitor", "alerts.json"), |
| + // The agent's records for the nightly restore drill (boxself), |
| + // and the scratch a crashed write of either leaves. |
| + boxself.SelfPath(dataDir), boxself.SelfPath(dataDir) + ".tmp", |
| + boxself.AssignmentPath(dataDir), boxself.AssignmentPath(dataDir) + ".tmp", |
| } { |
| files = append(files, hostbox.CensusFile(rel(path))) |
| } |
diff --git a/internal/host/haself_test.go b/internal/host/haself_test.go| index d5d8f5807..78c5b73cf 100644 |
| --- a/internal/host/haself_test.go |
| +++ b/internal/host/haself_test.go |
| @@ -22,7 +22,7 @@ func TestAgentEntrySetsOwnerBeforeRun(t *testing.T) { |
| fx := locktest.NewLockFixture(t) |
| lease.SetSelf(hafresh.Self{Ref: "stale"}) |
| var owner string |
| - agentEntry(envOf(nil), nil, groupReferenceBackoff, t.Logf, func() hafresh.Self { return hafresh.Self{Ref: "ie-box", IID: "i-0abc"} }, func() { |
| + agentEntry(envOf(map[string]string{"CARLOS_DATA_DIR": t.TempDir()}), nil, groupReferenceBackoff, t.Logf, func() hafresh.Self { return hafresh.Self{Ref: "ie-box", IID: "i-0abc"} }, func() { |
| h, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "") |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/verifyassign.go b/internal/host/verifyassign.go| new file mode 100644 |
| index 000000000..e4d9bcc04 |
| --- /dev/null |
| +++ b/internal/host/verifyassign.go |
| @@ -0,0 +1,107 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "slices" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The nightly restore drill's two inputs from the agent (member backups |
| +// slice 2a, P-9, P2-9). The drill (carlos ops hibernate-verify) publishes |
| +// under the box's lease reference, which only the agent knows, and on a |
| +// group box tests only the HA hosts this box is assigned. The agent writes |
| +// both under <data>/monitor/ (boxself), as user carlos, the user the |
| +// drill's unit runs as. |
| + |
| +// verifyAssignEvery is how often a group box recomputes its assignment. |
| +const verifyAssignEvery = 5 * time.Minute |
| + |
| +// dutyViewFunc is a host's serving evidence as the HA duties read it. |
| +type dutyViewFunc = func(registry.Route) boxchoice.WakeSnapshot |
| + |
| +// dutyView is the one view of a host's serving boxes this agent judges |
| +// HA duties and drill assignments by: a sidecar's projection by its |
| +// placement (a sidecar the lifetime index doesn't know is denied here), |
| +// DutySnapshot for any other route. |
| +func dutyView(e *edge.Edge, lifetimes *provision.LifetimeIndex) dutyViewFunc { |
| + return func(rt registry.Route) boxchoice.WakeSnapshot { |
| + if rt.IsSidecar() { |
| + entry, ok := lifetimes.Lookup(rt.Host) |
| + if !ok { |
| + return boxchoice.WakeSnapshot{LocalDenied: true} |
| + } |
| + return e.SidecarDutySnapshot(rt, entry.SidecarPlacement) |
| + } |
| + return e.DutySnapshot(rt) |
| + } |
| +} |
| + |
| +// armDutyView hands view to the HA duties (set, nil when the activator |
| +// runs no duties) and, on a group box, to the drill assignment (assign): |
| +// one value, so the two never judge a host's serving boxes differently. |
| +func armDutyView(view dutyViewFunc, set func(dutyViewFunc), group bool, assign func(dutyViewFunc)) { |
| + if set != nil { |
| + set(view) |
| + } |
| + if group { |
| + assign(view) |
| + } |
| +} |
| + |
| +// computeAssignment is the box that drills each HA route's host: the HRW |
| +// winner over the references of the host's serving boxes, the same |
| +// evidence and hash the HA duties use when a host has no lock. A route |
| +// whose view is not usable or names no serving box is Unknown. |
| +func computeAssignment(routes []registry.Route, view dutyViewFunc, now time.Time) boxself.Assignment { |
| + a := boxself.Assignment{At: now.UTC(), Hosts: map[string]string{}} |
| + for _, rt := range routes { |
| + if !rt.HA { |
| + continue |
| + } |
| + s := view(rt) |
| + refs := make([]string, 0, len(s.Serving)) |
| + for _, c := range s.Serving { |
| + refs = append(refs, c.BoxID) |
| + } |
| + winner, ok := boxchoice.HRW(rt.Host, refs) |
| + if !s.Usable || !ok { |
| + a.Unknown = append(a.Unknown, rt.Host) |
| + continue |
| + } |
| + a.Hosts[rt.Host] = winner |
| + } |
| + slices.Sort(a.Unknown) |
| + a.Unknown = slices.Compact(a.Unknown) |
| + return a |
| +} |
| + |
| +// verifyAssignLoop writes the assignment now and every verifyAssignEvery |
| +// until ctx ends. |
| +func verifyAssignLoop(ctx context.Context, list func() ([]registry.Route, error), view dutyViewFunc, dataDir string, logf func(string, ...any)) { |
| + t := time.NewTicker(verifyAssignEvery) |
| + defer t.Stop() |
| + runVerifyAssign(ctx, list, view, dataDir, t.C, time.Now, logf) |
| +} |
| + |
| +// runVerifyAssign is verifyAssignLoop on a given tick. A failed listing |
| +// or write is logged and leaves the last assignment in place. |
| +func runVerifyAssign(ctx context.Context, list func() ([]registry.Route, error), view dutyViewFunc, dataDir string, tick <-chan time.Time, now func() time.Time, logf func(string, ...any)) { |
| + for { |
| + if routes, err := list(); err != nil { |
| + logf("agent: drill assignment: list routes: %v", err) |
| + } else if err := boxself.WriteAssignment(dataDir, computeAssignment(routes, view, now())); err != nil { |
| + logf("agent: drill assignment: %v", err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-tick: |
| + } |
| + } |
| +} |
diff --git a/internal/host/verifyassign_test.go b/internal/host/verifyassign_test.go| new file mode 100644 |
| index 000000000..428024c1a |
| --- /dev/null |
| +++ b/internal/host/verifyassign_test.go |
| @@ -0,0 +1,190 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +type offEC2 struct{} |
| + |
| +func (offEC2) RoundTrip(*http.Request) (*http.Response, error) { |
| + return nil, errors.New("no IMDS here") |
| +} |
| + |
| +// TestAgentWritesSelfRefEqualToLeaseRef: the reference the agent writes |
| +// for the nightly drill is the one its lease locks name, which is the |
| +// label its metrics publish under, on a fixed box and on a group box. |
| +func TestAgentWritesSelfRefEqualToLeaseRef(t *testing.T) { |
| + quick := func(int) time.Duration { return time.Millisecond } |
| + const account, instance = "123456789012", "i-0a61f580df1acfa65" |
| + for name, group := range map[string]bool{"fixed": false, "group": true} { |
| + t.Run(name, func(t *testing.T) { |
| + withGroupIdentity(t, account, instance, nil) |
| + dir := t.TempDir() |
| + env := map[string]string{"CARLOS_DATA_DIR": dir} |
| + if group { |
| + env[hostenv.BoxReference] = hostenv.GroupReference |
| + } |
| + getenv := groupEnv(env) |
| + // RunAgent's identity: a group box's reference from its boot |
| + // evidence, any other box's from haSelfNow. |
| + identity := func() hafresh.Self { |
| + if group { |
| + return hafresh.Self{Ref: groupReferenceOf(account, instance), IID: instance} |
| + } |
| + return haSelfNow(getenv, &http.Client{Transport: offEC2{}}) |
| + } |
| + ran := false |
| + agentEntry(getenv, resolveGroupBoxReference, quick, func(string, ...any) {}, identity, func() { ran = true }) |
| + if !ran { |
| + t.Fatal("the agent did not start") |
| + } |
| + got, err := boxself.Read(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + leaseRef := lease.CurrentSelf().Ref |
| + if got.Ref != leaseRef || got.Ref != metricsBoxLabel(getenv, readMachineID()) || got.Group != group { |
| + t.Fatalf("self file %+v; lease ref %q, metrics label %q, group %v", got, leaseRef, metricsBoxLabel(getenv, readMachineID()), group) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestComputeAssignment(t *testing.T) { |
| + now := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) |
| + serving := func(refs ...string) []boxchoice.Candidate { |
| + var out []boxchoice.Candidate |
| + for _, r := range refs { |
| + out = append(out, boxchoice.Candidate{BoxID: r}) |
| + } |
| + return out |
| + } |
| + snaps := map[string]boxchoice.WakeSnapshot{ |
| + "two.example.com": {Usable: true, Serving: serving("g-a", "g-b")}, |
| + "one.example.com": {Usable: true, Serving: serving("g-b")}, |
| + "unusable.example.com": {Usable: false, Serving: serving("g-a")}, |
| + "empty.example.com": {Usable: true}, |
| + "fixed.example.com": {Usable: true, Serving: serving("g-a")}, |
| + } |
| + var asked []string |
| + view := func(rt registry.Route) boxchoice.WakeSnapshot { |
| + asked = append(asked, rt.Host) |
| + return snaps[rt.Host] |
| + } |
| + routes := []registry.Route{ |
| + {Host: "two.example.com", HA: true}, {Host: "one.example.com", HA: true}, |
| + {Host: "unusable.example.com", HA: true}, {Host: "empty.example.com", HA: true}, |
| + {Host: "fixed.example.com"}, |
| + } |
| + got := computeAssignment(routes, view, now) |
| + win, _ := boxchoice.HRW("two.example.com", []string{"g-a", "g-b"}) |
| + want := boxself.Assignment{At: now, Hosts: map[string]string{"two.example.com": win, "one.example.com": "g-b"}, Unknown: []string{"empty.example.com", "unusable.example.com"}} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("assignment %+v, want %+v", got, want) |
| + } |
| + if slices.Contains(asked, "fixed.example.com") { |
| + t.Fatal("asked the view about a route that is not HA") |
| + } |
| + if got := computeAssignment(nil, view, now); got.Hosts == nil || len(got.Hosts) != 0 || len(got.Unknown) != 0 { |
| + t.Fatalf("no routes: %+v", got) |
| + } |
| +} |
| + |
| +// TestAgentUsesOneDutyView: the view the HA duties read and the one the |
| +// drill assignment reads are one value, so the two never judge a host's |
| +// serving boxes differently; only a group box runs the assignment. |
| +func TestAgentUsesOneDutyView(t *testing.T) { |
| + calls := 0 |
| + view := func(registry.Route) boxchoice.WakeSnapshot { |
| + calls++ |
| + return boxchoice.WakeSnapshot{Self: "g-a", Usable: true} |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + duties, group bool |
| + wantSet, wantAs bool |
| + }{ |
| + {"group box", true, true, true, true}, |
| + {"fixed box", true, false, true, false}, |
| + {"group box without hibernation", false, true, false, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var set, assigned func(registry.Route) boxchoice.WakeSnapshot |
| + var setter func(func(registry.Route) boxchoice.WakeSnapshot) |
| + if tc.duties { |
| + setter = func(v func(registry.Route) boxchoice.WakeSnapshot) { set = v } |
| + } |
| + armDutyView(view, setter, tc.group, func(v func(registry.Route) boxchoice.WakeSnapshot) { assigned = v }) |
| + if (set != nil) != tc.wantSet || (assigned != nil) != tc.wantAs { |
| + t.Fatalf("duties got a view: %v, assignment got one: %v", set != nil, assigned != nil) |
| + } |
| + for _, v := range []func(registry.Route) boxchoice.WakeSnapshot{set, assigned} { |
| + if v == nil { |
| + continue |
| + } |
| + before := calls |
| + if s := v(registry.Route{Host: "shop.example.com", HA: true}); s.Self != "g-a" || calls != before+1 { |
| + t.Fatalf("a different view: %+v, calls %d -> %d", s, before, calls) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestAssignmentLoopWritesUntilStopped: the loop writes at once and on |
| +// every tick, from the routes and view it was given, and stops with its |
| +// context. |
| +func TestAssignmentLoopWritesUntilStopped(t *testing.T) { |
| + dir := t.TempDir() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + ticks := make(chan time.Time) |
| + listed := make(chan struct{}, 8) |
| + list := func() ([]registry.Route, error) { |
| + listed <- struct{}{} |
| + return []registry.Route{{Host: "shop.example.com", HA: true}}, nil |
| + } |
| + view := func(registry.Route) boxchoice.WakeSnapshot { |
| + return boxchoice.WakeSnapshot{Usable: true, Serving: []boxchoice.Candidate{{BoxID: "g-a"}}} |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + runVerifyAssign(ctx, list, view, dir, ticks, func() time.Time { return time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) }, func(string, ...any) {}) |
| + }() |
| + <-listed |
| + ticks <- time.Time{} |
| + <-listed |
| + cancel() |
| + <-done |
| + a, err := boxself.ReadAssignment(dir) |
| + if err != nil || a.Hosts["shop.example.com"] != "g-a" { |
| + t.Fatalf("assignment %+v, %v", a, err) |
| + } |
| + // A failed listing is logged and leaves the last assignment in place. |
| + stopped, stop := context.WithCancel(context.Background()) |
| + stop() |
| + var logged []string |
| + failing := func() ([]registry.Route, error) { return nil, errors.New("registry busy") } |
| + runVerifyAssign(stopped, failing, view, dir, ticks, time.Now, func(f string, args ...any) { logged = append(logged, fmt.Sprintf(f, args...)) }) |
| + if len(logged) != 1 || !strings.Contains(logged[0], "registry busy") { |
| + t.Fatalf("logged %q", logged) |
| + } |
| + if b, err := boxself.ReadAssignment(dir); err != nil || !reflect.DeepEqual(a, b) { |
| + t.Fatalf("assignment after a failed listing %+v, %v; want %+v", b, err, a) |
| + } |
| +} |