| new file mode 100644 |
| index 000000000..64d4ef9b3 |
| --- /dev/null |
| +++ b/internal/grouproll/roll_test.go |
| @@ -0,0 +1,2244 @@ |
| +//go:build linux || darwin |
| + |
| +package grouproll |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The roll verbs against the fake: ports of scripts/region_group_roll_test.py |
| +// (StandbyTests, CutTests, RoundOneTests, RollTransactionTests, |
| +// RoundTwoTests, RoundThreeTests, CloseLostArgvChecks and the roll halves |
| +// of the argv tests). Scenarios the required mutations rerun |
| +// (mutation_test.go) return an error instead of failing the test. |
| + |
| +var bg = context.Background() |
| + |
| +// rollOrder is the script's write order for a DR-4 roll. |
| +var rollOrder = []string{"prepare", "minimum", "enter", "permit", "apply", "exit", "minimum", "revoke"} |
| + |
| +// locked runs fn with a new engine while holding the group lock; a lock |
| +// another holder has is the "busy" refusal. |
| +func (h *harness) locked(fn func(e *Engine) error) error { |
| + unlock, err := h.state.Lock() |
| + if err != nil { |
| + return err |
| + } |
| + defer unlock() |
| + return fn(h.engine()) |
| +} |
| + |
| +func (h *harness) runRoll() error { return h.runRollTx("") } |
| + |
| +func (h *harness) runRollTx(tx string) error { |
| + return h.locked(func(e *Engine) error { return e.Roll(bg, fakeIID, newSHA, tx) }) |
| +} |
| + |
| +// activeTx is the open transaction ("" when none). |
| +func (h *harness) activeTx() string { |
| + h.t.Helper() |
| + tx, err := h.state.ActiveID() |
| + if err != nil { |
| + h.t.Fatalf("active transaction: %v", err) |
| + } |
| + return tx |
| +} |
| + |
| +// resume is StandbyTests.resume: the open transaction, resumed (or |
| +// returned). |
| +func (h *harness) resume() error { |
| + return h.locked(func(e *Engine) error { |
| + tx, err := h.state.ActiveID() |
| + if err != nil { |
| + return err |
| + } |
| + return e.Resume(bg, tx) |
| + }) |
| +} |
| + |
| +func (h *harness) returning() error { |
| + return h.locked(func(e *Engine) error { |
| + tx, err := h.state.ActiveID() |
| + if err != nil { |
| + return err |
| + } |
| + return e.Return(bg, tx) |
| + }) |
| +} |
| + |
| +func (h *harness) rollbackMember() error { |
| + return h.locked(func(e *Engine) error { |
| + tx, err := h.state.ActiveID() |
| + if err != nil { |
| + return err |
| + } |
| + return e.Rollback(bg, fakeIID, tx) |
| + }) |
| +} |
| + |
| +// txJournal opens transaction tx's journal read-only. |
| +func (h *harness) txJournal(tx string) *Journal { |
| + h.t.Helper() |
| + j, err := h.state.Load(tx, true) |
| + if err != nil { |
| + h.t.Fatalf("load %s: %v", tx, err) |
| + } |
| + h.t.Cleanup(func() { j.Close() }) |
| + return j |
| +} |
| + |
| +// onlyTx is the one transaction journal in the state directory. |
| +func (h *harness) onlyTx() string { |
| + h.t.Helper() |
| + paths, _ := filepath.Glob(filepath.Join(h.state.Directory(), "*"+journalSuffix)) |
| + if len(paths) != 1 { |
| + h.t.Fatalf("journals = %v, want one", paths) |
| + } |
| + return strings.TrimSuffix(filepath.Base(paths[0]), journalSuffix) |
| +} |
| + |
| +// appendRow adds a row to transaction tx's journal under the lock, as the |
| +// script tests' journal.add does. |
| +func (h *harness) appendRow(tx, kind string, fields map[string]any) { |
| + h.t.Helper() |
| + h.withLock(func() { |
| + j, err := h.state.Load(tx, false) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + defer j.Close() |
| + if _, err := j.Add(kind, fields); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + }) |
| +} |
| + |
| +// pauseAfterApply is RoundOneTests.pause_after_apply: the process dies |
| +// right after apply's write. |
| +func (h *harness) pauseAfterApply() { |
| + h.t.Helper() |
| + h.f.fault, h.f.faultAt = "death", 5 |
| + if !expectDeath(h.t, func() { h.runRoll() }) { |
| + h.t.Fatal("roll did not die at apply") |
| + } |
| +} |
| + |
| +// retained is assert_retained: the same two members, no launch, no |
| +// abandon, never a desired write, and no protocol breach. |
| +func (h *harness) retained() error { |
| + f := h.f |
| + if len(f.states) != 2 || f.states[fakeIID] == "" || f.states[fakePeer] == "" { |
| + return fmt.Errorf("members changed: %v", f.states) |
| + } |
| + if f.launches != 0 || f.abandons != 0 { |
| + return fmt.Errorf("launches %d abandons %d", f.launches, f.abandons) |
| + } |
| + for _, c := range f.calls { |
| + if c.Op == "desired" { |
| + return fmt.Errorf("desired written: %v", f.ops()) |
| + } |
| + } |
| + if len(f.violations) > 0 { |
| + return fmt.Errorf("protocol breaches: %v", f.violations) |
| + } |
| + return nil |
| +} |
| + |
| +func mustRetain(t *testing.T, h *harness) { |
| + t.Helper() |
| + if err := h.retained(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func countOf(xs []string, x string) int { |
| + n := 0 |
| + for _, s := range xs { |
| + if s == x { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +func isUncertain(err error) bool { |
| + var u Uncertain |
| + return errors.As(err, &u) |
| +} |
| + |
| +func blockedFlag(h *harness) bool { |
| + _, err := os.Lstat(h.state.DivergencePath()) |
| + return err == nil |
| +} |
| + |
| +// test_standby_roll_order (and test_default_transaction_is_uuid_hex's |
| +// write order): one roll writes in the script's order and leaves the |
| +// shape restored, the new artifact running and no transaction open. |
| +func scenarioStandbyRollOrder(h *harness) error { |
| + if err := h.runRoll(); err != nil { |
| + return err |
| + } |
| + f := h.f |
| + if !reflect.DeepEqual(f.writes, rollOrder) { |
| + return fmt.Errorf("writes %v, want %v", f.writes, rollOrder) |
| + } |
| + if f.minimum != 2 || f.desired != 2 || f.maximum != 2 { |
| + return fmt.Errorf("shape %d %d %d", f.minimum, f.desired, f.maximum) |
| + } |
| + if f.boxes[fakeIID]["binary_sha256"] != newSHA { |
| + return fmt.Errorf("binary %v", f.boxes[fakeIID]["binary_sha256"]) |
| + } |
| + if tx, err := h.state.ActiveID(); err != nil || tx != "" { |
| + return fmt.Errorf("active %q %v", tx, err) |
| + } |
| + return h.retained() |
| +} |
| + |
| +func TestRollStandbyOrder(t *testing.T) { |
| + if err := scenarioStandbyRollOrder(newHarness(t, 2)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// test_standby_response_loss: a lost answer at any write leaves a |
| +// transaction resume finishes, with one ExitStandby. |
| +func TestRollStandbyResponseLoss(t *testing.T) { |
| + for boundary := 1; boundary <= 8; boundary++ { |
| + t.Run(fmt.Sprint(boundary), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.fault, h.f.faultAt = "loss", boundary |
| + err := h.runRoll() |
| + if err != nil && !refusalOrUncertain(err) { |
| + t.Fatal(err) |
| + } |
| + if boundary == 6 && err != nil { |
| + // A lost ExitStandby answer is settled by the next |
| + // describe, not by stopping. |
| + t.Fatalf("roll after a lost exit answer = %v", err) |
| + } |
| + if h.activeTx() != "" { |
| + if err := h.resume(); err != nil { |
| + t.Fatalf("resume: %v\n%s", err, h.out.String()) |
| + } |
| + } |
| + if h.f.states[fakeIID] != "InService" || h.f.exits != 1 { |
| + t.Fatalf("state %s exits %d", h.f.states[fakeIID], h.f.exits) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_standby_resume and test_standby_resume_before_every_write: a death |
| +// after or before any write is resumed to the restored shape with one |
| +// ExitStandby. |
| +func TestRollStandbyResume(t *testing.T) { |
| + for _, before := range []bool{false, true} { |
| + for boundary := 1; boundary <= 8; boundary++ { |
| + t.Run(fmt.Sprintf("before=%v/%d", before, boundary), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.fault, h.f.faultAt, h.f.failBefore = "death", boundary, before |
| + if !expectDeath(t, func() { h.runRoll() }) { |
| + t.Fatal("no death") |
| + } |
| + if err := h.resume(); err != nil { |
| + t.Fatalf("resume: %v\n%s", err, h.out.String()) |
| + } |
| + if h.f.minimum != 2 || h.f.exits != 1 { |
| + t.Fatalf("minimum %d exits %d", h.f.minimum, h.f.exits) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// test_standby_shared_outage: an outage after the permit keeps the member |
| +// in Standby until the wait expires, with no ExitStandby, and resume |
| +// finishes once it clears. |
| +func scenarioStandbySharedOutage(h *harness) error { |
| + f := h.f |
| + f.after = func(name string) { |
| + if name == "permit" { |
| + f.outage = true |
| + } |
| + } |
| + start := f.now |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + return fmt.Errorf("roll = %v, want a refusal", err) |
| + } |
| + if f.states[fakeIID] != "Standby" || f.now.Sub(start) < standbyWait { |
| + return fmt.Errorf("state %s after %v", f.states[fakeIID], f.now.Sub(start)) |
| + } |
| + if f.exits != 0 || f.continues != 0 { |
| + return fmt.Errorf("exits %d continues %d", f.exits, f.continues) |
| + } |
| + if tx, _ := h.state.ActiveID(); tx == "" { |
| + return errors.New("transaction closed") |
| + } |
| + if err := h.retained(); err != nil { |
| + return err |
| + } |
| + f.outage, f.admitted = false, true |
| + f.boxes[fakeIID]["health"] = map[string]any{"state": "healthy", "code": int64(200)} |
| + if err := h.resume(); err != nil { |
| + return fmt.Errorf("resume: %w", err) |
| + } |
| + return h.retained() |
| +} |
| + |
| +func TestRollStandbySharedOutage(t *testing.T) { |
| + if err := scenarioStandbySharedOutage(newHarness(t, 2)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// test_hook_is_divergence_without_completion (test_standby_exit_pending_wait): |
| +// a return hook after ExitStandby is a divergence: no completion, the flag |
| +// written, an alert, the transaction kept, and resume writes nothing. |
| +func scenarioHookDivergence(h *harness, admitted bool) error { |
| + f := h.f |
| + f.hook, f.lossAfterExit = true, !admitted |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + return fmt.Errorf("roll = %v, want a refusal", err) |
| + } |
| + if f.states[fakeIID] != "Pending:Wait" || f.continues != 0 { |
| + return fmt.Errorf("state %s continues %d", f.states[fakeIID], f.continues) |
| + } |
| + for _, c := range f.calls { |
| + if c.Op == "complete" { |
| + return errors.New("lifecycle completion sent") |
| + } |
| + } |
| + if !blockedFlag(h) { |
| + return errors.New("divergence not flagged") |
| + } |
| + if !strings.Contains(h.out.String(), "ALERT") { |
| + return errors.New("no alert said") |
| + } |
| + tx, _ := h.state.ActiveID() |
| + if tx == "" { |
| + return errors.New("transaction closed") |
| + } |
| + j := h.txJournal(tx) |
| + if _, ok := j.Last("return-hook", nil); !ok { |
| + return errors.New("no return-hook row") |
| + } |
| + if _, ok := j.Last("alert", nil); !ok { |
| + return errors.New("no alert row") |
| + } |
| + if _, ok := j.Last("done", nil); ok { |
| + return errors.New("done recorded") |
| + } |
| + if !f.now.Before(f.deadline) { |
| + return errors.New("waited past the hook deadline") |
| + } |
| + writes := append([]string(nil), f.writes...) |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + return fmt.Errorf("resume = %v, want a refusal", err) |
| + } |
| + if !reflect.DeepEqual(writes, f.writes) { |
| + return fmt.Errorf("resume wrote %v", f.writes[len(writes):]) |
| + } |
| + return nil |
| +} |
| + |
| +func TestRollHookIsDivergenceWithoutCompletion(t *testing.T) { |
| + for _, admitted := range []bool{true, false} { |
| + t.Run(fmt.Sprintf("admitted=%v", admitted), func(t *testing.T) { |
| + if err := scenarioHookDivergence(newHarness(t, 2), admitted); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_standby_exit_pending_wait_resume_and_loss: a death or lost answer |
| +// at ExitStandby with a hook still ends held at Pending:Wait, flagged, |
| +// with one ExitStandby. |
| +func TestRollExitPendingWaitResumeAndLoss(t *testing.T) { |
| + cases := []struct { |
| + before bool |
| + fault string |
| + }{{false, "death"}, {true, "death"}, {false, "loss"}} |
| + for _, c := range cases { |
| + t.Run(fmt.Sprintf("before=%v/%s", c.before, c.fault), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.hook, h.f.failBefore = true, c.before |
| + h.f.fault, h.f.faultAt = c.fault, 6 |
| + var err error |
| + died := expectDeath(t, func() { err = h.runRoll() }) |
| + if !died && (refusalKey(err) == "" || isUncertain(err)) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if h.f.continues != 0 || h.f.exits != 1 || h.f.states[fakeIID] != "Pending:Wait" || !blockedFlag(h) { |
| + t.Fatalf("continues %d exits %d state %s blocked %v", h.f.continues, h.f.exits, |
| + h.f.states[fakeIID], blockedFlag(h)) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_default_abandon_and_resume_stay_failed |
| +// (test_standby_exit_pending_wait_admission_loss): the provider abandons |
| +// the held member; every resume is a failed probe that stays open, and |
| +// the flag blocks a new preflight. |
| +func scenarioDefaultAbandon(h *harness) error { |
| + f := h.f |
| + f.hook = true |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + return fmt.Errorf("roll = %v, want a refusal", err) |
| + } |
| + f.sleep(900 * time.Second) |
| + if f.states[fakeIID] != "Terminated" || f.abandons != 1 || f.launches != 1 { |
| + return fmt.Errorf("fake did not abandon: %s %d %d", f.states[fakeIID], f.abandons, f.launches) |
| + } |
| + for i := 0; i < 2; i++ { |
| + err := h.resume() |
| + if !isStop(err, "failed-probe") { |
| + return fmt.Errorf("resume %d = %v, want a failed probe", i, err) |
| + } |
| + tx, _ := h.state.ActiveID() |
| + if tx == "" { |
| + return errors.New("transaction closed") |
| + } |
| + j := h.txJournal(tx) |
| + if _, ok := j.Last("failed-probe", nil); !ok { |
| + return errors.New("no failed-probe row") |
| + } |
| + if _, ok := j.Last("done", nil); ok { |
| + return errors.New("done recorded") |
| + } |
| + } |
| + if !strings.Contains(h.out.String(), "FAIL") || f.continues != 0 { |
| + return fmt.Errorf("output %q continues %d", h.out.String(), f.continues) |
| + } |
| + writes := append([]string(nil), f.writes...) |
| + if _, _, err := h.engine().preflight(bg, fakeIID, newSHA); refusalKey(err) != "blocked" { |
| + return fmt.Errorf("preflight = %v, want blocked", err) |
| + } |
| + if !reflect.DeepEqual(writes, f.writes) { |
| + return errors.New("preflight wrote") |
| + } |
| + return nil |
| +} |
| + |
| +func TestRollDefaultAbandonAndResumeStayFailed(t *testing.T) { |
| + if err := scenarioDefaultAbandon(newHarness(t, 2)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// test_precheck_failures_before_minimum: a refusal before the group's |
| +// first write leaves minimum and Standby untouched. |
| +func TestRollPrecheckFailuresBeforeMinimum(t *testing.T) { |
| + cases := map[string]func(f *fake){ |
| + "offline": func(f *fake) { f.online = false }, |
| + "prepare": func(f *fake) { f.prepareBad = true }, |
| + "minimum": func(f *fake) { f.minimum = 1 }, |
| + "wrong group": func(f *fake) { f.boxes[fakeIID]["group"] = "wrong" }, |
| + "peer health": func(f *fake) { f.boxes[fakePeer]["health"].(map[string]any)["state"] = "unknown" }, |
| + "not admitted": func(f *fake) { f.admitted = false }, |
| + } |
| + for name, change := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + change(h.f) |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if countOf(h.f.writes, "minimum") != 0 || countOf(h.f.writes, "enter") != 0 { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_lock_refuses_second_writer: a held lock refuses the roll before any |
| +// write. |
| +func scenarioLockRefusesSecondWriter(h *harness) error { |
| + unlock, err := h.state.Lock() |
| + if err != nil { |
| + return err |
| + } |
| + defer unlock() |
| + other, err := OpenState(h.root, h.c, false) |
| + if err != nil { |
| + return err |
| + } |
| + other.fsync = h.state.fsync |
| + second := &harness{t: h.t, f: h.f, c: h.c, root: h.root, state: other} |
| + if err := second.runRoll(); refusalKey(err) != "busy" { |
| + return fmt.Errorf("second writer = %v, want busy", err) |
| + } |
| + if len(h.f.writes) != 0 { |
| + return fmt.Errorf("writes %v", h.f.writes) |
| + } |
| + return nil |
| +} |
| + |
| +func TestRollLockRefusesSecondWriter(t *testing.T) { |
| + if err := scenarioLockRefusesSecondWriter(newHarness(t, 2)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// test_rollback_same_transaction: after apply's write dies, rollback in |
| +// the same transaction revokes, permits and runs rollback, then returns. |
| +func TestRollRollbackSameTransaction(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + tx := h.activeTx() |
| + if err := h.rollbackMember(); err != nil { |
| + t.Fatalf("rollback: %v\n%s", err, h.out.String()) |
| + } |
| + if h.f.boxes[fakeIID]["binary_sha256"] != oldSHA { |
| + t.Fatal("old artifact not restored") |
| + } |
| + if got := h.f.writes[5:9]; !reflect.DeepEqual(got, []string{"revoke", "permit", "rollback", "exit"}) { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + want := map[[2]string]bool{{tx, "apply"}: true, {tx, "rollback"}: true} |
| + if !reflect.DeepEqual(h.f.used, want) { |
| + t.Fatalf("used %v", h.f.used) |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_standby_rollback_crash_boundaries: a death at any rollback write |
| +// is resumed to the old artifact in service. |
| +func TestRollRollbackCrashBoundaries(t *testing.T) { |
| + for boundary := 6; boundary <= 11; boundary++ { |
| + t.Run(fmt.Sprint(boundary), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.f.fault, h.f.faultAt = "death", boundary |
| + if !expectDeath(t, func() { h.rollbackMember() }) { |
| + t.Fatal("rollback did not die") |
| + } |
| + if err := h.resume(); err != nil { |
| + t.Fatalf("resume: %v\n%s", err, h.out.String()) |
| + } |
| + if h.f.boxes[fakeIID]["binary_sha256"] != oldSHA || h.f.states[fakeIID] != "InService" { |
| + t.Fatalf("binary %v state %s", h.f.boxes[fakeIID]["binary_sha256"], h.f.states[fakeIID]) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_standby_preinservice_is_not_inservice: healthy targets during |
| +// PreInService never authorize the minimum restore. |
| +func scenarioPreInService(h *harness) error { |
| + f := h.f |
| + polls := 0 |
| + f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if err != nil { |
| + return r, err |
| + } |
| + switch { |
| + case op == "exit": |
| + f.states[fakeIID] = "PreInService" |
| + case op == "group" && f.states[fakeIID] == "PreInService": |
| + polls++ |
| + // Targets finish warming before the lifecycle transition. |
| + if polls == 9 { |
| + f.states[fakeIID] = "InService" |
| + } |
| + case op == "minimum" && args["value"] == 2 && f.states[fakeIID] != "InService": |
| + f.violate("minimum restored in %s", f.states[fakeIID]) |
| + } |
| + return r, nil |
| + } |
| + if err := h.runRoll(); err != nil { |
| + return err |
| + } |
| + if polls < 9 || f.exits != 1 { |
| + return fmt.Errorf("polls %d exits %d", polls, f.exits) |
| + } |
| + if len(f.violations) > 0 { |
| + return fmt.Errorf("%v", f.violations) |
| + } |
| + return nil |
| +} |
| + |
| +func TestRollPreInServiceIsNotInService(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.collect = true |
| + if err := scenarioPreInService(h); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// test_standby_pending_proceed_without_completion. |
| +func TestRollPendingProceedWithoutCompletion(t *testing.T) { |
| + h := newHarness(t, 2) |
| + polls := 0 |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if err == nil && op == "exit" { |
| + h.f.states[fakeIID] = "Pending:Proceed" |
| + } |
| + if err == nil && op == "group" && h.f.states[fakeIID] == "Pending:Proceed" { |
| + if polls++; polls == 3 { |
| + h.f.states[fakeIID] = "InService" |
| + } |
| + } |
| + return r, err |
| + } |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if polls < 3 || h.f.continues != 0 { |
| + t.Fatalf("polls %d continues %d", polls, h.f.continues) |
| + } |
| +} |
| + |
| +// test_fake_abandon_terminates_and_replaces: the fake's own hook deadline. |
| +func TestFakeAbandonTerminatesAndReplaces(t *testing.T) { |
| + h := newHarness(t, 2) |
| + f := h.f |
| + f.hook, f.states[fakeIID] = true, "Standby" |
| + f.desired, f.minimum = 1, 1 |
| + if _, err := f.Unpark(bg, fakeIID); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.sleep(901 * time.Second) |
| + replacement := "i-" + strings.Repeat("3", 17) |
| + if f.abandons != 1 || f.states[fakeIID] != "Terminated" || f.states[replacement] != "Pending:Wait" || f.launches != 1 { |
| + t.Fatalf("%d %v", f.abandons, f.states) |
| + } |
| + g, _ := f.Describe(bg) |
| + if _, ok := g.Members[fakeIID]; ok { |
| + t.Fatal("abandoned member still listed") |
| + } |
| +} |
| + |
| +// test_fake_capacity_rules. |
| +func TestFakeCapacityRules(t *testing.T) { |
| + f := newFake(t, 2) |
| + if _, err := f.Park(bg, fakeIID); err == nil { |
| + t.Fatal("park below minimum accepted") |
| + } |
| + f.desired, f.minimum = 1, 1 |
| + if _, err := f.SetMinimum(bg, 2); err != nil || f.desired != 2 { |
| + t.Fatalf("minimum did not raise desired: %v %d", err, f.desired) |
| + } |
| +} |
| + |
| +// test_standby_return_process_or_transaction_changes: a changed process, |
| +// permit transaction or boot keeps the member in Standby. |
| +func TestRollReturnProcessOrTransactionChanges(t *testing.T) { |
| + for _, kind := range []string{"process", "transaction", "boot"} { |
| + t.Run(kind, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + box := h.f.boxes[fakeIID] |
| + switch kind { |
| + case "transaction": |
| + h.f.permit(fakeIID)["transaction"] = "other" |
| + case "boot": |
| + box["boot_id"] = "other" |
| + default: |
| + h.f.edge(fakeIID)["identity"] = box["boot_id"].(string) + ":100:100" |
| + } |
| + if err := h.returning(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("return = %v", err) |
| + } |
| + if h.f.exits != 0 { |
| + t.Fatal("member returned") |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_standby_post_exit_api_loss_is_resumable: a describe outage after a |
| +// lost ExitStandby answer stops resumable without a flag; the next |
| +// resume sees the hook and flags it. |
| +func TestRollPostExitAPILossIsResumable(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.hook = true |
| + h.f.fault, h.f.faultAt = "loss", 6 |
| + failing := true |
| + h.f.before = func(op string, args map[string]any) error { |
| + if failing && op == "group" && h.f.exits > 0 { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + if err := h.runRoll(); !isUncertain(err) { |
| + t.Fatalf("roll = %v, want uncertain", err) |
| + } |
| + if !h.f.now.Before(h.f.deadline) || h.f.continues != 0 || blockedFlag(h) { |
| + t.Fatalf("now %v deadline %v blocked %v", h.f.now, h.f.deadline, blockedFlag(h)) |
| + } |
| + failing = false |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if !blockedFlag(h) { |
| + t.Fatal("divergence not flagged") |
| + } |
| +} |
| + |
| +// test_consumed_uncertain_action_never_replays. |
| +func TestRollConsumedUncertainActionNeverReplays(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.f.boxes[fakeIID]["binary_sha256"] = oldSHA |
| + before := append([]string(nil), h.f.writes...) |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if !reflect.DeepEqual(before, h.f.writes) || h.f.states[fakeIID] != "Standby" { |
| + t.Fatalf("writes %v state %s", h.f.writes, h.f.states[fakeIID]) |
| + } |
| +} |
| + |
| +// test_permit_readiness_requires_action_and_unconsumed. |
| +func TestRollPermitRequiresActionAndUnconsumed(t *testing.T) { |
| + for _, c := range []struct { |
| + field string |
| + value any |
| + }{{"accepted", false}, {"consumed", true}, {"action", "repair"}} { |
| + t.Run(c.field, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.fault, h.f.faultAt = "death", 4 |
| + if !expectDeath(t, func() { h.runRoll() }) { |
| + t.Fatal("no death") |
| + } |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if err == nil && op == "session" && args["verb"] == "status" && args["iid"] == fakeIID { |
| + r.(map[string]any)["permit"].(map[string]any)[c.field] = c.value |
| + } |
| + return r, err |
| + } |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if countOf(h.f.writes, "apply") != 0 { |
| + t.Fatal("apply ran") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_stale_and_racing_readiness, the roll half: nothing is written. |
| +func TestRollStaleAndRacingReadiness(t *testing.T) { |
| + for _, race := range []string{"generation", "slow", "restart"} { |
| + t.Run(race, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + edgesRace(h, race) |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_journal_missing_or_corrupt_refuses_before_write. |
| +func TestRollJournalMissingOrCorruptRefusesBeforeWrite(t *testing.T) { |
| + for _, fault := range []string{"missing", "partial", "changed", "lost-active", "symlink"} { |
| + t.Run(fault, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.fault, h.f.faultAt = "death", 3 |
| + if !expectDeath(t, func() { h.runRoll() }) { |
| + t.Fatal("no death") |
| + } |
| + tx := h.activeTx() |
| + path := h.state.journalPath(tx) |
| + switch fault { |
| + case "missing": |
| + must(t, os.Remove(path)) |
| + case "partial": |
| + f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) |
| + must(t, err) |
| + _, err = f.WriteString(`{"partial":`) |
| + must(t, err) |
| + must(t, f.Close()) |
| + case "changed": |
| + raw, err := os.ReadFile(path) |
| + must(t, err) |
| + must(t, os.WriteFile(path, []byte(strings.Replace(string(raw), newSHA, oldSHA, 1)), 0o600)) |
| + case "lost-active": |
| + must(t, os.Remove(filepath.Join(h.state.Directory(), activeFile))) |
| + case "symlink": |
| + saved := path + ".saved" |
| + must(t, os.Rename(path, saved)) |
| + must(t, os.Symlink(saved, path)) |
| + } |
| + before := append([]string(nil), h.f.writes...) |
| + err := h.locked(func(e *Engine) error { return e.Resume(bg, tx) }) |
| + if refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if !reflect.DeepEqual(before, h.f.writes) { |
| + t.Fatalf("wrote %v", h.f.writes[len(before):]) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_hook_observed_before_target_describe_error_blocks. |
| +func TestRollHookObservedBeforeTargetErrorBlocks(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.hook = true |
| + h.f.before = func(op string, args map[string]any) error { |
| + if op == "targets" && h.f.states[fakeIID] == "Pending:Wait" { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !blockedFlag(h) || h.f.continues != 0 { |
| + t.Fatal("hook not flagged") |
| + } |
| + j := h.txJournal(h.activeTx()) |
| + if _, ok := j.Last("return-hook", nil); !ok { |
| + t.Fatal("no return-hook row") |
| + } |
| + if _, ok := j.Last("done", nil); ok { |
| + t.Fatal("done recorded") |
| + } |
| +} |
| + |
| +// test_death_during_divergence_recording: a death while the divergence is |
| +// recorded is repaired: the hook is alerted first, then the provider's |
| +// return is held. |
| +func TestRollDeathDuringDivergenceRecording(t *testing.T) { |
| + for _, boundary := range []string{"response", "snapshot", "return-hook", "alert"} { |
| + t.Run(boundary, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.hook = true |
| + h.afterEvent = func(kind string, row Row) { |
| + if kind == boundary && h.f.states[fakeIID] == "Pending:Wait" && (kind != "response" || row["op"] == "group") { |
| + panic(fakeDeath{kind}) |
| + } |
| + } |
| + if !expectDeath(t, func() { h.runRoll() }) { |
| + t.Fatal("no death") |
| + } |
| + h.afterEvent = nil |
| + h.f.states[fakeIID], h.f.deadline = "InService", time.Time{} |
| + for i := 0; i < 2; i++ { |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume %d = %v", i, err) |
| + } |
| + } |
| + if h.f.states[fakeIID] != "Standby" || !blockedFlag(h) || h.f.continues != 0 { |
| + t.Fatalf("state %s blocked %v", h.f.states[fakeIID], blockedFlag(h)) |
| + } |
| + j := h.txJournal(h.activeTx()) |
| + for _, k := range []string{"return-hook", "divergence-held"} { |
| + if _, ok := j.Last(k, nil); !ok { |
| + t.Fatalf("no %s row", k) |
| + } |
| + } |
| + if _, ok := j.Last("done", nil); ok { |
| + t.Fatal("done recorded") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_provider_return_without_tool_completion_is_held. |
| +func TestRollProviderReturnIsHeld(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.hook = true |
| + if err := h.runRoll(); refusalKey(err) == "" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + h.f.states[fakeIID], h.f.admitted, h.f.deadline = "InService", false, time.Time{} |
| + if err := h.resume(); !isStop(err, "divergence-held") { |
| + t.Fatalf("resume = %v, want divergence held", err) |
| + } |
| + f := h.f |
| + if f.states[fakeIID] != "Standby" || f.tg[fakeIID] != "unused" || f.minimum != 1 || f.desired != 1 || f.continues != 0 { |
| + t.Fatalf("state %s tg %s shape %d %d", f.states[fakeIID], f.tg[fakeIID], f.minimum, f.desired) |
| + } |
| +} |
| + |
| +// test_prepare_previous_results_refuse_before_group_write. |
| +func TestRollPreparePreviousResults(t *testing.T) { |
| + for previous, key := range map[string]string{"applied": "already_applied", |
| + "rolled-back": "already_rolled_back", "rollback-failed": "rollback_failed"} { |
| + t.Run(previous, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.previousResult = previous |
| + if err := h.runRoll(); refusalKey(err) != key { |
| + t.Fatalf("roll = %v, want %s", err, key) |
| + } |
| + if !reflect.DeepEqual(h.f.writes, []string{"prepare"}) { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_release_floor_matches_go (the roll half; the config half is |
| +// TestConfigMatchesScriptValidation). |
| +func TestRollReleaseFloor(t *testing.T) { |
| + for version, below := range map[string]bool{"v0.33.99": true, "0.33.0": true, "v0.34.0": false, |
| + "1.0.0": false, "0.9.0": true, "dev": false, "v00.33.0": false, "0.33.0-1": false, |
| + "v0.33.0+build": false, "v0.33.0\n": false, "v0.33.0000000000": false, "v0.33.١": false} { |
| + if belowFloor(version, "v0.34.0") != below { |
| + t.Errorf("belowFloor(%q) = %v", version, !below) |
| + } |
| + } |
| + h := newHarness(t, 2) |
| + h.f.version = "v0.33.0" |
| + if err := h.runRoll(); refusalKey(err) != "release_floor" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !reflect.DeepEqual(h.f.writes, []string{"prepare"}) { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| +} |
| + |
| +// test_unparseable_pointer_versions_refuse_before_group_write. |
| +func TestRollUnparseablePointerVersions(t *testing.T) { |
| + for _, version := range []string{"dev", "v00.34.0", "0.34.0+build", "0.34.0-rc1", "0.34", "v0.34.١"} { |
| + t.Run(version, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.version = version |
| + if err := h.runRoll(); refusalKey(err) != "release_version" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !reflect.DeepEqual(h.f.writes, []string{"prepare"}) { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_wrong_digest_or_unchanged_process_is_immediate: a wrong artifact or |
| +// an unchanged process after apply or rollback alerts at once, in |
| +// Standby, with the permit kept. |
| +func TestRollWrongDigestOrUnchangedProcess(t *testing.T) { |
| + for _, action := range []string{"apply", "rollback"} { |
| + for _, bad := range []string{"digest", "process"} { |
| + t.Run(action+"/"+bad, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if action == "rollback" { |
| + h.pauseAfterApply() |
| + } |
| + before := copyArgs(h.f.edge(fakeIID)) |
| + h.f.after = func(name string) { |
| + if name != action { |
| + return |
| + } |
| + if bad == "digest" { |
| + h.f.boxes[fakeIID]["binary_sha256"] = strings.Repeat("d", 64) |
| + } else { |
| + h.f.boxes[fakeIID]["edge"] = copyArgs(before) |
| + } |
| + } |
| + start := h.f.now |
| + var err error |
| + if action == "apply" { |
| + err = h.runRoll() |
| + } else { |
| + err = h.rollbackMember() |
| + } |
| + if refusalKey(err) != "process" { |
| + t.Fatalf("%s = %v", action, err) |
| + } |
| + if h.f.now.Sub(start) >= 10*time.Second || !strings.Contains(h.out.String(), "ALERT") { |
| + t.Fatalf("took %v", h.f.now.Sub(start)) |
| + } |
| + if h.f.states[fakeIID] != "Standby" || h.f.exits != 0 || h.f.permit(fakeIID)["state"] != "present" { |
| + t.Fatalf("state %s exits %d permit %v", h.f.states[fakeIID], h.f.exits, h.f.permit(fakeIID)) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// test_publication_lag_and_two_second_margin, the roll half. |
| +func TestRollPublicationLag(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.publicationLag = 20 * time.Second |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.f.now.Sub(fakeStart) < 20*time.Second { |
| + t.Fatalf("roll took %v", h.f.now.Sub(fakeStart)) |
| + } |
| + for _, lag := range []time.Duration{0, time.Second, 1999 * time.Millisecond} { |
| + t.Run(lag.String(), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.f.publicationLag = lag |
| + if err := h.resume(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if h.f.exits != 0 { |
| + t.Fatal("member returned") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_readiness_clock_starts_at_first_response_and_peers_get_sixty, the |
| +// roll half. |
| +func TestRollReadinessClockStartsAtFirstResponse(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.before = func(op string, args map[string]any) error { |
| + if op == "session" && args["verb"] == "status" { |
| + if args["iid"] == fakePeer { |
| + h.f.sleep(20 * time.Second) |
| + } else { |
| + h.f.sleep(3 * time.Second) |
| + } |
| + } |
| + return nil |
| + } |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.f.exits != 1 { |
| + t.Fatalf("exits %d", h.f.exits) |
| + } |
| +} |
| + |
| +// test_divergence_hold_crash_and_response_loss. |
| +func TestRollDivergenceHoldCrashAndResponseLoss(t *testing.T) { |
| + cases := []struct { |
| + before bool |
| + fault string |
| + }{{false, "death"}, {true, "death"}, {false, "loss"}} |
| + for _, c := range cases { |
| + t.Run(fmt.Sprintf("before=%v/%s", c.before, c.fault), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.hook = true |
| + if err := h.runRoll(); refusalKey(err) == "" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + h.f.states[fakeIID], h.f.deadline = "InService", time.Time{} |
| + h.f.failBefore, h.f.fault, h.f.faultAt = c.before, c.fault, 7 |
| + var err error |
| + if died := expectDeath(t, func() { err = h.resume() }); !died && (refusalKey(err) == "" || isUncertain(err)) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if err := h.resume(); !isStop(err, "divergence-held") { |
| + t.Fatalf("second resume = %v", err) |
| + } |
| + writes := append([]string(nil), h.f.writes...) |
| + if err := h.returning(); !isStop(err, "divergence-held") { |
| + t.Fatalf("return = %v", err) |
| + } |
| + f := h.f |
| + if !reflect.DeepEqual(writes, f.writes) || f.continues != 0 || f.states[fakeIID] != "Standby" || |
| + f.minimum != 1 || f.desired != 1 || countOf(f.writes, "enter") != 2 { |
| + t.Fatalf("writes %v state %s shape %d %d", f.writes, f.states[fakeIID], f.minimum, f.desired) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_cut_apply_terminates_session_then_reads_status. |
| +func TestRollCutApplyTerminatesSessionThenReadsStatus(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.sessions = func(iid, verb string) []string { |
| + if verb == "apply" { |
| + return []string{"owned-session"} |
| + } |
| + return nil |
| + } |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if err == nil && op == "session" && args["verb"] == "apply" { |
| + return nil, Uncertain{Key: "remote", Timeout: true} |
| + } |
| + return r, err |
| + } |
| + if err := h.runRoll(); !isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + for i, c := range h.f.calls { |
| + if c.Op == "session" && c.Args["verb"] == "apply" { |
| + next := h.f.calls[i+1 : i+3] |
| + if next[0].Op != "terminate_session" || next[0].Args["session_id"] != "owned-session" || |
| + next[1].Op != "session" || !reflect.DeepEqual(next[1].Args, map[string]any{"iid": fakeIID, "verb": "status"}) { |
| + t.Fatalf("after apply: %v", next) |
| + } |
| + return |
| + } |
| + } |
| + t.Fatal("no apply call") |
| +} |
| + |
| +// test_unexpected_exit_success_is_journaled_before_describe. |
| +func TestRollUnexpectedExitSuccessIsJournaled(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if err == nil && op == "exit" { |
| + return WriteResult{Uncertain: true, Response: map[string]any{}}, nil |
| + } |
| + return r, err |
| + } |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + j := h.txJournal(h.onlyTx()) |
| + resp, ok := j.Last("response", map[string]any{"op": "exit"}) |
| + if !ok || resp["result"].(map[string]any)["outcome"] != "uncertain-success" { |
| + t.Fatalf("exit response %v", resp) |
| + } |
| + for _, r := range j.Rows()[rowSeq(resp)+1:] { |
| + if r["kind"] == "intent" { |
| + if r["op"] != "group" { |
| + t.Fatalf("first call after exit: %v", r["op"]) |
| + } |
| + return |
| + } |
| + } |
| + t.Fatal("no call after exit") |
| +} |
| + |
| +// test_expired_exit_observation_leaves_resumable_record: a readiness read |
| +// older than 5 s at ExitStandby (the intent's fsync counted) sends |
| +// nothing and stays resumable. |
| +func TestRollExpiredExitObservationIsResumable(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.afterEvent = func(kind string, row Row) { |
| + if kind == "intent" && row["op"] == "exit" { |
| + h.f.sleep(6 * time.Second) |
| + } |
| + } |
| + if err := h.resume(); refusalKey(err) != "admission" { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if h.f.exits != 0 || blockedFlag(h) { |
| + t.Fatalf("exits %d blocked %v", h.f.exits, blockedFlag(h)) |
| + } |
| + h.afterEvent = nil |
| + if err := h.resume(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.f.exits != 1 { |
| + t.Fatalf("exits %d", h.f.exits) |
| + } |
| +} |
| + |
| +// test_ordinary_describe_blip_and_interrupt_do_not_block: a describe |
| +// failure or Ctrl-C after ExitStandby stops without a flag or a failed |
| +// probe, the error journaled, and resume finishes. |
| +func TestRollDescribeBlipAndInterruptDoNotBlock(t *testing.T) { |
| + for _, failure := range []error{Uncertain{Key: "api"}, context.Canceled} { |
| + name := errorName(failure) |
| + t.Run(name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + failing := true |
| + h.f.before = func(op string, args map[string]any) error { |
| + if failing && op == "group" && h.f.exits > 0 { |
| + return failure |
| + } |
| + return nil |
| + } |
| + if err := h.runRoll(); !errors.Is(err, failure) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if blockedFlag(h) { |
| + t.Fatal("flagged") |
| + } |
| + j := h.txJournal(h.activeTx()) |
| + if _, ok := j.Last("failed-probe", nil); ok { |
| + t.Fatal("failed probe") |
| + } |
| + if last, _ := j.Last("error", nil); last["error"] != name { |
| + t.Fatalf("error row %v", last) |
| + } |
| + failing = false |
| + if err := h.resume(); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_unknown_or_replaced_member_is_explicit_failed_probe. |
| +func TestRollUnknownOrReplacedMemberIsFailedProbe(t *testing.T) { |
| + for _, phase := range []string{"Unknown", "Terminated", "replaced"} { |
| + t.Run(phase, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.after = func(name string) { |
| + if name != "exit" { |
| + return |
| + } |
| + if phase == "replaced" { |
| + h.f.states[fakeIID] = "Terminated" |
| + other := "i-" + strings.Repeat("3", 17) |
| + h.f.states[other] = "InService" |
| + h.f.order = append(h.f.order, other) |
| + } else { |
| + h.f.states[fakeIID] = phase |
| + } |
| + } |
| + if err := h.runRoll(); !isStop(err, "failed-probe") { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + row, ok := h.txJournal(h.activeTx()).Last("failed-probe", nil) |
| + if !ok { |
| + t.Fatal("no failed-probe row") |
| + } |
| + if phase != "Unknown" && row["reason"] != Text("lost_member") { |
| + t.Fatalf("reason %v", row["reason"]) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_external_minimum_change_is_not_adopted. |
| +func TestRollExternalMinimumChangeIsNotAdopted(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.after = func(name string) { |
| + if name == "prepare" { |
| + h.f.minimum = 1 |
| + } |
| + } |
| + if err := h.runRoll(); refusalKey(err) != "shape" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !reflect.DeepEqual(h.f.writes, []string{"prepare"}) { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| +} |
| + |
| +// test_resume_reads_status_first_after_cut_apply. |
| +func TestRollResumeReadsStatusFirstAfterCutApply(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.f.calls = nil |
| + if err := h.resume(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if c := h.f.calls[0]; c.Op != "session" || !reflect.DeepEqual(c.Args, map[string]any{"iid": fakeIID, "verb": "status"}) { |
| + t.Fatalf("first call %v", c) |
| + } |
| +} |
| + |
| +// test_chosen_transaction_cli_reaches_journal_active_and_permit (the |
| +// engine half; TestCLIGroupLeaves covers the flag). |
| +func TestRollChosenTransaction(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := "B6_fault-2026_11_05" |
| + var observed []any |
| + h.f.after = func(name string) { |
| + if name == "permit" { |
| + v, err := h.state.Read(h.state.activePath()) |
| + must(t, err) |
| + observed = append(observed, v) |
| + if h.f.permit(fakeIID)["transaction"] != tx { |
| + t.Errorf("permit transaction %v", h.f.permit(fakeIID)["transaction"]) |
| + } |
| + } |
| + } |
| + if err := h.runRollTx(tx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(observed, []any{map[string]any{"transaction": tx}}) { |
| + t.Fatalf("active at permit: %v", observed) |
| + } |
| + j := h.txJournal(tx) |
| + if j.Rows()[0]["transaction"] != tx { |
| + t.Fatal("begin row") |
| + } |
| + if _, ok := j.Last("done", nil); !ok || h.activeTx() != "" { |
| + t.Fatal("not finished") |
| + } |
| +} |
| + |
| +// test_finished_transaction_refuses_without_calls_or_writes. |
| +func TestRollFinishedTransactionRefuses(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + tx := h.onlyTx() |
| + h.f.calls = nil |
| + before := snapshotFiles(t, h.state.Directory()) |
| + err := h.locked(func(e *Engine) error { return e.Roll(bg, fakeIID, oldSHA, tx) }) |
| + if refusalKey(err) != "record" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !reflect.DeepEqual(before, snapshotFiles(t, h.state.Directory())) || len(h.f.calls) != 0 { |
| + t.Fatalf("calls %v", h.f.ops()) |
| + } |
| +} |
| + |
| +// test_unfinished_transaction_refuses_without_calls_or_writes. |
| +func TestRollUnfinishedTransactionRefuses(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := "unfinished-roll" |
| + h.withLock(func() { |
| + j, err := h.state.Create(Header{Transaction: tx}) |
| + must(t, err) |
| + j.Close() |
| + }) |
| + before := snapshotFiles(t, h.state.Directory()) |
| + if err := h.runRollTx(tx); refusalKey(err) != "active" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !reflect.DeepEqual(before, snapshotFiles(t, h.state.Directory())) || len(h.f.calls) != 0 { |
| + t.Fatalf("calls %v", h.f.ops()) |
| + } |
| +} |
| + |
| +// test_invalid_or_probe_transaction_refuses_before_state_access: refused |
| +// as record without the lock (so before any state read) and with no call. |
| +func TestRollInvalidOrProbeTransactionRefuses(t *testing.T) { |
| + h := newHarness(t, 2) |
| + before := snapshotFiles(t, h.state.Directory()) |
| + for _, tx := range []string{"../escape", "has.dot", "space id", strings.Repeat("x", 81), "id\n", "café", |
| + "probe-", "probe-test", "-dash"} { |
| + if err := h.engine().Roll(bg, fakeIID, newSHA, tx); refusalKey(err) != "record" { |
| + t.Errorf("%q: %v", tx, err) |
| + } |
| + } |
| + if !reflect.DeepEqual(before, snapshotFiles(t, h.state.Directory())) || len(h.f.calls) != 0 { |
| + t.Fatalf("calls %v", h.f.ops()) |
| + } |
| +} |
| + |
| +// test_default_transaction_is_uuid_hex. |
| +func TestRollDefaultTransactionIsUUIDHex(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + tx := h.onlyTx() |
| + if !regexp.MustCompile(`^[0-9a-f]{32}$`).MatchString(tx) || h.txJournal(tx).Rows()[0]["transaction"] != tx { |
| + t.Fatalf("transaction %q", tx) |
| + } |
| + if !reflect.DeepEqual(h.f.writes, rollOrder) { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| +} |
| + |
| +// The begin row records the caller identity (spec V9), and a failed |
| +// identity read writes nothing. |
| +func TestRollRecordsCallerIdentity(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := h.txJournal(h.onlyTx()).Rows()[0]["caller_user_id"]; got != h.f.userID { |
| + t.Fatalf("caller_user_id %v", got) |
| + } |
| + if ops := h.f.ops(); ops[0] != "caller" || ops[1] != "group" { |
| + t.Fatalf("first calls %v", ops[:2]) |
| + } |
| + h = newHarness(t, 2) |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "caller" { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + before := snapshotFiles(t, h.state.Directory()) |
| + if err := h.runRoll(); !isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if !reflect.DeepEqual(before, snapshotFiles(t, h.state.Directory())) || len(h.f.calls) != 1 { |
| + t.Fatalf("calls %v", h.f.ops()) |
| + } |
| +} |
| + |
| +// Review Focus 3: a roll against a group another transaction has reshaped |
| +// (minimum N-1, a member parked) refuses shape before any write and |
| +// closes its own journal preflight-refused. |
| +func TestRollRefusesForeignTransactionShape(t *testing.T) { |
| + h := newHarness(t, 3) |
| + other := h.f.order[2] |
| + h.f.minimum, h.f.desired = 2, 2 |
| + h.f.states[other], h.f.tg[other] = "Standby", "unused" |
| + if err := h.runRoll(); refusalKey(err) != "shape" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if len(h.f.writes) != 0 || h.activeTx() != "" { |
| + t.Fatalf("writes %v active %q", h.f.writes, h.activeTx()) |
| + } |
| + done, ok := h.txJournal(h.onlyTx()).Last("done", nil) |
| + if !ok || done["outcome"] != "preflight-refused" { |
| + t.Fatalf("done %v", done) |
| + } |
| +} |
| + |
| +// test_return_waits_for_warming_targets. |
| +func TestRollReturnWaitsForWarmingTargets(t *testing.T) { |
| + for _, target := range []string{"initial", "draining", "unused"} { |
| + t.Run(target, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.after = func(name string) { |
| + if name == "exit" { |
| + h.f.tg[fakeIID] = target |
| + } |
| + } |
| + start := h.f.now |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.f.now.Sub(start) < h.f.targetWarmup || h.f.tg[fakeIID] != "healthy" || h.f.exits != 1 || blockedFlag(h) { |
| + t.Fatalf("took %v tg %s", h.f.now.Sub(start), h.f.tg[fakeIID]) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_warming_timeout_retains_record_then_resumes. |
| +func TestRollWarmingTimeoutRetainsRecordThenResumes(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.targetWarmup = 1000 * time.Second |
| + start := h.f.now |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if took := h.f.now.Sub(start); took < 900*time.Second || took >= 910*time.Second { |
| + t.Fatalf("took %v", took) |
| + } |
| + if !strings.Contains(h.out.String(), "ALERT") || blockedFlag(h) || h.f.minimum != 1 || |
| + h.f.permit(fakeIID)["state"] != "present" { |
| + t.Fatal("record not retained") |
| + } |
| + if _, ok := h.txJournal(h.activeTx()).Last("failed-probe", nil); ok { |
| + t.Fatal("failed probe") |
| + } |
| + if err := h.resume(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.activeTx() != "" || h.f.exits != 1 { |
| + t.Fatal("not finished") |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_rollback_after_failed_apply_readback. |
| +func TestRollRollbackAfterFailedApplyReadback(t *testing.T) { |
| + cases := []struct { |
| + installed string |
| + unchanged bool |
| + }{{newSHA, true}, {oldSHA, false}, {oldSHA, true}, {strings.Repeat("d", 64), false}} |
| + for _, c := range cases { |
| + t.Run(fmt.Sprintf("%s/%v", c.installed[:1], c.unchanged), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + original := copyArgs(h.f.edge(fakeIID)) |
| + h.f.after = func(name string) { |
| + if name == "apply" { |
| + h.f.boxes[fakeIID]["binary_sha256"] = c.installed |
| + if c.unchanged { |
| + h.f.boxes[fakeIID]["edge"] = copyArgs(original) |
| + } |
| + } |
| + } |
| + if err := h.runRoll(); refusalKey(err) == "" || isUncertain(err) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + h.f.after = nil |
| + calls := len(h.f.calls) |
| + writes := append([]string(nil), h.f.writes...) |
| + err := h.rollbackMember() |
| + if c.installed != oldSHA && c.installed != newSHA { |
| + if refusalKey(err) != "rollback_digest" || !reflect.DeepEqual(writes, h.f.writes) || |
| + h.f.states[fakeIID] != "Standby" { |
| + t.Fatalf("rollback = %v", err) |
| + } |
| + } else { |
| + if err != nil { |
| + t.Fatalf("rollback = %v\n%s", err, h.out.String()) |
| + } |
| + if h.f.boxes[fakeIID]["binary_sha256"] != oldSHA || h.f.states[fakeIID] != "InService" || h.activeTx() != "" { |
| + t.Fatal("not rolled back") |
| + } |
| + want := 0 |
| + if c.installed == newSHA { |
| + want = 1 |
| + } |
| + if countOf(h.f.writes, "rollback") != want || countOf(h.f.writes, "permit") != 1+want { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + } |
| + if c := h.f.calls[calls]; c.Op != "session" || c.Args["verb"] != "status" { |
| + t.Fatalf("first rollback call %v", c) |
| + } |
| + mustRetain(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// test_direct_return_classifies_pending_wait_before_refusal. |
| +func TestRollDirectReturnClassifiesPendingWait(t *testing.T) { |
| + for _, missing := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("missing=%v", missing), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.f.states[fakeIID] = "Pending:Wait" |
| + tx := h.activeTx() |
| + if !missing { |
| + h.appendRow(tx, "exit-intent", map[string]any{"process": "apply-process", "at_ms": ms(h.f.now)}) |
| + } |
| + if err := h.returning(); refusalKey(err) != "return_hook" { |
| + t.Fatalf("return = %v", err) |
| + } |
| + if _, ok := h.txJournal(tx).Last("return-hook", nil); !ok || !blockedFlag(h) || h.f.continues != 0 { |
| + t.Fatal("hook not recorded") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_automatic_rollback_resume_after_recording_decision. |
| +func TestRollAutomaticRollbackResumeAfterDecision(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.after = func(name string) { |
| + if name == "apply" { |
| + h.f.boxes[fakeIID]["binary_sha256"] = oldSHA |
| + } |
| + } |
| + if err := h.runRoll(); refusalKey(err) == "" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + h.afterEvent = func(kind string, _ Row) { |
| + if kind == "rollback-requested" { |
| + panic(fakeDeath{kind}) |
| + } |
| + } |
| + if !expectDeath(t, func() { h.rollbackMember() }) { |
| + t.Fatal("no death") |
| + } |
| + h.afterEvent = nil |
| + if err := h.resume(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if countOf(h.f.writes, "rollback") != 0 || h.f.boxes[fakeIID]["binary_sha256"] != oldSHA || h.activeTx() != "" { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_failed_apply_digest_readback_can_recover_to_new. |
| +func TestRollFailedApplyReadbackRecoversByRollback(t *testing.T) { |
| + h := newHarness(t, 2) |
| + failed := false |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if err == nil && op == "session" && args["verb"] == "status" && countOf(h.f.writes, "apply") > 0 && !failed { |
| + failed = true |
| + s := copyArgs(r.(map[string]any)) |
| + s["binary_sha256"] = strings.Repeat("d", 64) |
| + return s, nil |
| + } |
| + return r, err |
| + } |
| + if err := h.runRoll(); refusalKey(err) == "" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if err := h.rollbackMember(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if countOf(h.f.writes, "rollback") != 1 || h.f.boxes[fakeIID]["binary_sha256"] != oldSHA { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_hold_describe_blip_after_provider_return_is_resumable. |
| +func TestRollHoldDescribeBlipIsResumable(t *testing.T) { |
| + h := newHarness(t, 2) |
| + blip := true |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if blip && op == "group" && countOf(h.f.writes, "enter") == 2 { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + h.f.hook = true |
| + if err := h.runRoll(); refusalKey(err) == "" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + h.f.states[fakeIID], h.f.deadline = "InService", time.Time{} |
| + if err := h.resume(); !isUncertain(err) { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if _, ok := h.txJournal(h.activeTx()).Last("failed-probe", nil); ok { |
| + t.Fatal("failed probe") |
| + } |
| + blip = false |
| + if err := h.resume(); !isStop(err, "divergence-held") { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if h.f.continues != 0 || countOf(h.f.writes, "enter") != 2 { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_abandon_cli_after_interrupted_preflight (engine half): Ctrl-C in |
| +// preflight leaves the transaction open, and abandon closes it. |
| +func TestRollAbandonAfterInterruptedPreflight(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op != "caller" { |
| + return context.Canceled |
| + } |
| + return nil |
| + } |
| + if err := h.runRoll(); !errors.Is(err, context.Canceled) { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + tx := h.activeTx() |
| + if tx == "" { |
| + t.Fatal("interrupted preflight closed the transaction") |
| + } |
| + if err := h.locked(func(e *Engine) error { return e.Abandon(bg, tx) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + j := h.txJournal(tx) |
| + if done, _ := j.Last("done", nil); done["outcome"] != "abandoned" || h.activeTx() != "" { |
| + t.Fatalf("done %v", done) |
| + } |
| + if _, ok := j.Last("validated", nil); ok { |
| + t.Fatal("validated") |
| + } |
| + if a, _ := j.Last("abandoned", nil); a["attended_by"] != "test operator" { |
| + t.Fatalf("abandoned %v", a) |
| + } |
| +} |
| + |
| +// test_abandon_before_group_write_only. |
| +func TestRollAbandonBeforeGroupWriteOnly(t *testing.T) { |
| + for _, op := range []string{"", "minimum", "enter", "exit", "complete", "session:permit", "exit-intent"} { |
| + t.Run(op, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.prepareBad = true |
| + if err := h.runRoll(); refusalKey(err) != "prepare" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + tx := h.activeTx() |
| + switch { |
| + case op == "exit-intent": |
| + h.appendRow(tx, "exit-intent", map[string]any{}) |
| + case strings.HasPrefix(op, "session:"): |
| + h.appendRow(tx, "intent", map[string]any{"op": "session", "args": map[string]any{"verb": op[8:]}}) |
| + case op != "": |
| + h.appendRow(tx, "intent", map[string]any{"op": op, "args": map[string]any{}}) |
| + } |
| + calls := len(h.f.calls) |
| + err := h.locked(func(e *Engine) error { return e.Abandon(bg, tx) }) |
| + j := h.txJournal(tx) |
| + if op != "" { |
| + if refusalKey(err) != "abandon_refused" || h.activeTx() != tx { |
| + t.Fatalf("abandon = %v", err) |
| + } |
| + if _, ok := j.Last("done", nil); ok { |
| + t.Fatal("done") |
| + } |
| + } else { |
| + if err != nil || h.activeTx() != "" { |
| + t.Fatalf("abandon = %v", err) |
| + } |
| + if done, _ := j.Last("done", nil); done["outcome"] != "abandoned" { |
| + t.Fatalf("done %v", done) |
| + } |
| + } |
| + if len(h.f.calls) != calls { |
| + t.Fatalf("abandon called %v", h.f.ops()[calls:]) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_box_action_time_does_not_consume_readiness_wait. |
| +func TestRollBoxActionTimeDoesNotConsumeReadinessWait(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.after = func(name string) { |
| + if name == "apply" { |
| + h.f.sleep(901 * time.Second) |
| + } |
| + } |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.activeTx() != "" { |
| + t.Fatal("not finished") |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_rollback_waits_for_cut_apply_lock_before_inspecting_digest. |
| +func TestRollRollbackWaitsForStatus(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + h.f.boxes[fakeIID]["binary_sha256"] = oldSHA |
| + reads := 0 |
| + h.f.before = func(op string, args map[string]any) error { |
| + if op == "session" && args["verb"] == "status" { |
| + reads++ |
| + if reads < 3 { |
| + return Refusal{Key: "remote"} |
| + } |
| + if reads == 3 { |
| + h.f.boxes[fakeIID]["binary_sha256"] = newSHA |
| + } |
| + } |
| + if reads < 3 && (op != "session" || args["verb"] != "status") { |
| + t.Errorf("%s before a status read", op) |
| + } |
| + return nil |
| + } |
| + tx := h.activeTx() |
| + start := h.f.now |
| + if err := h.rollbackMember(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := h.txJournal(tx).Last("rollback-requested", nil); r["already_restored"] != false { |
| + t.Fatalf("decision %v", r) |
| + } |
| + if h.f.now.Sub(start) < 10*time.Second || countOf(h.f.writes, "rollback") != 1 { |
| + t.Fatalf("took %v writes %v", h.f.now.Sub(start), h.f.writes) |
| + } |
| + mustRetain(t, h) |
| +} |
| + |
| +// test_fsync_precedes_provider_write: every provider call after the begin |
| +// row follows a journal fsync (the intent's), and sessions are numbered |
| +// 1..n. The caller identity read precedes the journal, whose begin row |
| +// records it. |
| +func TestRollFsyncPrecedesProviderWrite(t *testing.T) { |
| + h := newHarness(t, 2) |
| + var trace []string |
| + h.state.fsync = func(*os.File) error { trace = append(trace, "sync"); return nil } |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op != "caller" && (len(trace) == 0 || trace[len(trace)-1] != "sync") { |
| + t.Errorf("%s without a preceding fsync", op) |
| + } |
| + trace = append(trace, "api") |
| + return nil |
| + } |
| + if err := h.runRoll(); err != nil { |
| + t.Fatal(err) |
| + } |
| + n := 0 |
| + for _, r := range h.txJournal(h.onlyTx()).Rows() { |
| + if r["kind"] == "intent" && r["op"] == "session" { |
| + n++ |
| + if !sameValue(r["session"], n) { |
| + t.Fatalf("session %v, want %d", r["session"], n) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// The fact builder always sets the two facts whose script default is |
| +// true: on a fresh roll journal both are false, a floor row checks the |
| +// floor, a hook row with the flag records the divergence, and a depart |
| +// journal never needs the roll's floor row. |
| +func TestDecisionFactsFreshJournal(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seed(true) |
| + facts := func() Facts { |
| + var f Facts |
| + must(t, h.locked(func(e *Engine) error { |
| + if err := e.load(tx); err != nil { |
| + return err |
| + } |
| + defer e.close() |
| + if err := e.restoreHeader(); err != nil { |
| + return err |
| + } |
| + var err error |
| + f, err = e.decisionFacts("resume", nil, false, observed{}) |
| + return err |
| + })) |
| + return f |
| + } |
| + if f := facts(); f.DivergenceRecorded || f.FloorChecked || f.ExitState != "none" || f.N != 2 { |
| + t.Fatalf("fresh: %+v", f) |
| + } |
| + h.appendRow(tx, "floor", map[string]any{"rule": "dr4"}) |
| + if f := facts(); !f.FloorChecked || f.DivergenceRecorded { |
| + t.Fatalf("floor: %+v", f) |
| + } |
| + h.appendRow(tx, "return-hook", map[string]any{}) |
| + if f := facts(); f.DivergenceRecorded || !f.Hook { |
| + t.Fatalf("hook without the flag: %+v", f) |
| + } |
| + h.withLock(func() { must(t, h.state.Write(h.state.DivergencePath(), map[string]any{"transaction": tx})) }) |
| + if f := facts(); !f.DivergenceRecorded { |
| + t.Fatalf("hook with the flag: %+v", f) |
| + } |
| + |
| + d := newHarness(t, 2) |
| + d.withLock(func() { |
| + j, err := d.state.Create(Header{Kind: "replace", Transaction: "t-replace", IID: fakeIID}) |
| + must(t, err) |
| + j.Close() |
| + }) |
| + must(t, d.locked(func(e *Engine) error { |
| + must(t, e.load("t-replace")) |
| + defer e.close() |
| + f, err := e.decisionFacts("return", nil, false, observed{}) |
| + if err == nil && !f.FloorChecked { |
| + t.Errorf("replace: FloorChecked false") |
| + } |
| + return err |
| + })) |
| +} |
| + |
| +// The divergence flag check fails closed: anything but "not there" is a |
| +// damaged record, for preflight and the fact builder alike. |
| +func TestBlockedFailsClosed(t *testing.T) { |
| + h := newHarness(t, 2) |
| + must(t, os.Chmod(h.state.Directory(), 0o000)) |
| + defer os.Chmod(h.state.Directory(), 0o700) |
| + if os.Geteuid() == 0 { |
| + t.Skip("root reads any directory") |
| + } |
| + if _, err := h.engine().blocked(); refusalKey(err) != "record" { |
| + t.Fatalf("blocked = %v", err) |
| + } |
| +} |
| + |
| +// test_return / test_rollback / test_resume (argv, engine half): on a |
| +// validated journal with nothing written, return needs an exit intent, |
| +// rollback needs the member held, and resume's first call is status. |
| +func TestRollVerbsOnFreshJournal(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seed(true) |
| + h.f.before = func(op string, args map[string]any) error { |
| + if op == "session" && args["verb"] == "prepare" { |
| + return Refusal{Key: "api"} |
| + } |
| + return nil |
| + } |
| + if err := h.locked(func(e *Engine) error { return e.Return(bg, tx) }); refusalKey(err) != "return_intent" { |
| + t.Fatalf("return = %v", err) |
| + } |
| + if h.f.calls[0].Op != "group" { |
| + t.Fatalf("return's first call %v", h.f.calls[0]) |
| + } |
| + h.f.calls = nil |
| + if err := h.locked(func(e *Engine) error { return e.Rollback(bg, fakeIID, tx) }); refusalKey(err) != "held" { |
| + t.Fatalf("rollback = %v", err) |
| + } |
| + if c := h.f.calls[0]; c.Op != "session" || c.Args["verb"] != "status" { |
| + t.Fatalf("rollback's first call %v", c) |
| + } |
| + h.f.calls = nil |
| + if err := h.locked(func(e *Engine) error { return e.Resume(bg, tx) }); refusalKey(err) != "api" { |
| + t.Fatalf("resume = %v", err) |
| + } |
| + if c := h.f.calls[0]; c.Op != "session" || c.Args["verb"] != "prepare" { |
| + t.Fatalf("resume's first call %v", c) |
| + } |
| +} |
| + |
| +// Every writing verb refuses another kind of journal (the probe's) with |
| +// journal_kind, before any call. |
| +func TestRollVerbsRefuseProbeJournal(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.withLock(func() { |
| + j, err := h.state.Create(Header{Kind: "probe", Transaction: "probe-t", IID: fakeIID}) |
| + must(t, err) |
| + j.Close() |
| + }) |
| + verbs := map[string]func(e *Engine) error{ |
| + "resume": func(e *Engine) error { return e.Resume(bg, "probe-t") }, |
| + "return": func(e *Engine) error { return e.Return(bg, "probe-t") }, |
| + "rollback": func(e *Engine) error { return e.Rollback(bg, fakeIID, "probe-t") }, |
| + "abandon": func(e *Engine) error { return e.Abandon(bg, "probe-t") }, |
| + "close-lost": func(e *Engine) error { return e.CloseLost(bg, "probe-t") }, |
| + } |
| + for name, fn := range verbs { |
| + if err := h.locked(fn); refusalKey(err) != "journal_kind" { |
| + t.Errorf("%s = %v", name, err) |
| + } |
| + } |
| + if len(h.f.calls) != 0 { |
| + t.Fatalf("calls %v", h.f.ops()) |
| + } |
| +} |
| + |
| +// CloseLostArgvChecks, at the engine. |
| + |
| +// seedLost is CloseLostArgvChecks.seed_lost: a validated roll whose member |
| +// is gone, with an exit intent. |
| +func (h *harness) seedLost() string { |
| + tx := h.seed(true) |
| + h.f.states[fakeIID], h.f.ec2State = "Terminated", "terminated" |
| + h.appendRow(tx, "intent", map[string]any{"op": "exit", "args": map[string]any{"iid": fakeIID}}) |
| + return tx |
| +} |
| + |
| +func (h *harness) closeLost(tx string) error { |
| + return h.locked(func(e *Engine) error { return e.CloseLost(bg, tx) }) |
| +} |
| + |
| +// stillActive is assert_still_active: open, no closure rows, reads only. |
| +func (h *harness) stillActive(t *testing.T, tx string) { |
| + t.Helper() |
| + if h.activeTx() != tx { |
| + t.Fatalf("active %q", h.activeTx()) |
| + } |
| + j := h.txJournal(tx) |
| + for _, k := range []string{"lost-member-closed", "done"} { |
| + if _, ok := j.Last(k, nil); ok { |
| + t.Fatalf("%s recorded", k) |
| + } |
| + } |
| + for _, op := range h.f.ops() { |
| + if op != "group" && op != "ec2_instance" { |
| + t.Fatalf("close-lost called %s", op) |
| + } |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes %v", h.f.writes) |
| + } |
| +} |
| + |
| +func (h *harness) checkClosed(t *testing.T, tx string) { |
| + t.Helper() |
| + if err := h.closeLost(tx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.activeTx() != "" || !reflect.DeepEqual(h.f.ops(), []string{"group", "ec2_instance"}) { |
| + t.Fatalf("calls %v", h.f.ops()) |
| + } |
| + j := h.txJournal(tx) |
| + rows := j.Rows() |
| + var kinds []string |
| + for _, r := range rows[len(rows)-6:] { |
| + kinds = append(kinds, r["kind"].(string)) |
| + } |
| + if !reflect.DeepEqual(kinds, []string{"intent", "response", "intent", "response", "lost-member-closed", "done"}) { |
| + t.Fatalf("rows %v", kinds) |
| + } |
| + closed, _ := j.Last("lost-member-closed", nil) |
| + group := closed["group"].(map[string]any) |
| + if closed["iid"] != fakeIID || group["arn"] != h.c.GroupARN || group["members"].(map[string]any)[fakeIID] != nil { |
| + t.Fatalf("closed %v", closed) |
| + } |
| + want := h.f.ec2State |
| + if want == "" { |
| + want = "not-found" |
| + } |
| + resp, _ := j.Last("response", map[string]any{"op": "ec2_instance"}) |
| + if closed["describe"].(map[string]any)["state"] != want || !sameValue(closed["describe"], resp["result"]) { |
| + t.Fatalf("describe %v", closed["describe"]) |
| + } |
| + if done, _ := j.Last("done", nil); done["outcome"] != "failed-member-lost" { |
| + t.Fatalf("done %v", done) |
| + } |
| + if !strings.Contains(h.out.String(), Text("lost_closed")) { |
| + t.Fatal("not said") |
| + } |
| +} |
| + |
| +// test_close_lost_terminated_preserves_flags_and_status. |
| +func TestCloseLostTerminatedPreservesFlagsAndStatus(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.withLock(func() { |
| + must(t, h.state.Write(h.state.DivergencePath(), map[string]any{"transaction": tx, "phase": "Pending:Wait"})) |
| + must(t, h.state.Write(h.state.ObservationPath(), map[string]any{"evidence": "preserve exactly"})) |
| + }) |
| + read := func() [2]string { |
| + a, _ := os.ReadFile(h.state.DivergencePath()) |
| + b, _ := os.ReadFile(h.state.ObservationPath()) |
| + return [2]string{string(a), string(b)} |
| + } |
| + before := read() |
| + h.checkClosed(t, tx) |
| + if read() != before { |
| + t.Fatal("flags changed") |
| + } |
| + if !strings.Contains(h.out.String(), h.state.DivergencePath()) { |
| + t.Fatal("retained flag not named") |
| + } |
| + var status strings.Builder |
| + must(t, Status(h.root, h.c, tx, &status)) |
| + if !strings.Contains(status.String(), `"outcome": "failed-member-lost"`) { |
| + t.Fatalf("status %s", status.String()) |
| + } |
| + saved, _ := os.ReadFile(h.state.journalPath(tx)) |
| + h.f.calls = nil |
| + if err := h.closeLost(tx); err == nil || len(h.f.calls) != 0 { |
| + t.Fatalf("second close-lost = %v, calls %v", err, h.f.ops()) |
| + } |
| + if again, _ := os.ReadFile(h.state.journalPath(tx)); string(again) != string(saved) { |
| + t.Fatal("journal changed") |
| + } |
| +} |
| + |
| +// test_close_lost_not_found. |
| +func TestCloseLostNotFound(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.f.ec2State = "" |
| + h.checkClosed(t, tx) |
| +} |
| + |
| +// test_close_lost_refuses_present_group_states. |
| +func TestCloseLostRefusesPresentGroupStates(t *testing.T) { |
| + for _, state := range []string{"Standby", "InService", "Pending", "Pending:Wait", "Terminating", "Terminated"} { |
| + t.Run(state, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + // The group still lists the member, in any state. |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if op == "group" && err == nil { |
| + g := r.(GroupView) |
| + g.Members[fakeIID] = Member{Phase: fakePhase(state), Raw: state} |
| + return g, nil |
| + } |
| + return r, err |
| + } |
| + if err := h.closeLost(tx); refusalKey(err) != "close_lost_refused" { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + h.stillActive(t, tx) |
| + }) |
| + } |
| +} |
| + |
| +// test_close_lost_refuses_nonterminal_ec2_states. |
| +func TestCloseLostRefusesNonterminalEC2States(t *testing.T) { |
| + for _, state := range []string{"pending", "running", "shutting-down", "stopping", "stopped", "unknown"} { |
| + t.Run(state, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.f.ec2State = state |
| + if err := h.closeLost(tx); refusalKey(err) != "close_lost_refused" { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + h.stillActive(t, tx) |
| + }) |
| + } |
| +} |
| + |
| +// test_close_lost_refuses_read_errors and _invalid_ec2_evidence (the |
| +// adapter refuses malformed EC2 answers as api: TestInstance in |
| +// grouprollaws). |
| +func TestCloseLostRefusesReadErrors(t *testing.T) { |
| + for _, op := range []string{"group", "ec2_instance"} { |
| + t.Run(op, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.f.before = func(called string, _ map[string]any) error { |
| + if called == op { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + if err := h.closeLost(tx); !isUncertain(err) { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + h.stillActive(t, tx) |
| + }) |
| + } |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if op == "ec2_instance" && err == nil { |
| + s := r.(InstanceState) |
| + s.IID = fakePeer |
| + return s, nil |
| + } |
| + return r, err |
| + } |
| + if err := h.closeLost(tx); refusalKey(err) != "close_lost_refused" { |
| + t.Fatalf("other instance's evidence: %v", err) |
| + } |
| + h.stillActive(t, tx) |
| +} |
| + |
| +// test_close_lost_refuses_wrong_group_identity. |
| +func TestCloseLostRefusesWrongGroupIdentity(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if op == "group" && err == nil { |
| + g := r.(GroupView) |
| + g.ARN += "-recreated" |
| + return g, nil |
| + } |
| + return r, err |
| + } |
| + if err := h.closeLost(tx); refusalKey(err) != "scope" { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + h.stillActive(t, tx) |
| +} |
| + |
| +// test_close_lost_refuses_no_journal, _finished_journal_even_with_active_pointer, |
| +// _wrong_kind, _without_active_pointer and _obeys_group_lock. |
| +func TestCloseLostRefusals(t *testing.T) { |
| + t.Run("no journal", func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if err := h.closeLost("missing"); refusalKey(err) != "record" || len(h.f.calls) != 0 { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + }) |
| + t.Run("finished", func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.appendRow(tx, "done", map[string]any{"outcome": "failed-member-lost"}) |
| + if err := h.closeLost(tx); refusalKey(err) != "record" || len(h.f.calls) != 0 { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + }) |
| + t.Run("wrong kind", func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.withLock(func() { |
| + j, err := h.state.Create(Header{Kind: "probe", Transaction: "probe-argv-test", IID: fakeIID}) |
| + must(t, err) |
| + j.Close() |
| + }) |
| + if err := h.closeLost("probe-argv-test"); refusalKey(err) != "journal_kind" || len(h.f.calls) != 0 { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + h.stillActive(t, "probe-argv-test") |
| + }) |
| + t.Run("no active pointer", func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + must(t, os.Remove(filepath.Join(h.state.Directory(), activeFile))) |
| + if err := h.closeLost(tx); refusalKey(err) != "record" || len(h.f.calls) != 0 { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + }) |
| + t.Run("lock", func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + other, err := OpenState(h.root, h.c, false) |
| + must(t, err) |
| + unlock, err := other.Lock() |
| + must(t, err) |
| + defer unlock() |
| + if err := h.closeLost(tx); refusalKey(err) != "busy" || len(h.f.calls) != 0 { |
| + t.Fatalf("close-lost = %v", err) |
| + } |
| + }) |
| +} |
| + |
| +// test_later_roll_can_start: after close-lost, a new roll opens and gets |
| +// past preflight. |
| +func TestCloseLostLaterRollCanStart(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seedLost() |
| + h.checkClosed(t, tx) |
| + h.f.states[fakeIID] = "InService" |
| + h.f.prepareBad = true |
| + if err := h.runRollTx("after-loss"); refusalKey(err) != "prepare" { |
| + t.Fatalf("roll = %v", err) |
| + } |
| + if h.activeTx() != "after-loss" { |
| + t.Fatal("new roll not active") |
| + } |
| + if _, ok := h.txJournal("after-loss").Last("validated", nil); !ok { |
| + t.Fatal("not validated") |
| + } |
| + for _, w := range h.f.writes { |
| + if w != "prepare" { |
| + t.Fatalf("group write %s", w) |
| + } |
| + } |
| +} |
| + |
| +// The exit state classify reads: the latest exit intent with its own |
| +// response is acknowledged; with an error row it is ambiguous when the |
| +// request was dispatched and unsent when it was not; alone it is |
| +// dispatched (a death between intent and response, Review Focus 2). |
| +func TestDecisionFactsExitState(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + rows []map[string]any |
| + want string |
| + }{ |
| + {"none", nil, "none"}, |
| + {"dispatched", []map[string]any{{"kind": "intent", "op": "exit"}}, "dispatched"}, |
| + {"acknowledged", []map[string]any{{"kind": "intent", "op": "exit"}, {"kind": "response", "op": "exit", "intent": "$"}}, "acknowledged"}, |
| + {"ambiguous", []map[string]any{{"kind": "intent", "op": "exit"}, {"kind": "error", "op": "exit", "intent": "$", "dispatched": true}}, "ambiguous"}, |
| + {"unsent", []map[string]any{{"kind": "intent", "op": "exit"}, {"kind": "error", "op": "exit", "intent": "$", "dispatched": false}}, "none"}, |
| + {"older answer", []map[string]any{{"kind": "intent", "op": "exit"}, {"kind": "response", "op": "exit", "intent": "$"}, |
| + {"kind": "intent", "op": "exit"}}, "dispatched"}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seed(true) |
| + var seq int64 |
| + for _, r := range c.rows { |
| + fields := map[string]any{} |
| + for k, v := range r { |
| + if k != "kind" { |
| + fields[k] = v |
| + } |
| + } |
| + if fields["intent"] == "$" { |
| + fields["intent"] = seq |
| + } |
| + h.withLock(func() { |
| + j, err := h.state.Load(tx, false) |
| + must(t, err) |
| + row, err := j.Add(r["kind"].(string), fields) |
| + must(t, err) |
| + if r["kind"] == "intent" { |
| + seq = rowSeq(row) |
| + } |
| + j.Close() |
| + }) |
| + } |
| + must(t, h.locked(func(e *Engine) error { |
| + must(t, e.load(tx)) |
| + defer e.close() |
| + must(t, e.restoreHeader()) |
| + f, err := e.decisionFacts("return", nil, false, observed{}) |
| + if err == nil && f.ExitState != c.want { |
| + t.Errorf("exit state %q, want %q", f.ExitState, c.want) |
| + } |
| + return err |
| + })) |
| + }) |
| + } |
| +} |
| + |
| +// mutation never replays a consumed action: a status showing this |
| +// transaction's action consumed is verified, not permitted again. |
| +func TestRollMutationVerifiesConsumedAction(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.pauseAfterApply() |
| + tx := h.activeTx() |
| + writes := append([]string(nil), h.f.writes...) |
| + must(t, h.locked(func(e *Engine) error { |
| + must(t, e.load(tx)) |
| + defer e.close() |
| + must(t, e.restoreHeader()) |
| + return e.mutation(bg) |
| + })) |
| + if !reflect.DeepEqual(writes, h.f.writes) { |
| + t.Fatalf("wrote %v", h.f.writes[len(writes):]) |
| + } |
| + if _, ok := h.txJournal(tx).Last("box-action-verified", map[string]any{"action": "apply"}); !ok { |
| + t.Fatal("consumed action not verified") |
| + } |
| +} |