carlos / platform Public

grouproll: the seeded return simulation and its classifier mutants

A port of the script's Simulation: 12% write-answer loss, 4% describe
errors, 8% admission flips, up to three deaths at 0.7% per boundary
(every journal row, before and after every provider call, every wait),
chaos after validated. A death panics out of the engine; the next turn
reopens state and journal and resumes. TestSimulationMutations: the
five classifier mutants each fail within 50 seeds. CI runs 200 seeds.

GROUPROLL_SIM_SEEDS=3000, once: wall 654.1 s (go test real 10m54s), PASS.
Coverage: admission-drop 20982, admission-recovery 19986, death 8856
(before-api 1276, after-api 1300), describe-error 11374, diverged 1544,
failed 754, provider-return 790, provider-abandon 754, resume 41574,
loss:exit 290, phase:ReturnHeld 1544, phase:Returning 2246,
phase:Serving 2246, steps 4197800.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1a246449e2cc7b67b644dc3d6f4a92da09a69933 parent 6629082
2 files changed, +552 −1
  • internal/grouproll/fake_test.go +17 −1
  • internal/grouproll/sim_test.go +535 −0

CI failed — run details

Intent

Attributed to this commit: 22.2 g CO₂e (2,814,149 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/fake_test.go b/internal/grouproll/fake_test.go
index ce23b74ab..4f901bb27 100644
--- a/internal/grouproll/fake_test.go
+++ b/internal/grouproll/fake_test.go
@@ -10,6 +10,7 @@ import (
"path/filepath"
"sort"
"strings"
+ "sync"
"testing"
"time"
@@ -169,13 +170,21 @@ func newFake(t *testing.T, n int) *fake {
return f
}
+// liveFixtures caches the fixtures' bytes: the simulation reads a status
+// thousands of times.
+var liveFixtures sync.Map
+
// liveFixture reads a copied live fixture.
func liveFixture(t *testing.T, name string) []byte {
t.Helper()
+ if b, ok := liveFixtures.Load(name); ok {
+ return b.([]byte)
+ }
b, err := os.ReadFile(filepath.Join("testdata", "live", name))
if err != nil {
t.Fatal(err)
}
+ liveFixtures.Store(name, b)
return b
}
@@ -893,9 +902,16 @@ type harness struct {
}
func newHarness(t *testing.T, n int) *harness {
+ t.Helper()
+ return newHarnessAt(t, stateRoot(t), n)
+}
+
+// newHarnessAt is newHarness with its state under root (the simulation
+// gives each seed its own directory under one stateRoot).
+func newHarnessAt(t *testing.T, root string, n int) *harness {
t.Helper()
f := newFake(t, n)
- h := &harness{t: t, f: f, c: f.c, root: stateRoot(t)}
+ h := &harness{t: t, f: f, c: f.c, root: root}
s, err := OpenState(h.root, h.c, false)
if err != nil {
t.Fatal(err)
diff --git a/internal/grouproll/sim_test.go b/internal/grouproll/sim_test.go
new file mode 100644
index 000000000..2073c12f6
--- /dev/null
+++ b/internal/grouproll/sim_test.go
@@ -0,0 +1,535 @@
+//go:build linux || darwin
+
+package grouproll
+
+import (
+ "fmt"
+ "math/rand"
+ "os"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The seeded return simulation, ported from scripts/region_group_roll_test.py
+// (SimulationJournal, SimulationFake, Simulation; :2301-2620). One seed is
+// one roll of the fake's member with chaos after the validated row: a 4%
+// describe failure at group and target reads, a 12% lost answer at every
+// write, an 8% admission flip at reads and waits, and up to three process
+// deaths at 0.7% per boundary. A death is a panic of simDeath out of the
+// engine; the harness recovers it, and the next turn opens the state and
+// the journal again from disk and resumes, as the script's simulation
+// reloads its durable rows. Boundaries are every journal row (before and
+// after it is written), before and after every provider call (so between
+// an intent and its dispatch, and between the provider's answer and the
+// response row: Review Focus 2) and every wait. The provider returns a
+// hook or not, and after a hook it either returns the member itself or
+// abandons it. Audits run at every boundary.
+
+// simDeath is the simulated process dying at a boundary.
+type simDeath struct{ at string }
+
+// simFailure is a failed audit; its message is the script's assertion
+// text.
+type simFailure struct{ msg string }
+
+type simTransition struct {
+ at time.Time
+ raw string
+}
+
+type simulation struct {
+ t *testing.T
+ seed int64
+ rng *rand.Rand
+ h *harness
+ f *fake
+ tx string
+ classify func(Facts) Decision
+
+ coverage map[string]int
+ trace []string
+ deaths int
+ chaos bool
+ transitions []simTransition
+ providerReturns bool
+ // last journaled row of each kind, kept as rows become durable.
+ rows map[string]Row
+ forbidden []string // complete, desired or terminate calls seen
+}
+
+// runSeed runs one seed and returns its coverage, or the first failed
+// audit with the seed and the trace's tail. classify replaces the decider
+// (nil is Classify); the audited wrapper always runs around it. Each seed
+// gets its own state directory under base, removed afterwards.
+func runSeed(t *testing.T, base string, seed int64, classify func(Facts) Decision) (coverage map[string]int, err error) {
+ if classify == nil {
+ classify = Classify
+ }
+ root, err := os.MkdirTemp(base, "seed-")
+ if err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(root)
+ s := &simulation{t: t, seed: seed, rng: rand.New(rand.NewSource(seed)), classify: classify,
+ coverage: map[string]int{}, rows: map[string]Row{}, tx: fmt.Sprintf("sim-%d", seed)}
+ s.h = newHarnessAt(t, root, 2)
+ s.f = s.h.f
+ s.f.collect = true
+ s.f.hook = s.rng.Intn(2) == 1
+ s.f.targetWarmup = time.Duration(1+s.rng.Intn(80)) * time.Second
+ s.providerReturns = s.rng.Intn(2) == 1
+ s.f.intercept = s.request
+ s.h.classify = s.decide
+ 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) }
+ 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 *simulation) 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 *simulation) fail(msg string) { panic(simFailure{msg}) }
+
+func (s *simulation) check(ok bool, msg string) {
+ if !ok {
+ s.fail(msg)
+ }
+}
+
+func (s *simulation) last(kind string) bool { _, ok := s.rows[kind]; return ok }
+
+// active is the script simulation's store.active: whether the pointer
+// file names a transaction (the engine's own reads check the journals).
+func (s *simulation) 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
+}
+
+// journalStep is SimulationJournal.add's two boundaries.
+func (s *simulation) journalStep(when, kind string, row Row) {
+ if when == "after" {
+ s.rows[kind] = row
+ if kind == "validated" {
+ s.chaos = true
+ }
+ switch kind {
+ case "failed-probe", "return-hook", "divergence-held", "done":
+ s.trace = append(s.trace, "journal:"+kind)
+ }
+ }
+ s.audit(when + ":journal:" + kind)
+ s.maybeDie(when + ":journal:" + kind)
+}
+
+func (s *simulation) 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"]++
+ s.coverage["death:"+boundary]++
+ // Review Focus 2: a death after an intent row and before its
+ // dispatch, or after the provider answered and before the
+ // response row.
+ for _, side := range []string{"before-api", "after-api"} {
+ if strings.HasPrefix(boundary, side+":") {
+ s.coverage["death:"+side]++
+ }
+ }
+ panic(simDeath{boundary})
+ }
+}
+
+// environment flips the member's admission at reads and waits.
+func (s *simulation) environment(boundary string) {
+ if s.chaos && s.rng.Float64() < 0.08 {
+ f := s.f
+ f.admitted = !f.admitted
+ if f.admitted {
+ f.boxes[fakeIID]["health"] = map[string]any{"state": "healthy", "code": int64(200)}
+ s.coverage["admission-recovery"]++
+ } else {
+ f.boxes[fakeIID]["health"] = map[string]any{"state": "unhealthy", "code": int64(503)}
+ s.coverage["admission-drop"]++
+ }
+ s.trace = append(s.trace, fmt.Sprintf("admission=%v@%s", f.admitted, boundary))
+ }
+}
+
+// advance is SimulationFake.advance: time passes, then the member's
+// scheduled lifecycle transitions apply.
+func (s *simulation) advance(d time.Duration) {
+ s.f.sleep(d)
+ for len(s.transitions) > 0 && !s.transitions[0].at.After(s.f.now) {
+ raw := s.transitions[0].raw
+ s.transitions = s.transitions[1:]
+ s.f.states[fakeIID] = raw
+ s.coverage["phase:"+string(fakePhase(raw))]++
+ s.trace = append(s.trace, "transition:"+raw)
+ }
+}
+
+// sleep is the engine's wait.
+func (s *simulation) sleep(d time.Duration) {
+ s.advance(d)
+ s.environment("sleep")
+ s.audit("sleep")
+ s.maybeDie("sleep")
+}
+
+func (s *simulation) schedule(raws ...string) {
+ at := s.f.now
+ s.transitions = nil
+ for _, raw := range raws {
+ at = at.Add(time.Duration(1+s.rng.Intn(8)) * time.Second)
+ s.transitions = append(s.transitions, simTransition{at, raw})
+ }
+}
+
+// request is SimulationFake.request, the fake's intercept.
+func (s *simulation) request(op string, args map[string]any, write bool, perform func() (any, error)) (any, error) {
+ f := s.f
+ s.advance(50 * time.Millisecond)
+ // Admission changes at reads and waits, including both status reads.
+ // A confirmed observation is stable through its immediate dispatch.
+ if !write {
+ s.environment(op)
+ }
+ s.maybeDie("before-api:" + op)
+ s.audit("before-api:" + op)
+ if s.chaos && (op == "group" || op == "targets") && s.rng.Float64() < 0.04 {
+ s.coverage["describe-error"]++
+ if s.last("return-hook") {
+ s.coverage["describe-error-after-hook"]++
+ }
+ s.trace = append(s.trace, "describe-error:"+op)
+ return nil, Uncertain{Key: "api"}
+ }
+ if v := pyNumber(args["value"]); op == "minimum" && v != nil && *v == 2 {
+ s.check(!s.last("return-hook") && !s.last("divergence-hold"), "minimum restored in hold")
+ s.check(f.states[fakeIID] == "InService" && f.tg[fakeIID] == "healthy" && f.admitted,
+ "minimum restored before readiness")
+ s.check(f.desired == 2, "minimum raised desired")
+ }
+ switch op {
+ case "complete":
+ s.forbidden = append(s.forbidden, op)
+ s.fail("lifecycle completion attempted")
+ case "desired", "terminate":
+ s.forbidden = append(s.forbidden, op)
+ s.fail("forbidden provider write")
+ }
+ oldDesired := f.desired
+ result, err := perform()
+ if err != nil {
+ return nil, err
+ }
+ if op == "minimum" {
+ s.check(f.desired == oldDesired, "minimum raised desired")
+ }
+ name := op
+ if op == "session" {
+ name, _ = args["verb"].(string)
+ }
+ 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]++
+ }
+ switch op {
+ case "exit":
+ if f.hook {
+ f.states[fakeIID] = "Pending"
+ s.schedule("Pending:Wait")
+ } else {
+ f.states[fakeIID] = "PreInService"
+ s.schedule("Pending", "InService")
+ }
+ case "enter":
+ s.transitions = nil
+ }
+ s.audit("after-api:" + op)
+ s.maybeDie("after-api:" + op)
+ 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
+}
+
+// audit is Simulation.audit: the invariants at every boundary.
+func (s *simulation) audit(boundary string) {
+ f := s.f
+ s.check(f.continues == 0, "lifecycle completion attempted")
+ s.check(f.exits <= 1, "duplicate accepted return write")
+ s.check(len(s.forbidden) == 0, "forbidden provider write")
+ s.check(len(f.violations) == 0, "box protocol breach: "+strings.Join(f.violations, "; "))
+ if f.abandons > 0 {
+ s.check(f.hook && f.states[fakeIID] == "Terminated" && f.launches == 1, "unexpected replacement")
+ s.check(!s.last("done"), "terminated member recorded as pass")
+ } else {
+ s.check(len(f.states) == 2 && f.states[fakePeer] != "" && f.states[fakeIID] != "" &&
+ f.states[fakeIID] != "Terminated", "same iid lost")
+ }
+ if s.last("return-hook") {
+ s.check(blockedFlag(s.h), "divergence not flagged")
+ s.check(!s.last("done"), "hook recorded as pass")
+ }
+ if s.last("divergence-hold") {
+ s.check(f.minimum == 1, "minimum restored in hold")
+ }
+ if s.last("divergence-held") {
+ s.check(f.states[fakeIID] == "Standby" && f.tg[fakeIID] == "unused" && f.desired == 1 && f.minimum == 1,
+ "hold not verified")
+ s.check(blockedFlag(s.h), "held group not blocked")
+ }
+ s.coverage["steps"]++
+}
+
+// decide is Simulation.decide: the decider under audit.
+func (s *simulation) decide(facts Facts) Decision {
+ d := s.classify(facts)
+ readiness := facts.Readiness
+ if readiness == "" {
+ readiness = "unknown"
+ }
+ s.trace = append(s.trace, fmt.Sprintf("decide:%s:%s:%s:hook=%v:%s", facts.Context, facts.Phase, d.Action, facts.Hook, readiness))
+ s.check(d.Action != "complete" && d.Action != "abandon", "lifecycle completion decision")
+ if facts.Context == "return" && facts.Observed && !facts.DescribeError && !facts.OperationError {
+ if facts.Phase == ReturnHeld {
+ s.check(d.Action == "diverged", "divergence decision bypassed")
+ }
+ if facts.Phase == Absent || facts.Phase == Leaving || !facts.MembersMatch {
+ if facts.ExitState != "none" || facts.Hook {
+ s.check(d.Action == "failed", "terminated member recorded as pass")
+ }
+ }
+ }
+ if d.Action == "restore-minimum" {
+ s.check(!facts.Hook && !facts.HoldStarted, "minimum decision in hold")
+ s.check(facts.Phase == Serving && facts.TargetsHealthy && facts.Readiness == "ok",
+ "minimum decision before readiness")
+ }
+ s.audit("classify")
+ return d
+}
+
+// turn is one process: open the state, roll or resume, and maybe die.
+func (s *simulation) turn(first bool) (err error, died bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ if _, ok := r.(simDeath); !ok {
+ panic(r)
+ }
+ died = true
+ }
+ }()
+ 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
+ if first {
+ return e.Roll(bg, fakeIID, newSHA, s.tx)
+ }
+ return e.Resume(bg, s.tx)
+ })
+ return err, false
+}
+
+// run is Simulation.run: at most 40 turns, chaos and deaths in the first
+// 20, then the transaction must converge.
+func (s *simulation) run() map[string]int {
+ f := s.f
+ converged := false
+ for turn := 0; turn < 40; turn++ {
+ if turn >= 20 {
+ s.chaos = false
+ f.admitted = true
+ f.boxes[fakeIID]["health"] = map[string]any{"state": "healthy", "code": int64(200)}
+ }
+ err, died := s.turn(turn == 0)
+ switch {
+ case isStop(err, "divergence-held"):
+ s.check(s.last("divergence-held"), "divergence held without its row")
+ converged = true
+ case died || refusalOrUncertain(err):
+ s.coverage["resume"]++
+ case err != nil:
+ s.fail("unexpected error: " + err.Error())
+ }
+ if converged {
+ break
+ }
+ s.audit("operator-return")
+ if !s.active() {
+ converged = true
+ break
+ }
+ if s.last("return-hook") && !s.last("divergence-hold") {
+ s.check(blockedFlag(s.h), "divergence not flagged")
+ if f.states[fakeIID] == "Pending:Wait" {
+ s.coverage["diverged"]++
+ // The tool stopped. Only the provider moves next.
+ if s.providerReturns {
+ f.deadline = time.Time{}
+ f.states[fakeIID] = "Pending:Proceed"
+ s.schedule("Pending", "InService")
+ s.coverage["provider-return"]++
+ } else {
+ s.advance(901 * time.Second)
+ s.coverage["provider-abandon"]++
+ }
+ }
+ if s.last("failed-probe") {
+ s.check(f.states[fakeIID] == "Terminated", "unexpected failed probe")
+ s.coverage["failed"]++
+ converged = true
+ break
+ }
+ }
+ s.advance(3 * time.Second)
+ }
+ s.check(converged, "did not converge after fault injection stopped")
+ s.audit("end")
+ if f.hook {
+ if s.providerReturns {
+ s.check(s.last("divergence-held") && f.states[fakeIID] == "Standby", "hook return did not hold")
+ } else {
+ s.check(s.last("failed-probe") && f.states[fakeIID] == "Terminated", "provider loss not failed")
+ }
+ s.check(blockedFlag(s.h), "divergence not flagged")
+ s.check(!s.last("done"), "hook recorded as pass")
+ } else {
+ s.check(!s.active() && f.states[fakeIID] == "InService", "ordinary return not finished")
+ s.check(f.minimum == 2 && f.desired == 2 && f.maximum == 2, "ordinary return left the shape changed")
+ }
+ return s.coverage
+}
+
+// simSeeds is GROUPROLL_SIM_SEEDS (default 200) from GROUPROLL_SIM_START
+// (default 0).
+func simSeeds(t *testing.T) (start, count int64) {
+ t.Helper()
+ count, start = 200, 0
+ for name, p := range map[string]*int64{"GROUPROLL_SIM_SEEDS": &count, "GROUPROLL_SIM_START": &start} {
+ if v := os.Getenv(name); v != "" {
+ n, err := strconv.ParseInt(v, 10, 64)
+ if err != nil || n < 0 {
+ t.Fatalf("%s=%q", name, v)
+ }
+ *p = n
+ }
+ }
+ return start, count
+}
+
+// TestSeededSimulation: every seed converges with every audit holding;
+// with 50 or more seeds, every path the script's simulation covers is
+// covered, and deaths fell both between an intent and its dispatch and
+// between the provider's answer and its response row.
+func TestSeededSimulation(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 := runSeed(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("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{"describe-error", "diverged", "failed", "provider-return", "death", "resume",
+ "admission-drop", "admission-recovery", "loss:exit", "phase:ReturnHeld", "phase:Returning",
+ "phase:Serving", "death:before-api", "death:after-api"} {
+ if coverage[event] == 0 {
+ t.Errorf("coverage %s = 0", event)
+ }
+ }
+ }
+}
+
+// simAssertion is the script's test_simulation_mutations pattern: the
+// audits a classifier mutant must trip.
+var simAssertion = "lifecycle completion decision|divergence decision bypassed|terminated member recorded as pass|minimum decision in hold"
+
+// TestSimulationMutations: the script's five classifier mutants each fail
+// the simulation within 50 seeds, on the script's assertion.
+func TestSimulationMutations(t *testing.T) {
+ base := stateRoot(t)
+ swap := func(from string, to Decision) func(Facts) Decision {
+ return func(f Facts) Decision {
+ if d := Classify(f); d.Action == from {
+ return to
+ }
+ return Classify(f)
+ }
+ }
+ mutants := []struct {
+ name string
+ classify func(Facts) Decision
+ }{
+ {"continue", swap("diverged", Decision{Action: "complete"})},
+ {"abandon", swap("diverged", Decision{Action: "abandon"})},
+ {"divergence-not-flagged", swap("diverged", Decision{Action: "wait", Delay: waitDelay})},
+ {"terminated-pass", swap("failed", Decision{Action: "finish-return"})},
+ {"minimum-in-hold", swap("hold", Decision{Action: "restore-minimum"})},
+ }
+ for _, m := range mutants {
+ t.Run(m.name, func(t *testing.T) {
+ for seed := int64(0); seed < 50; seed++ {
+ _, err := runSeed(t, base, seed, m.classify)
+ if err == nil {
+ continue
+ }
+ first := strings.SplitN(strings.TrimPrefix(err.Error(), fmt.Sprintf("seed=%d: ", seed)), "\n", 2)[0]
+ if !regexp.MustCompile(simAssertion).MatchString(first) {
+ t.Fatalf("mutant failed on another assertion: %v", err)
+ }
+ t.Logf("simulation mutation caught: %s: seed %d: %s", m.name, seed, first)
+ return
+ }
+ t.Fatalf("%s survived the simulation", m.name)
+ })
+ }
+}