grouproll: the seeded depart simulation and its mutants
TestSeededDepartSimulation runs replace and remove seeds with Task 7's death model, cut sessions, every drain outcome and terminate activity outcome, and audits H4 and H5 at the provider. TestDepartMutations: the five required mutants plus an audit control, each caught. 3000 seeds, final code: PASS, 952 s. replace 2027, remove 973; replaced 823, removed 370, drain-failed 1807; drained 1662, drain-uncertain 3222, drain-moving 485, cancel-drain 1807; pre-action-checked 1207, edge-stopped 1640, terminate-checked 1193, replacement-admitted 1160; terminate wait 12250, retry 369, fail 242; outcomes Failed 132, Cancelled 122, unsettled 113, pending 127, stuck 121, unknown 163, lagging 138; deaths 8901 (before-api 1328, after-api 1210); cuts 3195, terminated 3149; describe errors 11652; resumes 40187.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/grouproll/depart_test.go+8 −1internal/grouproll/mutation_test.go+47 −0internal/grouproll/sim_test.go+684 −0
CI failed — run details
Intent
<task-notification> <task-id>a4599f79b6d38e3e1</task-id> <tool-use-id>toolu_01L7eJBXsmJGWFfxUfK5uH7e</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a4599f79b6d38e3e1.output</output-file> <status>completed</status> <summary>Agent "Implement Task 9: replace/remove" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>Waiting for the result.</result> <usage><subagent_tokens>451174</subagent_tokens><tool_uses>105</tool_uses><duration_ms>2736746</duration_ms></usage> </task-notification>
Attributed to this commit: 11.2 g CO₂e (1,431,332 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on group-roll-verb, 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/grouproll/depart_test.go b/internal/grouproll/depart_test.go| index 9eb8bd7cc..00913ac0b 100644 |
| --- a/internal/grouproll/depart_test.go |
| +++ b/internal/grouproll/depart_test.go |
| @@ -26,7 +26,14 @@ const heldTx = "t6-held" |
| // when set, changes the config further before the state opens. |
| func newHeldHarness(t *testing.T, members int, configure func(c *Config)) *harness { |
| t.Helper() |
| - h := newHarnessWith(t, stateRoot(t), members, func(c *Config) { |
| + return newHeldHarnessAt(t, stateRoot(t), members, configure) |
| +} |
| + |
| +// newHeldHarnessAt is newHeldHarness with its state under root (the |
| +// depart simulation gives each seed its own directory). |
| +func newHeldHarnessAt(t *testing.T, root string, members int, configure func(c *Config)) *harness { |
| + t.Helper() |
| + h := newHarnessWith(t, root, members, func(c *Config) { |
| floor, prefix, bucket := "v0.35.0", "instances", "example-bucket" |
| c.HAFloor, c.DataPrefix, c.DataBucket = &floor, &prefix, &bucket |
| if configure != nil { |
diff --git a/internal/grouproll/mutation_test.go b/internal/grouproll/mutation_test.go| index 07e087e8e..7827aef0d 100644 |
| --- a/internal/grouproll/mutation_test.go |
| +++ b/internal/grouproll/mutation_test.go |
| @@ -6,6 +6,8 @@ import ( |
| "context" |
| "fmt" |
| "os" |
| + "regexp" |
| + "strings" |
| "testing" |
| "time" |
| ) |
| @@ -109,3 +111,48 @@ func TestRequiredMutations(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// TestDepartMutations: the planned handovers' required mutants, each an |
| +// executor seam, must fail the depart simulation's audits within 100 |
| +// seeds, on the audit that names it. |
| +func TestDepartMutations(t *testing.T) { |
| + base := stateRoot(t) |
| + mutants := []struct { |
| + name string |
| + mutate func(s *departSim) |
| + audit string |
| + }{ |
| + {"terminate with decrement", func(s *departSim) { |
| + s.h.seams.terminateDecrement = func(_ context.Context, iid string) (WriteResult, error) { |
| + return s.f.terminateDecrement(iid) |
| + } |
| + }, "terminate with decrement|desired lowered other than by Park|H4 violated"}, |
| + {"provider lowers desired on terminate (audit control)", func(s *departSim) { s.lowersOnTerminate = true }, |
| + "desired lowered other than by Park"}, |
| + {"terminate before edge stop", func(s *departSim) { s.h.seams.terminateFirst = true }, |
| + "terminate before edge stop"}, |
| + {"skip the second sweep", func(s *departSim) { s.h.seams.skipSecondSweep = true }, |
| + "terminate without an empty second sweep"}, |
| + {"unpark on unknown drain status", func(s *departSim) { s.h.seams.unparkUnknownDrain = true }, |
| + "unpark while the drain may be moving|unpark while the move runs"}, |
| + {"restore desired before the terminate check", func(s *departSim) { s.h.seams.restoreDesiredEarly = true }, |
| + "desired raised before the terminate check"}, |
| + } |
| + for _, m := range mutants { |
| + t.Run(m.name, func(t *testing.T) { |
| + for seed := int64(0); seed < 100; seed++ { |
| + _, err := runDepartSeed(t, base, seed, m.mutate) |
| + if err == nil { |
| + continue |
| + } |
| + first := strings.SplitN(strings.TrimPrefix(err.Error(), fmt.Sprintf("seed=%d: ", seed)), "\n", 2)[0] |
| + if !regexp.MustCompile(m.audit).MatchString(first) { |
| + t.Fatalf("mutant failed on another audit: %v", err) |
| + } |
| + t.Logf("depart mutation caught: %s: seed %d: %s", m.name, seed, first) |
| + return |
| + } |
| + t.Fatalf("%s survived the depart simulation", m.name) |
| + }) |
| + } |
| +} |
diff --git a/internal/grouproll/sim_test.go b/internal/grouproll/sim_test.go| index 2073c12f6..4c3c911a5 100644 |
| --- a/internal/grouproll/sim_test.go |
| +++ b/internal/grouproll/sim_test.go |
| @@ -533,3 +533,687 @@ func TestSimulationMutations(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// The seeded depart simulation (Go-only: the script has no departure |
| +// simulation). One seed is one replace (two or three members) or remove |
| +// (three members) of the held fake's member, with Task 7's death model: |
| +// up to three deaths at 0.7% per boundary (every journal row, before and |
| +// after every provider call, every wait) once the validated row is |
| +// written, then the next turn opens the state from disk and resumes. The |
| +// chaos is the roll simulation's (4% describe errors, 12% lost write |
| +// answers, 8% admission flips) plus cut sessions (a box session that |
| +// times out after its effect, 3%), and per seed a drain outcome (ok, |
| +// failed, refused, dropped once, the remote bound's 124, dropped while |
| +// the move ran or after it finished, a status that cannot reach the |
| +// agent, an agent restart), terminate activities that fail, are |
| +// cancelled, succeed unsettled, stay pending, get stuck or report an |
| +// unknown status, an edge that will not stop, and locks naming the |
| +// member before the drain or after the stop. The operator resumes, runs |
| +// cancel-drain when the tool says the drain may still move hosts, and |
| +// fixes the provider after an explicit stop. Chaos stops at turn 20 of |
| +// 40, and every seed must converge: replaced or removed, or returned |
| +// after a failed drain. |
| +// |
| +// Audits (H4 and H5, at the provider, from the durable rows and the |
| +// fake's truth): |
| +// - desired is never lowered except by EnterStandby of the header member; |
| +// - Terminate only after a drained row of this transaction, a |
| +// pre-action-checked row, an edge-stopped row with MainPID 0, and an |
| +// empty second sweep after that row (every listed host read, none |
| +// naming the member, every moved host seen), with the edge gone; |
| +// - ExitStandby only after a failed drain, and only when the status the |
| +// return acted on showed drain.state=known and no running move of |
| +// this transaction (and no such move runs); |
| +// - desired is raised only by the replace, after the terminate check, |
| +// with the member gone; minimum is restored only after desired, or by |
| +// the return once the member is serving; |
| +// - no fence-clear in a departure, no lifecycle completion, and a cut |
| +// session is terminated before the next box call. |
| + |
| +type departSim struct { |
| + t *testing.T |
| + seed int64 |
| + rng *rand.Rand |
| + h *harness |
| + f *fake |
| + tx, kind string |
| + n int |
| + |
| + coverage map[string]int |
| + trace []string |
| + deaths int |
| + chaos bool |
| + rows []Row |
| + sessions int |
| + pendingCut string |
| + lockAfterStop bool |
| + needCancel bool |
| + cancelled bool |
| + fenceSeen bool // the agent installed this transaction's fence |
| + // lowersOnTerminate is the audit control: a provider whose terminate |
| + // lowers desired though the call said no decrement. |
| + lowersOnTerminate bool |
| + lastAlert string |
| +} |
| + |
| +func unknownDrain(map[string]any) map[string]any { |
| + return map[string]any{"state": "unknown", "incarnation": nil, "transaction": nil, "step": nil, |
| + "result": nil, "error": "context deadline exceeded"} |
| +} |
| + |
| +// runDepartSeed runs one depart seed. mutate, when set, applies a mutant |
| +// (the engine's seams) before the run. |
| +func runDepartSeed(t *testing.T, base string, seed int64, mutate func(s *departSim)) (coverage map[string]int, err error) { |
| + root, err := os.MkdirTemp(base, "seed-") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer os.RemoveAll(root) |
| + rng := rand.New(rand.NewSource(seed)) |
| + s := &departSim{t: t, seed: seed, rng: rng, coverage: map[string]int{}, tx: fmt.Sprintf("dep-%d", seed), |
| + kind: "replace", n: 2 + rng.Intn(2)} |
| + if rng.Intn(3) == 0 { |
| + s.kind, s.n = "remove", 3 |
| + } |
| + s.coverage["kind:"+s.kind]++ |
| + s.h = newHeldHarnessAt(t, root, s.n, nil) |
| + s.f = s.h.f |
| + s.f.collect = true |
| + held := s.f.held |
| + modes := []string{"ok", "ok", "ok", "fail", "refused", "drop-once", "remote-timeout", "drop-done", |
| + "drop-running", "drop-running-unknown", "restart"} |
| + mode := modes[rng.Intn(len(modes))] |
| + s.coverage["drain-mode:"+mode]++ |
| + switch mode { |
| + case "drop-running-unknown": |
| + held.drainMode, held.statusDrain = "drop-running", unknownDrain |
| + case "restart": |
| + held.afterDrain = s.f.restartAgent |
| + default: |
| + held.drainMode = mode |
| + } |
| + if rng.Float64() < 0.3 { |
| + // A drain report with a float in it, as the agent may print. |
| + held.reportEdit = func(r map[string]any) { r["holds"].(map[string]any)["longest_ms"] = 1500.5 } |
| + } |
| + if rng.Float64() < 0.1 { |
| + held.locks["mine"] = heldLock(ref(fakeIID), fakeIID) |
| + s.coverage["lock-before-drain"]++ |
| + } |
| + s.lockAfterStop = rng.Float64() < 0.1 |
| + if rng.Float64() < 0.1 { |
| + held.edgeStops = false |
| + } |
| + held.enteringPolls = rng.Intn(4) |
| + for i, k := 0, rng.Intn(4); i < k; i++ { |
| + switch rng.Intn(7) { |
| + case 0: |
| + held.outcomes = append(held.outcomes, termOutcome{status: "Failed"}) |
| + case 1: |
| + held.outcomes = append(held.outcomes, termOutcome{status: "Cancelled"}) |
| + case 2: |
| + held.outcomes = append(held.outcomes, termOutcome{lagging: true}) |
| + case 3: |
| + held.outcomes = append(held.outcomes, termOutcome{status: "Successful", after: time.Duration(30+rng.Intn(170)) * time.Second}) |
| + case 4: |
| + held.outcomes = append(held.outcomes, termOutcome{status: "InProgress", after: time.Duration(10+rng.Intn(90)) * time.Second}) |
| + case 5: |
| + held.outcomes = append(held.outcomes, termOutcome{status: "InProgress", after: 700 * time.Second}) |
| + default: |
| + held.outcomes = append(held.outcomes, termOutcome{status: "Mystery", after: time.Duration(10+rng.Intn(50)) * time.Second}) |
| + } |
| + } |
| + s.f.sessions = func(string, string) []string { |
| + s.sessions++ |
| + return []string{fmt.Sprintf("sess-%d", s.sessions)} |
| + } |
| + s.f.intercept = s.request |
| + s.h.beforeEvent = func(kind string, _ map[string]any) { s.journalStep("before", kind, nil) } |
| + s.h.afterEvent = func(kind string, row Row) { s.journalStep("after", kind, row) } |
| + if mutate != nil { |
| + mutate(s) |
| + } |
| + defer func() { |
| + if r := recover(); r != nil { |
| + f, ok := r.(simFailure) |
| + if !ok { |
| + panic(r) |
| + } |
| + coverage, err = nil, s.failure(f.msg) |
| + } |
| + }() |
| + return s.run(), nil |
| +} |
| + |
| +func (s *departSim) failure(msg string) error { |
| + tail := s.trace |
| + if len(tail) > 40 { |
| + tail = tail[len(tail)-40:] |
| + } |
| + return fmt.Errorf("seed=%d: %s\ntrace=%s", s.seed, msg, strings.Join(tail, " ")) |
| +} |
| + |
| +func (s *departSim) fail(msg string) { panic(simFailure{msg}) } |
| + |
| +func (s *departSim) check(ok bool, msg string) { |
| + if !ok { |
| + s.fail(msg) |
| + } |
| +} |
| + |
| +// lastRow is the latest durable row of kind, nil when none; index is its |
| +// place in rows. |
| +func (s *departSim) lastRow(kind string) (Row, int) { |
| + for i := len(s.rows) - 1; i >= 0; i-- { |
| + if s.rows[i]["kind"] == kind { |
| + return s.rows[i], i |
| + } |
| + } |
| + return nil, -1 |
| +} |
| + |
| +func (s *departSim) has(kind string) bool { r, _ := s.lastRow(kind); return r != nil } |
| + |
| +func (s *departSim) active() bool { |
| + _, err := os.Lstat(s.h.state.activePath()) |
| + if err != nil && !os.IsNotExist(err) { |
| + s.fail("active transaction unreadable: " + err.Error()) |
| + } |
| + return err == nil |
| +} |
| + |
| +func (s *departSim) journalStep(when, kind string, row Row) { |
| + if when == "after" { |
| + s.rows = append(s.rows, row) |
| + switch kind { |
| + case "validated": |
| + s.chaos = true |
| + case "terminate-decision": |
| + s.coverage[fmt.Sprintf("terminate:%v", row["action"])]++ |
| + if reason, ok := row["reason"].(string); ok { |
| + s.coverage["terminate-reason:"+reason]++ |
| + } |
| + case "alert": |
| + reason, _ := row["reason"].(string) |
| + s.lastAlert = reason |
| + s.coverage["alert:"+reason]++ |
| + case "done": |
| + s.coverage[fmt.Sprintf("outcome:%v", row["outcome"])]++ |
| + case "drain-uncertain", "drain-failed", "drained", "pre-action-checked", "edge-stopped", |
| + "departure-finished", "replacement-admitted", "report", "fence-moot", "return-refused-moving", |
| + "drain-cancelled", "terminate-checked": |
| + s.coverage[kind]++ |
| + } |
| + switch kind { |
| + case "drain-failed", "drained", "edge-stopped", "terminate-checked", "done", "alert", "failed-probe": |
| + s.trace = append(s.trace, "journal:"+kind) |
| + } |
| + } |
| + s.audit(when + ":journal:" + kind) |
| + s.maybeDie(when + ":journal:" + kind) |
| +} |
| + |
| +func (s *departSim) maybeDie(boundary string) { |
| + if s.chaos && s.deaths < 3 && s.rng.Float64() < 0.007 { |
| + s.deaths++ |
| + s.trace = append(s.trace, "death@"+boundary) |
| + s.coverage["death"]++ |
| + for _, side := range []string{"before-api", "after-api"} { |
| + if strings.HasPrefix(boundary, side+":") { |
| + s.coverage["death:"+side]++ |
| + } |
| + } |
| + panic(simDeath{boundary}) |
| + } |
| +} |
| + |
| +// environment flips admission at reads and waits; the member's health |
| +// follows only while its edge runs. |
| +func (s *departSim) environment(boundary string) { |
| + if !s.chaos || s.rng.Float64() >= 0.08 { |
| + return |
| + } |
| + f := s.f |
| + f.admitted = !f.admitted |
| + if f.edge(fakeIID)["pid"] != nil { |
| + if f.admitted { |
| + f.boxes[fakeIID]["health"] = map[string]any{"state": "healthy", "code": int64(200)} |
| + } else { |
| + f.boxes[fakeIID]["health"] = map[string]any{"state": "unhealthy", "code": int64(503)} |
| + } |
| + } |
| + if f.admitted { |
| + s.coverage["admission-recovery"]++ |
| + } else { |
| + s.coverage["admission-drop"]++ |
| + } |
| + s.trace = append(s.trace, fmt.Sprintf("admission=%v@%s", f.admitted, boundary)) |
| +} |
| + |
| +func (s *departSim) advance(d time.Duration) { s.f.sleep(d) } |
| + |
| +func (s *departSim) sleep(d time.Duration) { |
| + s.advance(d) |
| + s.environment("sleep") |
| + s.audit("sleep") |
| + s.maybeDie("sleep") |
| +} |
| + |
| +func (s *departSim) memberGone() bool { |
| + st, ok := s.f.states[fakeIID] |
| + return !ok || strings.HasPrefix(st, "Terminat") |
| +} |
| + |
| +// request is the depart simulation's provider: chaos, deaths and the |
| +// request-time audits around the held fake. |
| +func (s *departSim) request(op string, args map[string]any, write bool, perform func() (any, error)) (any, error) { |
| + f := s.f |
| + s.advance(50 * time.Millisecond) |
| + if !write { |
| + s.environment(op) |
| + } |
| + s.maybeDie("before-api:" + op) |
| + s.audit("before-api:" + op) |
| + verb, _ := args["verb"].(string) |
| + switch op { |
| + case "session": |
| + s.check(s.pendingCut == "", "box call before the cut session was terminated") |
| + s.check(verb != "fence-clear", "fence-clear in a departure") |
| + case "terminate_session": |
| + if args["session_id"] == s.pendingCut { |
| + s.pendingCut = "" |
| + s.coverage["cut-terminated"]++ |
| + } |
| + case "complete": |
| + s.fail("lifecycle completion attempted") |
| + case "terminate": |
| + s.auditTerminate(args) |
| + if len(f.held.outcomes) > 0 { |
| + o := f.held.outcomes[0] |
| + label := o.status |
| + if o.lagging { |
| + label = "lagging" |
| + } else if o.status == "InProgress" && o.after >= 600*time.Second { |
| + label = "stuck" |
| + } |
| + s.coverage["terminate-outcome:"+label]++ |
| + } |
| + case "exit": |
| + s.auditExit() |
| + case "desired": |
| + s.check(s.kind == "replace" && s.has("terminate-checked") && s.memberGone(), |
| + "desired raised before the terminate check") |
| + case "minimum": |
| + if v := pyNumber(args["value"]); v != nil && *v == int64(s.n) { |
| + if s.has("drain-failed") { |
| + s.check(f.states[fakeIID] == "InService" && f.tg[fakeIID] == "healthy" && f.admitted, |
| + "minimum restored before readiness") |
| + } else { |
| + s.check(s.kind == "replace" && s.has("terminate-checked") && f.desired == s.n, |
| + "minimum restored before desired") |
| + } |
| + } |
| + } |
| + if s.chaos && (op == "group" || op == "targets") && s.rng.Float64() < 0.04 { |
| + s.coverage["describe-error"]++ |
| + s.trace = append(s.trace, "describe-error:"+op) |
| + return nil, Uncertain{Key: "api"} |
| + } |
| + oldDesired := f.desired |
| + result, err := perform() |
| + if op == "terminate" && err == nil && s.lowersOnTerminate { |
| + f.desired-- |
| + } |
| + parked := op == "enter" && args["iid"] == fakeIID && args["decrement"] == true |
| + s.check(f.desired >= oldDesired || parked, "desired lowered other than by Park of the member") |
| + if err != nil { |
| + return nil, err |
| + } |
| + name := op |
| + if op == "session" { |
| + name = verb |
| + } |
| + if write { |
| + s.trace = append(s.trace, fmt.Sprintf("write:%s(%s,%d,%d)", name, f.states[fakeIID], f.minimum, f.desired)) |
| + s.coverage["write:"+name]++ |
| + } |
| + if op == "enter" && f.held.enteringPolls > 0 { |
| + // Entry is asynchronous: still registered while it settles. |
| + f.states[fakeIID], f.tg[fakeIID] = "EnteringStandby", "draining" |
| + } |
| + if op == "session" && verb == "edge-stop" && s.lockAfterStop { |
| + f.held.locks["late"] = heldLock(ref(fakeIID), fakeIID) |
| + s.lockAfterStop = false |
| + s.coverage["lock-after-stop"]++ |
| + } |
| + s.audit("after-api:" + op) |
| + s.maybeDie("after-api:" + op) |
| + if op == "session" && s.chaos && s.rng.Float64() < 0.03 { |
| + s.pendingCut = fmt.Sprintf("sess-%d", s.sessions) |
| + s.coverage["cut:"+verb]++ |
| + s.trace = append(s.trace, "cut:"+verb) |
| + return nil, Uncertain{Key: "remote", Timeout: true} |
| + } |
| + if write && s.chaos && s.rng.Float64() < 0.12 { |
| + s.trace = append(s.trace, "response-loss:"+name) |
| + s.coverage["loss:"+name]++ |
| + return nil, Uncertain{Key: "api"} |
| + } |
| + return result, nil |
| +} |
| + |
| +// namesMember is the sweep's rule, written again from §25.6 step 4 as the |
| +// audit's oracle: a lock that is not a release marker names the member |
| +// when its owner is not a string, or names the member's ref or iid. |
| +func namesMember(v map[string]any) bool { |
| + if v["absent"] == true { |
| + return false |
| + } |
| + lock, _ := v["lock"].(map[string]any) |
| + owner, isStr := lock["owner"].(string) |
| + if lock != nil && (lock["carlos_release"] != nil || isStr && strings.HasPrefix(owner, "released/v1;")) { |
| + return false |
| + } |
| + if !isStr { |
| + return true |
| + } |
| + if rest, ok := strings.CutPrefix(owner, "box/v1;"); ok { |
| + for _, field := range strings.Split(rest, ";") { |
| + if field == "ref="+ref(fakeIID) || field == "iid="+fakeIID { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + return strings.Contains(owner, ref(fakeIID)) || strings.Contains(owner, fakeIID) |
| +} |
| + |
| +// emptySweepAfter: after row index from, a lock_hosts answer and an |
| +// answer for every listed host, none naming the member, and every host |
| +// the drain moved found with a lock. |
| +func (s *departSim) emptySweepAfter(from int, report map[string]any) bool { |
| + intents := map[int64]Row{} |
| + var hosts []any |
| + read := map[string]bool{} |
| + seen := map[string]bool{} |
| + for _, r := range s.rows[from+1:] { |
| + switch r["kind"] { |
| + case "intent": |
| + intents[rowSeq(r)] = r |
| + case "response": |
| + n := pyNumber(r["intent"]) |
| + if n == nil { |
| + continue |
| + } |
| + args, _ := intents[*n]["args"].(map[string]any) |
| + switch r["op"] { |
| + case "lock_hosts": |
| + hosts, _ = r["result"].([]any) |
| + read, seen = map[string]bool{}, map[string]bool{} |
| + case "lock": |
| + host, _ := args["host"].(string) |
| + v, _ := r["result"].(map[string]any) |
| + if namesMember(v) { |
| + return false |
| + } |
| + read[host] = true |
| + if v["absent"] != true { |
| + seen[host] = true |
| + } |
| + } |
| + } |
| + } |
| + if hosts == nil { |
| + return false |
| + } |
| + for _, h := range hosts { |
| + if name, _ := h.(string); HostName.MatchString(name) && !read[name] { |
| + return false |
| + } |
| + } |
| + moved, _ := report["moved"].([]any) |
| + for _, m := range moved { |
| + host, _ := m.(map[string]any)["host"].(string) |
| + if !seen[host] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func (s *departSim) auditTerminate(args map[string]any) { |
| + s.check(args["decrement"] == false, "terminate with decrement") |
| + s.check(!s.has("drain-failed"), "terminate after a failed drain") |
| + drained, _ := s.lastRow("drained") |
| + report, _ := drained["report"].(map[string]any) |
| + s.check(drained != nil && report["transaction"] == s.tx, "terminate without a drained row of this transaction") |
| + s.check(s.has("pre-action-checked"), "terminate without the pre-action check") |
| + stopped, at := s.lastRow("edge-stopped") |
| + systemd, _ := stopped["systemd"].(map[string]any) |
| + pid := pyNumber(systemd["main_pid"]) |
| + s.check(stopped != nil && pid != nil && *pid == 0, "terminate before edge stop") |
| + s.check(s.emptySweepAfter(at, report), "terminate without an empty second sweep") |
| + s.check(s.f.edge(fakeIID)["pid"] == nil, "terminate while the edge runs") |
| +} |
| + |
| +func (s *departSim) auditExit() { |
| + s.check(s.has("drain-failed"), "exit without a failed drain") |
| + _, at := s.lastRow("exit-intent") |
| + var status map[string]any |
| + for i := at - 1; i >= 0; i-- { |
| + if r := s.rows[i]; r["kind"] == "readiness" && r["iid"] == fakeIID { |
| + status, _ = r["status"].(map[string]any) |
| + break |
| + } |
| + } |
| + d, _ := status["drain"].(map[string]any) |
| + running := func(d map[string]any) bool { |
| + return d["transaction"] == s.tx && d["step"] == "move" && d["result"] == "running" |
| + } |
| + s.check(at >= 0 && d["state"] == "known" && !running(d), "unpark while the drain may be moving") |
| + s.check(!running(s.f.held.drainState), "unpark while the move runs") |
| +} |
| + |
| +// audit runs at every boundary. |
| +func (s *departSim) audit(boundary string) { |
| + f := s.f |
| + if f.held.fence == s.tx { |
| + s.fenceSeen = true |
| + } |
| + s.check(f.continues == 0, "lifecycle completion attempted") |
| + s.check(len(f.held.h4) == 0 && f.states[fakePeer] != "Terminated", "H4 violated: "+strings.Join(f.held.h4, "; ")) |
| + s.check(len(f.violations) == 0, "box protocol breach: "+strings.Join(f.violations, "; ")) |
| + s.check(f.desired <= f.maximum && f.minimum <= f.desired, "capacity out of shape") |
| + s.coverage["steps"]++ |
| +} |
| + |
| +// fix is the operator after an explicit stop: the provider or the box is |
| +// put right for the stop's reason. |
| +func (s *departSim) fix() { |
| + held := s.f.held |
| + switch s.lastAlert { |
| + case Text("edge_running"): |
| + held.edgeStops = true |
| + case Text("lock_held_after_stop"): |
| + delete(held.locks, "late") |
| + case Text("terminate_failed"): |
| + held.outcomes = nil |
| + case Text("terminate_unsettled"), Text("terminate_stuck"), Text("terminate_status"): |
| + s.f.settleTerminates() |
| + case Text("terminate_left_standby"): |
| + s.fail("member left Standby without a terminate") |
| + } |
| + s.lastAlert = "" |
| +} |
| + |
| +// calm ends the chaos: the provider settles and the operator's fixes are in. |
| +func (s *departSim) calm() { |
| + f := s.f |
| + s.chaos = false |
| + f.admitted = true |
| + if f.edge(fakeIID)["pid"] != nil { |
| + f.boxes[fakeIID]["health"] = map[string]any{"state": "healthy", "code": int64(200)} |
| + } |
| + f.held.outcomes = nil |
| + f.settleTerminates() |
| + f.held.edgeStops = true |
| + delete(f.held.locks, "late") |
| + s.lockAfterStop = false |
| +} |
| + |
| +func (s *departSim) turn(first bool) (err error, died bool) { |
| + defer func() { |
| + if r := recover(); r != nil { |
| + if _, ok := r.(simDeath); !ok { |
| + panic(r) |
| + } |
| + died = true |
| + s.pendingCut = "" // the process that owed the cleanup is gone |
| + } |
| + }() |
| + state, oerr := OpenState(s.h.root, s.h.c, false) |
| + if oerr != nil { |
| + s.fail("state unreadable: " + oerr.Error()) |
| + } |
| + state.fsync = s.h.state.fsync |
| + s.h.state = state |
| + err = s.h.locked(func(e *Engine) error { |
| + e.sleep = s.sleep |
| + switch { |
| + case first: |
| + return e.Depart(bg, fakeIID, s.kind, s.tx) |
| + case s.needCancel: |
| + if err := e.CancelDrain(bg, fakeIID, s.tx); err != nil { |
| + return err |
| + } |
| + s.needCancel, s.cancelled = false, true |
| + s.coverage["cancel-drain"]++ |
| + return nil |
| + } |
| + return e.Resume(bg, s.tx) |
| + }) |
| + return err, false |
| +} |
| + |
| +func (s *departSim) run() map[string]int { |
| + f := s.f |
| + converged := false |
| + for turn := 0; turn < 40; turn++ { |
| + if turn >= 20 { |
| + s.calm() |
| + } |
| + err, died := s.turn(turn == 0) |
| + switch { |
| + case died: |
| + s.coverage["resume"]++ |
| + case isStop(err, "drain-moving"): |
| + s.check(s.has("return-refused-moving"), "drain-moving stop without its row") |
| + s.coverage["drain-moving"]++ |
| + s.needCancel = true |
| + case isStop(err, "failed-probe"): |
| + s.fail("failed probe: " + err.Error()) |
| + case err == nil: |
| + case refusalOrUncertain(err): |
| + s.coverage["resume"]++ |
| + s.fix() |
| + default: |
| + s.fail("unexpected error: " + err.Error()) |
| + } |
| + s.audit("operator-return") |
| + if !s.needCancel && !s.active() { |
| + converged = true |
| + break |
| + } |
| + s.advance(3 * time.Second) |
| + } |
| + s.check(converged, "did not converge after fault injection stopped") |
| + s.audit("end") |
| + done, _ := s.lastRow("done") |
| + outcome, _ := done["outcome"].(string) |
| + n := s.n |
| + switch outcome { |
| + case "replaced": |
| + s.check(s.kind == "replace", "replaced in a removal") |
| + s.check(f.states[fakeIID] == "Terminated" && f.held.departed[ref(fakeIID)], "replaced member not gone") |
| + s.check(f.minimum == n && f.desired == n && f.maximum == n, "replace left the shape changed") |
| + s.check(f.states[replacementIID] == "InService" && f.tg[replacementIID] == "healthy", "replacement not serving") |
| + s.check(s.has("report") && s.has("replacement-admitted"), "replace without its report") |
| + case "removed": |
| + s.check(s.kind == "remove", "removed in a replace") |
| + s.check(f.states[fakeIID] == "Terminated" && f.held.departed[ref(fakeIID)], "removed member not gone") |
| + s.check(f.minimum == n-1 && f.desired == n-1 && f.maximum == n, "remove left the wrong shape") |
| + _, launched := f.states[replacementIID] |
| + s.check(!launched, "a removal launched a replacement") |
| + case "drain-failed": |
| + s.check(f.states[fakeIID] == "InService" && f.minimum == n && f.desired == n, "failed drain not returned") |
| + for _, c := range f.calls { |
| + s.check(c.Op != "terminate" && !(c.Op == "session" && c.Args["verb"] == "edge-stop"), |
| + "a failed drain stopped or terminated the member") |
| + } |
| + if !s.cancelled { |
| + // The tool never clears the fence of a failed drain (a refused |
| + // or unanswered drain may have installed none). |
| + s.check(f.held.fence == s.tx || f.held.fence == "" && !s.fenceSeen, "a failed drain lost its fence") |
| + // The operator ends the drain on the closed transaction. |
| + s.chaos = false |
| + if err, _ := s.turnCancel(); err != nil { |
| + s.fail("cancel-drain after a closed failed drain: " + err.Error()) |
| + } |
| + } |
| + s.check(f.held.fence == "", "the fence survived cancel-drain") |
| + default: |
| + s.fail("unexpected outcome " + outcome) |
| + } |
| + return s.coverage |
| +} |
| + |
| +func (s *departSim) turnCancel() (error, bool) { |
| + s.needCancel = true |
| + err, died := s.turn(false) |
| + return err, died |
| +} |
| + |
| +// TestSeededDepartSimulation: every replace and remove seed converges |
| +// with every audit holding; with 50 or more seeds, every path is covered. |
| +func TestSeededDepartSimulation(t *testing.T) { |
| + start, count := simSeeds(t) |
| + base := stateRoot(t) |
| + began := time.Now() |
| + coverage := map[string]int{} |
| + for seed := start; seed < start+count; seed++ { |
| + c, err := runDepartSeed(t, base, seed, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range c { |
| + coverage[k] += v |
| + } |
| + } |
| + var keys []string |
| + for k := range coverage { |
| + if !strings.HasPrefix(k, "death:") || k == "death:before-api" || k == "death:after-api" { |
| + keys = append(keys, k) |
| + } |
| + } |
| + sort.Strings(keys) |
| + var summary []string |
| + for _, k := range keys { |
| + summary = append(summary, fmt.Sprintf("%s=%d", k, coverage[k])) |
| + } |
| + t.Logf("depart simulation seeds=%d..%d wall=%.3fs coverage={%s}", start, start+count-1, |
| + time.Since(began).Seconds(), strings.Join(summary, " ")) |
| + if count >= 50 { |
| + for _, event := range []string{"kind:replace", "kind:remove", "outcome:replaced", "outcome:removed", |
| + "outcome:drain-failed", "drain-moving", "cancel-drain", "drain-uncertain", "return-refused-moving", |
| + "death", "death:before-api", "death:after-api", "resume", "describe-error", "loss:terminate", |
| + "loss:drain", "cut-terminated", "terminate:retry", "terminate:wait", "terminate:fail", |
| + "terminate-outcome:Failed", "terminate-outcome:Cancelled", "terminate-outcome:Successful", |
| + "terminate-outcome:InProgress", "terminate-outcome:stuck", "terminate-outcome:Mystery", |
| + "terminate-outcome:lagging", "departure-finished", "replacement-admitted", "fence-moot", |
| + "lock-after-stop", "lock-before-drain", "admission-drop"} { |
| + if coverage[event] == 0 { |
| + t.Errorf("coverage %s = 0", event) |
| + } |
| + } |
| + } |
| +} |