carlos / platform Public

grouproll: replace, remove and cancel-drain

Ports the held-floor branch's planned handovers: Depart (start_depart,
check_remove, depart), the drain with three sessions that rejoin the
move, the H5 pre-action check, the lock sweep over the configured data
bucket (absence only from a listing), the proven edge stop, terminate
and its recovery through TerminateDecision on every pass, the watch,
the drain summary and CancelDrain. The roll's drain path is no longer
stubbed. Every depart, drain and cancel test of region_group_held_test.py
is ported against the held fake, plus Go-only tests for the stop proof,
foreign fences and report checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7c3b6d1dd90ee61965ae5da9c053759762f3a90d parent 1a24644
4 files changed, +3,181 −20
  • internal/grouproll/depart.go +1,217 −15
  • internal/grouproll/depart_test.go +1,470 −0
  • internal/grouproll/fake_test.go +485 −3
  • internal/grouproll/roll.go +9 −2

Intent

Human

<task-notification> <task-id>ac6a6f8205cd69548</task-id> <tool-use-id>toolu_01FcG3yxYqVwTTHtjWgecVjv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/ac6a6f8205cd69548.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7: roll engine + sim" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Task 7 is done and everything passes, with four concerns (below). Four commits on `group-roll-verb`, not pushed: **Commits:** - `4e2abb69` the roll engine (roll, resume, rollback, return, abandon, close-lost) and the three Task 5 carry-ins - `d1b43794` the ten required mutations - `66290821` the six CLI leaves, parity rows, census re-proposal - `1a246449` the seeded simulation The brief asked for six commits. The engine is one file, so its four logical steps landed together in the first commit. **Tests:** `go test ./internal/grouproll/... ./internal/grouprollaws/...` passes, as do the CLI, parity, docsite, release and census tests, vet, gofmt and the darwin and windows cross-builds. - The 3000-seed run passed in 10 min 54 s. Coverage counts are in the commit body, including deaths between an intent and its provider call (1276) and between the call and its response row (1300). - The five classifier mutants and the ten required mutations each fail their named scenario. - I wrote `roll.go` before its tests, so this was not strict TDD. Instead I ran hand mutants against `roll.go`; three survived at first, and I added tests that now catch them. **Concerns:** 1. Drain is stubbed until Task 9: a roll whose floor holds stops "unsupported" with the member parked and no drain sent. 2. The 200-seed CI run takes about 44 s. Most of that is the state re-reading every journal on each resume, which the script also does. 3. `runSeed` takes a `*testing.T` and a base directory, unlike the brief's signature. The census proposal now has 22 units awaiting the reviewer at Task 14. I also inventoried Task 8's two refusing `Put` methods, whose omission was failing the record-write census before this task. 4. Go commands ran outside the sandbox because its build cache is read-only there; `GOCACHE` stayed at its default. The full report, including the Python-to-Go test map and the six held-test drain cases deferred to Task 9, is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-group-roll-verb/.superpowers/sdd/2026-11-09-group-roll-verb/task-7-report.md`.</result> <usage><subagent_tokens>478968</subagent_tokens><tool_uses>121</tool_uses><duration_ms>3076113</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bc037xm37</task-id> <tool-use-id>toolu_019k47uUbMi74R4RexfdUrVS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/bc037xm37.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra Task 7 review" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/grouproll/depart.go b/internal/grouproll/depart.go
index 17313a9c5..93a9e1884 100644
--- a/internal/grouproll/depart.go
+++ b/internal/grouproll/depart.go
@@ -1,30 +1,1232 @@
package grouproll
-import "context"
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
-// The planned handovers (replace, remove) and the drain a roll runs when
-// the floor holds (region HA spec §25; script :1923-2338) are Task 9's.
-// Until then each step refuses "unsupported", which stops a transaction
-// resumable before any drain or terminate, and nothing writes the
-// "drained" row the fence and summary steps act on.
+// The planned handovers (region HA spec §25.4-§25.6 and the binding
+// rulings of §25.15; script :2271-2681 on held-floor-sha-map): replace
+// and remove, the drain a roll runs when the floor holds, the H5 check
+// immediately before the action, the edge stop, the terminate and its
+// recovery, the watch, and cancel-drain. Every post-intent terminate pass
+// is TerminateDecision's; the return after a failed drain is the roll's
+// return executor (Classify), the only caller of ExitStandby.
-// depart is the script's Operator.depart (replace and remove).
-func (e *Engine) depart(ctx context.Context) error { return refuse("unsupported") }
+// DrainTries is the script's DRAIN_TRIES: drain sessions per transaction.
+// A rerun joins the move step the agent reports for the transaction.
+const DrainTries = 3
-// drain is the script's Operator.drain.
-func (e *Engine) drain(ctx context.Context) error { return refuse("unsupported") }
+// summaryWait is the watch's and the depart loop's poll bound (the
+// script's min(5, end - now)).
+const summaryWait = 5 * time.Second
-// preAction is the script's Operator.pre_action (H5).
-func (e *Engine) preAction(ctx context.Context) error { return refuse("unsupported") }
+var incarnationPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
+
+// Depart is the script's start_depart: open a replace or remove
+// transaction for member iid (tx, when not empty, is the operator's chosen
+// id), run preflight (and, for remove, check_remove), record the validated
+// member, and run the departure. The caller holds the group lock. A
+// preflight refusal closes the transaction preflight-refused; an interrupt
+// leaves it open for abandon, as Roll does.
+func (e *Engine) Depart(ctx context.Context, iid, kind, tx string) error {
+ if !departKinds[kind] {
+ return refuse("unsupported")
+ }
+ if tx != "" && (!TX.MatchString(tx) || strings.HasPrefix(tx, "probe-") || strings.HasPrefix(tx, "-")) {
+ return refuse("record")
+ }
+ if !e.s.Held() {
+ return refuse("active")
+ }
+ if active, err := e.s.ActiveID(); err != nil {
+ return err
+ } else if active != "" {
+ return refuse("active")
+ }
+ if tx != "" {
+ // A finished transaction's id is taken: refused before any call.
+ if _, err := os.Lstat(e.s.journalPath(tx)); !errors.Is(err, os.ErrNotExist) {
+ return refuse("record")
+ }
+ } else {
+ tx = randomHex()
+ }
+ if e.Caller == nil {
+ return refuse("unsupported")
+ }
+ user, _, err := e.Caller.CallerIdentity(ctx)
+ if err != nil {
+ return err
+ }
+ j, err := e.s.Create(Header{Kind: kind, Transaction: tx, IID: iid, AttendedBy: e.attended, CallerUserID: user})
+ if err != nil {
+ return err
+ }
+ e.open(j)
+ defer e.close()
+ e.say("journal", j.Path())
+ snap, s, err := e.preflight(ctx, iid, "")
+ if err == nil && kind == "remove" {
+ err = e.checkRemove(snap.View, iid)
+ }
+ if err != nil {
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return err
+ }
+ if _, jerr := e.event("done", map[string]any{"outcome": "preflight-refused"}); jerr != nil {
+ return jerr
+ }
+ if ferr := e.s.Finish(); ferr != nil {
+ return ferr
+ }
+ return err
+ }
+ identity := map[string]any{}
+ for _, k := range []string{"iid", "boot_id", "account", "region", "group", "config_digest", "box_ref"} {
+ v, ok := s[k]
+ if !ok {
+ return refuse("record")
+ }
+ identity[k] = v
+ }
+ edge, _ := s["edge"].(map[string]any)
+ process, ok := edge["identity"]
+ if !ok {
+ return refuse("record")
+ }
+ members := []any{}
+ for _, m := range sortedMembers(snap.View) {
+ members = append(members, m)
+ }
+ if _, err := e.event("validated", map[string]any{"old": s["binary_sha256"], "new": s["binary_sha256"],
+ "n": snap.View.Desired, "members": members, "identity": identity, "original_process": process,
+ "template": snap.View.Template}); err != nil {
+ return err
+ }
+ return e.depart(ctx)
+}
+
+// checkRemove is the script's check_remove: at least two members remain,
+// the member's served pools are known, and every one of them is served by
+// a survivor whose own served pools are known.
+func (e *Engine) checkRemove(g GroupView, iid string) error {
+ if g.Desired-1 < 2 {
+ return refuse("remove_minimum")
+ }
+ pools, ok := stringList(e.memberEdges[iid]["served_pools"])
+ if !ok {
+ return refuse("remove_pools_unknown")
+ }
+ served := map[string]bool{}
+ for member, edges := range e.memberEdges {
+ // Unknown served_pools prove nothing, so they serve nothing here.
+ if theirs, ok := stringList(edges["served_pools"]); member != iid && ok {
+ for _, p := range theirs {
+ served[p] = true
+ }
+ }
+ }
+ for _, p := range pools {
+ if !served[p] {
+ return refuse("remove_pools", "pool", p)
+ }
+ }
+ return nil
+}
+
+// stringList is v as a list of strings, when it is one.
+func stringList(v any) ([]string, bool) {
+ raw, ok := v.([]any)
+ if !ok {
+ return nil, false
+ }
+ out := make([]string, len(raw))
+ for i, x := range raw {
+ s, ok := x.(string)
+ if !ok {
+ return nil, false
+ }
+ out[i] = s
+ }
+ return out, true
+}
+
+// depart is the script's Operator.depart: the shared shape (lower
+// minimum, park, verify Standby), then the drain and the H5 check, the
+// stop and the terminate, then the watch. Each step is decided from the
+// journal and a fresh group read, so resume continues where a cut left
+// off.
+func (e *Engine) depart(ctx context.Context) error {
+ if err := e.restoreHeader(); err != nil {
+ return err
+ }
+ iid, kind, n := e.hStr("iid"), e.kind(), e.hInt("n")
+ if e.has("done", nil) {
+ return e.s.Finish()
+ }
+ if e.unchanged() {
+ return e.returnMember(ctx)
+ }
+ if !e.has("floor", nil) {
+ rule, err := e.Floor(ctx, kind, "")
+ if err != nil {
+ return err
+ }
+ if rule != "drain" {
+ if _, err := e.event("done", map[string]any{"outcome": "floor-refused"}); err != nil {
+ return err
+ }
+ if err := e.s.Finish(); err != nil {
+ return err
+ }
+ return refuse("floor_refused")
+ }
+ }
+ if e.rule() != "drain" {
+ return refuse("record")
+ }
+ // The H5 check passed before the first edge-stop was sent. A stopped
+ // agent cannot answer it again, so after a cut re-prove the stop and
+ // read the locks again instead (stopAndTerminate).
+ end := e.clock().Add(standbyWait)
+ peersChecked := false
+ for !e.has("intent", map[string]any{"op": "terminate"}) {
+ if !e.clock().Before(end) {
+ return e.alert("timeout", false)
+ }
+ g, err := e.snapshot(ctx)
+ if err != nil {
+ return err
+ }
+ if err := e.invariant(g); err != nil {
+ return err
+ }
+ m, listed := g.View.Members[iid]
+ if listed && m.Phase == Serving {
+ if e.has("drained", nil) {
+ return refuse("held")
+ }
+ if !peersChecked {
+ for _, member := range e.hMembers() {
+ on, err := e.online(ctx, member)
+ if err != nil {
+ return err
+ }
+ if !on {
+ return refuse("offline")
+ }
+ if !peerOK(g, member) {
+ return refuse("peer")
+ }
+ if _, err := e.readiness(ctx, member); err != nil {
+ return err
+ }
+ }
+ peersChecked = true
+ }
+ switch {
+ case g.View.Minimum == n && g.View.Desired == n:
+ if _, err := e.event("phase", map[string]any{"phase": "lower-minimum"}); err != nil {
+ return err
+ }
+ if err := e.setMinimum(ctx, n-1); err != nil {
+ return err
+ }
+ case g.View.Minimum == n-1 && g.View.Desired == n:
+ if _, err := e.event("phase", map[string]any{"phase": "enter-standby"}); err != nil {
+ return err
+ }
+ if !e.has("enter-activity-baseline", nil) {
+ as, err := e.activities(ctx, iid)
+ if err != nil {
+ return err
+ }
+ if _, err := e.event("enter-activity-baseline", map[string]any{"activities": activityRows(iid, as)}); err != nil {
+ return err
+ }
+ }
+ w, err := e.parkMember(ctx, iid)
+ if err != nil {
+ return err
+ }
+ if w.Activity != "" {
+ if _, err := e.event("enter-activity", map[string]any{"activity": w.Activity}); err != nil {
+ return err
+ }
+ }
+ end = e.clock().Add(standbyWait)
+ default:
+ return e.alert("members", false)
+ }
+ continue
+ }
+ if !listed || (m.Phase != Parked && m.Phase != Parking) {
+ return e.alert("members", false)
+ }
+ // EnterStandby is asynchronous: while entry is pending check the
+ // capacity only, then wait for the settled Standby state.
+ if g.View.Minimum != n-1 || g.View.Desired != n-1 {
+ return refuse("held")
+ }
+ if m.Phase != Parked || !deregisteredFrom(g, iid) {
+ e.sleepFor(summaryWait, end)
+ continue
+ }
+ if err := e.standby(g, true); err != nil {
+ return err
+ }
+ for _, member := range e.hMembers() {
+ if member != iid && !peerOK(g, member) {
+ return refuse("peer")
+ }
+ }
+ if !e.stopSent() {
+ err := func() error {
+ if !e.has("drained", nil) {
+ if err := e.drain(ctx); err != nil {
+ return err
+ }
+ }
+ return e.preAction(ctx)
+ }()
+ if isStop(err, "drain-failed") {
+ return e.returnMember(ctx)
+ }
+ if err != nil {
+ return err
+ }
+ }
+ if err := e.stopAndTerminate(ctx); err != nil {
+ return err
+ }
+ }
+ return e.departWatch(ctx)
+}
+
+// sleepFor sleeps d, never past end.
+func (e *Engine) sleepFor(d time.Duration, end time.Time) {
+ e.sleepWithin(Decision{Action: "wait", Delay: d}, end)
+}
+
+// drainFailed is the script's drain_failed: journal the failure, say each
+// reason, and stop drain-failed (the return follows).
+func (e *Engine) drainFailed(reasons []string, report any) error {
+ rs := make([]any, len(reasons))
+ for i, r := range reasons {
+ rs[i] = r
+ }
+ if _, err := e.event("drain-failed", map[string]any{"reasons": rs, "report": report}); err != nil {
+ return err
+ }
+ for _, r := range reasons {
+ e.say("ALERT", Text("drain_reason", "reason", r))
+ }
+ return stopped("drain-failed", "drain_failed")
+}
+
+// drain is the script's Operator.drain: up to DrainTries drain sessions
+// (an uncertain one is run again and joins the move), then the report
+// must be this transaction's finished move, fenced, from a known agent
+// incarnation. Anything else is a failed drain.
+func (e *Engine) drain(ctx context.Context) error {
+ iid, tx := e.hStr("iid"), e.hStr("transaction")
+ if _, err := e.event("phase", map[string]any{"phase": "drain"}); err != nil {
+ return err
+ }
+ var r BoxResult
+ for attempt := 1; ; attempt++ {
+ var err error
+ r, err = e.box(ctx, iid, "drain", BoxArgs{Transaction: tx})
+ if err == nil {
+ break
+ }
+ var u Uncertain
+ switch {
+ case errors.As(err, &u):
+ if _, jerr := e.event("drain-uncertain", map[string]any{"attempt": attempt, "reason": u.Error()}); jerr != nil {
+ return jerr
+ }
+ if attempt == DrainTries {
+ return e.drainFailed([]string{u.Error()}, nil)
+ }
+ case isRefusal(err):
+ return e.drainFailed([]string{reasonOf(err)}, nil)
+ default:
+ return err
+ }
+ }
+ value, _ := r.Value.(map[string]any)
+ report, ok := value["report"].(map[string]any)
+ if !ok {
+ return e.drainFailed([]string{Text("drain_report")}, nil)
+ }
+ exit := pyNumber(value["exit"])
+ incarnation, _ := report["incarnation"].(string)
+ if exit == nil || *exit != 0 || report["transaction"] != tx || report["step"] != "move" ||
+ report["result"] != "ok" || report["fence"] != tx || !incarnationPattern.MatchString(incarnation) {
+ reasons, ok := stringList(report["reasons"])
+ if report["transaction"] != tx || !ok || len(reasons) == 0 {
+ reasons = []string{Text("drain_report")}
+ }
+ if len(reasons) > 32 {
+ reasons = reasons[:32]
+ }
+ return e.drainFailed(reasons, report)
+ }
+ _, err := e.event("drained", map[string]any{"incarnation": incarnation, "report": report})
+ return err
+}
+
+// dataKeyPrefix is the script's AWS.data_prefix: the configured data bucket
+// and the prefix its host directories sit under ("" or "<prefix>/").
+func dataKeyPrefix(bucket, prefix string) (string, error) {
+ if !Bucket.MatchString(bucket) {
+ return "", refuse("data_bucket")
+ }
+ if prefix == "" {
+ return "", nil
+ }
+ return prefix + "/", nil
+}
+
+// objectError is a store listing's failure as the script's invoke raised
+// it: an interrupt stays one, an Uncertain stays itself, anything else is
+// Uncertain(api). A failed read is never absence.
+func objectError(ctx context.Context, err error) error {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ var u Uncertain
+ if errors.As(err, &u) {
+ return u
+ }
+ return Uncertain{Key: "api"}
+}
+
+// lockHosts is the script's call("lock_hosts"): the host directories
+// under the data prefix, from a delimiter listing of the data bucket.
+func (e *Engine) lockHosts(ctx context.Context, bucket, prefix string) ([]string, error) {
+ var hosts []string
+ _, err := e.call(ctx, "lock_hosts", map[string]any{"bucket": bucket, "prefix": prefix}, time.Time{},
+ func(ctx context.Context, _ func(string)) (any, error) {
+ p, err := dataKeyPrefix(bucket, prefix)
+ if err != nil {
+ return nil, err
+ }
+ if e.Objects == nil {
+ return nil, refuse("unsupported")
+ }
+ dirs, err := e.Objects.Bucket(bucket).ListDirs(ctx, p)
+ if err != nil {
+ return nil, objectError(ctx, err)
+ }
+ out := []any{}
+ for _, d := range dirs {
+ if !strings.HasPrefix(d, p) || !strings.HasSuffix(d, "/") || len(d) < len(p)+1 {
+ return nil, refuse("api")
+ }
+ hosts = append(hosts, d[len(p):len(d)-1])
+ }
+ sort.Strings(hosts)
+ for _, h := range hosts {
+ out = append(out, h)
+ }
+ return out, nil
+ })
+ return hosts, err
+}
+
+// lockRead is the script's call("lock"): one host's lock.json. Absence is
+// only ever the listing's answer for the exact key, never a failed GET.
+func (e *Engine) lockRead(ctx context.Context, bucket, prefix, host string) (map[string]any, error) {
+ var out map[string]any
+ _, err := e.call(ctx, "lock", map[string]any{"bucket": bucket, "prefix": prefix, "host": host}, time.Time{},
+ func(ctx context.Context, _ func(string)) (any, error) {
+ p, err := dataKeyPrefix(bucket, prefix)
+ if err != nil {
+ return nil, err
+ }
+ if !HostName.MatchString(host) {
+ return nil, refuse("api")
+ }
+ if e.Objects == nil {
+ return nil, refuse("unsupported")
+ }
+ store := e.Objects.Bucket(bucket)
+ key := p + host + "/lock.json"
+ keys, err := store.List(ctx, key)
+ if err != nil {
+ return nil, objectError(ctx, err)
+ }
+ found := false
+ for _, k := range keys {
+ found = found || k == key
+ }
+ if !found {
+ out = map[string]any{"absent": true}
+ return out, nil
+ }
+ body, err := readObject(ctx, store, key)
+ if err != nil {
+ return nil, err
+ }
+ v, err := decodeObject(body)
+ if err != nil {
+ return nil, err
+ }
+ out = map[string]any{"absent": false, "lock": v}
+ return out, nil
+ })
+ return out, err
+}
+
+// pyStrOf is Python's str() of a decoded JSON value, for the messages
+// that format one (None, True, numbers and strings as Python prints them;
+// a list or object as JSON).
+func pyStrOf(v any) string {
+ switch x := v.(type) {
+ case nil:
+ return "None"
+ case bool:
+ if x {
+ return "True"
+ }
+ return "False"
+ case string:
+ return x
+ case int64:
+ return strconv.FormatInt(x, 10)
+ case json.Number:
+ return string(x)
+ }
+ s, err := pythonDumps(v)
+ if err != nil {
+ return "?"
+ }
+ return s
+}
+
+// locksNamingMember is the script's locks_naming_member (§25.6 step 4):
+// every lock in the region's data bucket that names the member and is
+// neither a release marker nor another box's. The bucket and prefix are
+// the tool's own config, never the member's word. Each host the drain
+// moved must be found with a lock, or the sweep looked in the wrong place.
+func (e *Engine) locksNamingMember(ctx context.Context) ([]string, error) {
+ ref, _ := e.hIdentity()["box_ref"].(string)
+ iid := e.hStr("iid")
+ if e.c.DataBucket == nil || e.c.DataPrefix == nil {
+ return nil, refuse("record")
+ }
+ bucket, prefix := *e.c.DataBucket, *e.c.DataPrefix
+ // A cross-check only: a member naming another bucket is misconfigured.
+ edges, err := e.edges(ctx, ref)
+ if err != nil {
+ return nil, err
+ }
+ if named, ok := edges["data_bucket"].(string); !ok || named != bucket {
+ return nil, refuse("data_bucket_mismatch", "bucket", pyStrOf(edges["data_bucket"]))
+ }
+ drained, _ := e.last("drained", nil)
+ report, _ := drained["report"].(map[string]any)
+ moved := map[string]bool{}
+ if list, ok := report["moved"].([]any); ok {
+ for _, m := range list {
+ if mm, ok := m.(map[string]any); ok {
+ moved[pyStrOf(mm["host"])] = true
+ }
+ }
+ }
+ hosts, err := e.lockHosts(ctx, bucket, prefix)
+ if err != nil {
+ return nil, err
+ }
+ held, seen := []string{}, map[string]bool{}
+ for _, host := range hosts {
+ if !HostName.MatchString(host) {
+ continue
+ }
+ v, err := e.lockRead(ctx, bucket, prefix, host)
+ if err != nil {
+ return nil, err
+ }
+ if v["absent"] == true {
+ continue
+ }
+ seen[host] = true
+ lock, isMap := v["lock"].(map[string]any)
+ owner, isStr := lock["owner"].(string)
+ if isMap && (lock["carlos_release"] != nil || (isStr && strings.HasPrefix(owner, "released/v1;"))) {
+ continue
+ }
+ switch {
+ case !isStr:
+ held = append(held, host)
+ case strings.HasPrefix(owner, "box/v1;"):
+ for _, field := range strings.Split(owner[len("box/v1;"):], ";") {
+ if field == "ref="+ref || field == "iid="+iid {
+ held = append(held, host)
+ break
+ }
+ }
+ case strings.Contains(owner, ref) || strings.Contains(owner, iid):
+ held = append(held, host)
+ }
+ }
+ var missed []string
+ for host := range moved {
+ if !seen[host] {
+ missed = append(missed, host)
+ }
+ }
+ sort.Strings(missed)
+ if len(missed) > 0 {
+ return nil, refuse("lock_sweep_missed", "host", missed[0])
+ }
+ return held, nil
+}
+
+// section is s[name] or {} (the script's `s.get(name) or {}`).
+func section(s map[string]any, name string) map[string]any {
+ if m, ok := s[name].(map[string]any); ok {
+ return m
+ }
+ return map[string]any{}
+}
+
+// preAction is the script's Operator.pre_action (H5 and R3.1): the locks,
+// then the fence, the drain and the incarnation, read once more right
+// before the provider action. Any doubt is a failed drain.
+func (e *Engine) preAction(ctx context.Context) error {
+ iid, tx := e.hStr("iid"), e.hStr("transaction")
+ drained, hasDrained := e.last("drained", nil)
+ var held []string
+ var s map[string]any
+ err := func() error {
+ var err error
+ if held, err = e.locksNamingMember(ctx); err != nil {
+ return err
+ }
+ if s, err = e.status(ctx, iid); err != nil {
+ return err
+ }
+ return e.identity(s, iid)
+ }()
+ if err != nil {
+ if !refusalOrUncertain(err) {
+ return err
+ }
+ return e.drainFailed([]string{reasonOf(err)}, nil)
+ }
+ if len(held) > 0 {
+ if len(held) > 20 {
+ held = held[:20]
+ }
+ return e.drainFailed([]string{Text("lock_held", "hosts", strings.Join(held, ", "))}, nil)
+ }
+ fence, d := section(s, "fence"), section(s, "drain")
+ if fence["state"] != "present" || fence["transaction"] != tx {
+ return e.drainFailed([]string{Text("fence_missing")}, nil)
+ }
+ if d["state"] != "known" || d["transaction"] != tx || d["step"] != "move" || d["result"] != "ok" {
+ return e.drainFailed([]string{Text("drain_void")}, nil)
+ }
+ if !hasDrained || !pyEqual(d["incarnation"], drained["incarnation"]) {
+ return e.drainFailed([]string{Text("incarnation")}, nil)
+ }
+ _, err = e.event("pre-action-checked", map[string]any{"fence": fence, "drain": d})
+ return err
+}
+
+// stopEdge is the script's Operator.stop_edge (R3.1): stop
+// carlos-edge.service under the fence and prove it gone (MainPID 0), then
+// read the fence once more.
+func (e *Engine) stopEdge(ctx context.Context) error {
+ iid, tx := e.hStr("iid"), e.hStr("transaction")
+ if _, err := e.event("phase", map[string]any{"phase": "edge-stop"}); err != nil {
+ return err
+ }
+ r, err := e.box(ctx, iid, "edge-stop", BoxArgs{})
+ if err != nil {
+ return err
+ }
+ systemd, _ := r.Value.(map[string]any)
+ pid := pyNumber(systemd["main_pid"])
+ if pid == nil || *pid != 0 || (systemd["active_state"] != "inactive" && systemd["active_state"] != "failed") {
+ return e.alert("edge_running", false)
+ }
+ s, err := e.status(ctx, iid)
+ if err != nil {
+ return err
+ }
+ if err := e.identity(s, iid); err != nil {
+ return err
+ }
+ fence := section(s, "fence")
+ if fence["state"] != "present" || fence["transaction"] != tx {
+ return e.alert("fence_missing", false)
+ }
+ _, err = e.event("edge-stopped", map[string]any{"systemd": systemd, "fence": fence})
+ return err
+}
+
+// fenceClear is the script's Operator.fence_clear: remove this
+// transaction's fence and prove it absent.
+func (e *Engine) fenceClear(ctx context.Context) error {
+ iid := e.hStr("iid")
+ r, err := e.box(ctx, iid, "fence-clear", BoxArgs{Transaction: e.hStr("transaction")})
+ if err != nil {
+ return err
+ }
+ s, ok := r.Value.(map[string]any)
+ if !ok {
+ return refuse("record")
+ }
+ if err := e.identity(s, iid); err != nil {
+ return err
+ }
+ if section(s, "fence")["state"] != "absent" {
+ return refuse("fence_missing")
+ }
+ _, err = e.event("fence-cleared", map[string]any{"fence": s["fence"]})
+ return err
+}
// liftFence is the script's Operator.lift_fence: after a finished drain,
// clear the fence once.
func (e *Engine) liftFence(ctx context.Context) error {
if e.has("drained", nil) && !e.unchanged() && !e.has("fence-cleared", nil) {
- return refuse("unsupported")
+ return e.fenceClear(ctx)
+ }
+ return nil
+}
+
+// stopSent: an edge-stop session was ever asked for.
+func (e *Engine) stopSent() bool {
+ for _, r := range e.j.Rows() {
+ args, _ := r["args"].(map[string]any)
+ if r["kind"] == "intent" && r["op"] == "session" && args["verb"] == "edge-stop" {
+ return true
+ }
+ }
+ return false
+}
+
+// stopAndTerminate is the script's Operator.stop_and_terminate: prove the
+// edge stopped, read the locks once more now that the member can change
+// nothing, then make the provider call. An uncertain terminate is left to
+// the watch's TerminateDecision.
+func (e *Engine) stopAndTerminate(ctx context.Context) error {
+ iid := e.hStr("iid")
+ if !e.seams.terminateFirst {
+ if err := e.stopEdge(ctx); err != nil {
+ return err
+ }
+ }
+ if !e.seams.skipSecondSweep && !e.seams.terminateFirst {
+ held, err := e.locksNamingMember(ctx)
+ if err != nil {
+ return err
+ }
+ if len(held) > 0 {
+ return e.alert("lock_held_after_stop", false)
+ }
+ }
+ if _, err := e.event("phase", map[string]any{"phase": "terminate"}); err != nil {
+ return err
+ }
+ w, err := e.terminate(ctx, iid)
+ var u Uncertain
+ switch {
+ case err == nil:
+ if w.Activity != "" {
+ if _, err := e.event("terminate-activity", map[string]any{"activity": w.Activity}); err != nil {
+ return err
+ }
+ }
+ case !errors.As(err, &u):
+ return err
+ }
+ if e.seams.terminateFirst {
+ return e.stopEdge(ctx)
+ }
+ return nil
+}
+
+// terminate is the script's call("terminate", iid=..., decrement=False):
+// H4 holds in the adapter (Standby member, desired == minimum).
+func (e *Engine) terminate(ctx context.Context, iid string) (WriteResult, error) {
+ decrement := e.seams.terminateDecrement != nil
+ var w WriteResult
+ _, err := e.call(ctx, "terminate", map[string]any{"iid": iid, "decrement": decrement}, time.Time{},
+ func(ctx context.Context, _ func(string)) (any, error) {
+ var err error
+ if decrement {
+ w, err = e.seams.terminateDecrement(ctx, iid)
+ } else {
+ w, err = e.g.Terminate(ctx, iid)
+ }
+ if err != nil {
+ return nil, err
+ }
+ return writeMap(w), nil
+ })
+ return w, err
+}
+
+// raiseDesired is the script's call("desired", value=n): only a raise,
+// for the replace's final restore (H4, the adapter's own guard).
+func (e *Engine) raiseDesired(ctx context.Context, n int) error {
+ _, err := e.call(ctx, "desired", map[string]any{"value": n}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) {
+ w, err := e.g.RaiseDesired(ctx, n)
+ if err != nil {
+ return nil, err
+ }
+ return writeMap(w), nil
+ })
+ return err
+}
+
+// previousTerminateActivities is the script's
+// previous_terminate_activities: activity IDs earlier terminate attempts
+// own (those their responses named, and those listed when an earlier
+// attempt was decided), from the rows before seq.
+func (e *Engine) previousTerminateActivities(seq int64) []string {
+ ids := map[string]bool{}
+ for _, r := range e.j.Rows() {
+ if rowSeq(r) >= seq {
+ break
+ }
+ if r["kind"] == "response" && r["op"] == "terminate" {
+ if result, ok := r["result"].(map[string]any); ok {
+ if id, ok := result["activity"].(string); ok && id != "" {
+ ids[id] = true
+ }
+ }
+ }
+ if r["kind"] == "terminate-decision" {
+ facts, _ := r["facts"].(map[string]any)
+ acts, _ := facts["activities"].([]any)
+ for _, a := range acts {
+ am, _ := a.(map[string]any)
+ if id, ok := am["id"].(string); ok && id != "" {
+ ids[id] = true
+ }
+ }
+ }
+ }
+ out := make([]string, 0, len(ids))
+ for id := range ids {
+ out = append(out, id)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// departWatch is the script's Operator.depart_watch: every pass asks
+// TerminateDecision about the latest terminate intent; once the member is
+// gone, the provider check behind H4, the replace's restore of desired
+// then minimum, the departure (the member's edges file gone, DR-5), and
+// for replace the replacement admitted at the floor.
+func (e *Engine) departWatch(ctx context.Context) error {
+ iid, kind, n := e.hStr("iid"), e.kind(), e.hInt("n")
+ var survivors []string
+ for _, m := range e.hMembers() {
+ if m != iid {
+ survivors = append(survivors, m)
+ }
+ }
+ first, _ := e.last("intent", map[string]any{"op": "terminate"})
+ start := rowAtMS(first)
+ end := e.clock().Add(standbyWait)
+ var departedAt int64
+ departed := false
+ replacement := ""
+ retries := 0
+ for {
+ if !e.clock().Before(end) {
+ return e.alert("watch_timeout", false)
+ }
+ g, err := e.snapshot(ctx)
+ if err != nil {
+ return err
+ }
+ if g.View.Maximum != n || !sameValue(g.View.Template, e.header["template"]) {
+ return refuse("members")
+ }
+ if e.seams.restoreDesiredEarly && kind == "replace" && g.View.Desired < n {
+ if err := e.raiseDesired(ctx, n); err != nil {
+ return err
+ }
+ continue
+ }
+ m, listed := g.View.Members[iid]
+ phase := Absent
+ var raw any
+ if listed {
+ phase, raw = m.Phase, m.Raw
+ }
+ // Every pass, a fresh start or a resume, asks TerminateDecision.
+ intent, _ := e.last("intent", map[string]any{"op": "terminate"})
+ settled := phase == Absent || phase == Leaving
+ var response Row
+ for _, r := range e.j.Rows() {
+ if r["kind"] == "response" && sameValue(r["intent"], intent["seq"]) {
+ response = r
+ break
+ }
+ }
+ activityID := ""
+ if result, ok := response["result"].(map[string]any); ok {
+ activityID, _ = result["activity"].(string)
+ }
+ facts := TerminateFacts{Phase: phase, Answered: response != nil, ActivityID: activityID,
+ PreviousIDs: e.previousTerminateActivities(rowSeq(intent)), IntentAt: rowAtMS(intent),
+ IntentSeq: int(rowSeq(intent)), Now: ms(e.clock()), Retries: retries}
+ if !settled && phase == Parked {
+ as, err := e.activities(ctx, iid)
+ if err != nil {
+ return err
+ }
+ for _, a := range as {
+ if a.Kind == "terminate" {
+ facts.Activities = append(facts.Activities, a)
+ }
+ }
+ }
+ d := TerminateDecision(facts)
+ if !settled {
+ var reason, id any
+ if d.Reason != "" {
+ reason = d.Reason
+ }
+ if activityID != "" {
+ id = activityID
+ }
+ previous := make([]any, len(facts.PreviousIDs))
+ for i, p := range facts.PreviousIDs {
+ previous[i] = p
+ }
+ journaled := map[string]any{"phase": raw, "member_phase": string(phase), "intent_at": facts.IntentAt,
+ "intent_seq": facts.IntentSeq, "now": facts.Now, "retries": retries, "answered": facts.Answered,
+ "activity_id": id, "previous_ids": previous, "activities": activityRows(iid, facts.Activities)}
+ if _, err := e.event("terminate-decision", map[string]any{"action": d.Action, "reason": reason,
+ "facts": journaled}); err != nil {
+ return err
+ }
+ }
+ switch d.Action {
+ case "fail":
+ // An explicit, recoverable stop; the journal stays for resume.
+ key := d.Reason
+ if key == "" {
+ key = "terminate_status"
+ }
+ return e.alert(key, false)
+ case "retry":
+ retries++
+ if err := e.stopAndTerminate(ctx); err != nil {
+ return err
+ }
+ continue
+ case "wait":
+ e.sleepWithin(d, end)
+ continue
+ case "done":
+ default:
+ return refuse("record")
+ }
+ others := []string{}
+ for _, member := range sortedMembers(g.View) {
+ if member != iid {
+ others = append(others, member)
+ }
+ }
+ if !e.has("terminate-checked", nil) {
+ // The provider check behind H4: terminating the Standby member
+ // changed neither desired nor membership.
+ if g.View.Desired != n-1 || g.View.Minimum != n-1 || !sameStrings(others, survivors) {
+ return e.alert("desired_changed", true)
+ }
+ members := []any{}
+ for _, member := range sortedMembers(g.View) {
+ members = append(members, member)
+ }
+ if _, err := e.event("terminate-checked", map[string]any{"desired": g.View.Desired, "members": members}); err != nil {
+ return err
+ }
+ }
+ if kind == "replace" && g.View.Desired < n {
+ if _, err := e.event("phase", map[string]any{"phase": "restore-desired"}); err != nil {
+ return err
+ }
+ if err := e.raiseDesired(ctx, n); err != nil {
+ return err
+ }
+ continue
+ }
+ if kind == "replace" && g.View.Minimum < n {
+ if _, err := e.event("phase", map[string]any{"phase": "restore-minimum"}); err != nil {
+ return err
+ }
+ if err := e.setMinimum(ctx, n); err != nil {
+ return err
+ }
+ continue
+ }
+ if !departed {
+ keys, err := e.edgesList(ctx)
+ if err != nil {
+ return err
+ }
+ ref, _ := e.hIdentity()["box_ref"].(string)
+ present := false
+ for _, k := range keys {
+ if m := EdgesKey.FindStringSubmatch(k); m != nil && m[1] == ref {
+ present = true
+ }
+ }
+ if !present {
+ departed, departedAt = true, ms(e.clock())
+ if _, err := e.event("departure-finished", map[string]any{"seconds": seconds(departedAt - start)}); err != nil {
+ return err
+ }
+ }
+ }
+ ready := true
+ for _, member := range survivors {
+ ready = ready && peerOK(g, member)
+ }
+ if kind == "replace" {
+ var fresh []string
+ for _, member := range others {
+ if !containsString(e.hMembers(), member) {
+ fresh = append(fresh, member)
+ }
+ }
+ if len(fresh) > 1 || g.View.Desired != n || g.View.Minimum != n {
+ return refuse("members")
+ }
+ ready = ready && len(fresh) == 1 && peerOK(g, fresh[0])
+ if ready && replacement == "" {
+ err := e.admitReplacement(ctx, fresh[0], start)
+ switch {
+ case err == nil:
+ replacement = fresh[0]
+ case refusalOrUncertain(err):
+ ready = false
+ default:
+ return err
+ }
+ }
+ ready = ready && replacement != ""
+ } else if g.View.Desired != n-1 || g.View.Minimum != n-1 || !sameStrings(others, survivors) {
+ return e.alert("desired_changed", true)
+ }
+ if ready && departed {
+ return e.finishDepart(start, departedAt, replacement)
+ }
+ e.sleepFor(summaryWait, end)
+ }
+}
+
+// admitReplacement: the replacement is online, ready, and at the floor
+// too (§25.9: it publishes ha_take 1).
+func (e *Engine) admitReplacement(ctx context.Context, iid string, start int64) error {
+ on, err := e.online(ctx, iid)
+ if err != nil {
+ return err
+ }
+ if !on {
+ return refuse("offline")
+ }
+ r, err := e.readiness(ctx, iid)
+ if err != nil {
+ return err
+ }
+ if take, ok := r.Edges["ha_take"].(int64); !ok || take != 1 {
+ return refuse("admission")
+ }
+ _, err = e.event("replacement-admitted", map[string]any{"iid": iid, "seconds": seconds(ms(e.clock()) - start)})
+ return err
+}
+
+// seconds is a millisecond span in the script's float seconds.
+func seconds(ms int64) float64 { return float64(ms) / 1000 }
+
+func containsString(xs []string, x string) bool {
+ for _, s := range xs {
+ if s == x {
+ return true
+ }
+ }
+ return false
+}
+
+// finishDepart is the script's Operator.finish_depart: the fence went
+// with the member's disk, so no fence-clear; the summary; done.
+func (e *Engine) finishDepart(start, departedAt int64, replacement string) error {
+ kind, n := e.kind(), e.hInt("n")
+ // R3.1: the fence lived on the member's disk, which went with it.
+ if _, err := e.event("fence-moot", map[string]any{"reason": Text("fence_moot")}); err != nil {
+ return err
+ }
+ e.say("fence", Text("fence_moot"))
+ var r any
+ if replacement != "" {
+ r = replacement
+ }
+ if err := e.drainSummary(map[string]any{"replacement": r, "departure_seconds": seconds(departedAt - start)}); err != nil {
+ return err
+ }
+ outcome := "removed"
+ if kind == "replace" {
+ outcome = "replaced"
+ }
+ if _, err := e.event("done", map[string]any{"outcome": outcome}); err != nil {
+ return err
+ }
+ if err := e.s.Finish(); err != nil {
+ return err
+ }
+ if kind == "replace" {
+ e.say("done", Text("replaced"))
+ } else {
+ e.say("done", Text("removed", "n", strconv.Itoa(n-1)))
+ }
+ return nil
+}
+
+// sized is Python's len() of a report field, `len(x or [])`.
+func sized(v any) (int, error) {
+ switch x := v.(type) {
+ case nil:
+ return 0, nil
+ case bool:
+ if !x {
+ return 0, nil
+ }
+ case []any:
+ return len(x), nil
+ case map[string]any:
+ return len(x), nil
+ case string:
+ return len([]rune(x)), nil
+ }
+ if n := pyNumber(v); n != nil && *n == 0 {
+ return 0, nil
+ }
+ // len() of a number raised TypeError, which main printed as record.
+ return 0, refuse("record")
+}
+
+// drainSummary is the script's Operator.drain_summary: the drain's
+// outcome for the operator, journaled as report and printed as one JSON
+// line (Python's json.dumps with sort_keys).
+func (e *Engine) drainSummary(extra map[string]any) error {
+ drained, _ := e.last("drained", nil)
+ report := section(drained, "report")
+ holds := section(report, "holds")
+ moved, err := sized(report["moved"])
+ if err != nil {
+ return err
+ }
+ released, err := sized(report["released"])
+ if err != nil {
+ return err
}
+ summary := map[string]any{"transaction": e.hStr("transaction"), "transaction_kind": e.kind(),
+ "member": e.hStr("iid"), "hosts_moved": moved, "hosts_released": released,
+ "longest_hold_ms": holds["longest_ms"], "todays_answer": holds["todays_answer"],
+ "connections_closed_at_bound": report["connections_closed_at_bound"]}
+ for k, v := range extra {
+ summary[k] = v
+ }
+ if _, err := e.event("report", summary); err != nil {
+ return err
+ }
+ line, err := pythonDumps(summary)
+ if err != nil {
+ return refuse("record")
+ }
+ _, _ = e.out.Write([]byte(line + "\n"))
return nil
}
-// drainSummary is the script's Operator.drain_summary.
-func (e *Engine) drainSummary() error { return refuse("unsupported") }
+// CancelDrain is the script's cancel_drain: drain --cancel on the member
+// for transaction tx, a transaction closed after a failed drain or one
+// whose return stopped because the agent may still move hosts. The box
+// verb removes the fence and fails unless the agent or systemd confirmed
+// the stop; status proves it. The caller holds the group lock.
+func (e *Engine) CancelDrain(ctx context.Context, iid, tx string) error {
+ if !e.s.Held() || !TX.MatchString(tx) || strings.HasPrefix(tx, "-") {
+ return refuse("record")
+ }
+ j, err := e.s.Load(tx, false)
+ if err != nil {
+ return err
+ }
+ e.open(j)
+ defer e.close()
+ done, closed := e.last("done", nil)
+ // A closed failed drain, or one whose return stopped because the
+ // agent still moved hosts (refuseWhileMoving).
+ stoppedMoving := !closed && e.has("return-refused-moving", nil)
+ kind := e.kind()
+ if (kind != "roll" && !departKinds[kind]) || e.hStr("iid") != iid ||
+ !(stoppedMoving || closed && done["outcome"] == "drain-failed") || !e.has("drain-failed", nil) {
+ return refuse("cancel_refused")
+ }
+ if valid, ok := e.last("validated", nil); ok {
+ for k, v := range valid {
+ switch k {
+ case "seq", "previous", "hash", "kind", "at_ms":
+ continue
+ }
+ e.header[k] = v
+ }
+ }
+ r, err := e.box(ctx, iid, "drain-cancel", BoxArgs{Transaction: tx})
+ if err != nil {
+ return err
+ }
+ v, ok := r.Value.(map[string]any)
+ if !ok {
+ return refuse("record")
+ }
+ if exit := pyNumber(v["exit"]); exit != nil && *exit == 1 {
+ if _, err := e.event("drain-cancel-failed", map[string]any{"detail": v["detail"]}); err != nil {
+ return err
+ }
+ return refuse("cancel_failed", "detail", pyStrOf(v["detail"]))
+ }
+ if err := e.identity(v, iid); err != nil {
+ return err
+ }
+ fence, drain := section(v, "fence"), section(v, "drain")
+ if fence["state"] != "absent" || drain["transaction"] == tx {
+ if _, err := e.event("drain-cancel-failed", map[string]any{"fence": fence, "drain": drain}); err != nil {
+ return err
+ }
+ f, ferr := pythonDumps(fence)
+ d, derr := pythonDumps(drain)
+ if ferr != nil || derr != nil {
+ return refuse("record")
+ }
+ // The script's json.dumps(dict(fence=..., drain=...)): fence first.
+ return refuse("cancel_failed", "detail", `{"fence": `+f+`, "drain": `+d+`}`)
+ }
+ if _, err := e.event("drain-cancelled", map[string]any{"fence": fence, "drain": drain,
+ "attended_by": e.attended}); err != nil {
+ return err
+ }
+ e.say("cancel-drain", Text("cancelled"))
+ return nil
+}
diff --git a/internal/grouproll/depart_test.go b/internal/grouproll/depart_test.go
new file mode 100644
index 000000000..9eb8bd7cc
--- /dev/null
+++ b/internal/grouproll/depart_test.go
@@ -0,0 +1,1470 @@
+//go:build linux || darwin
+
+package grouproll
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The planned handovers against the held fake: ports of
+// held-floor-sha-map's scripts/region_group_held_test.py ReplaceTests,
+// CancelDrainTests, RemoveTests, RemoveMinimumTests, DrainedRollTests and
+// the departure halves of FloorTests (the floor itself is floor_test.go's).
+
+const heldTx = "t6-held"
+
+// newHeldHarness is HeldBase.setUp: the held config (ha_floor v0.35.0, a
+// data bucket and prefix), the held fake, every live box at the floor,
+// the template pinned at v0.35.0 and the golden router pointer. configure,
+// when set, changes the config further before the state opens.
+func newHeldHarness(t *testing.T, members int, configure func(c *Config)) *harness {
+ t.Helper()
+ h := newHarnessWith(t, stateRoot(t), members, func(c *Config) {
+ floor, prefix, bucket := "v0.35.0", "instances", "example-bucket"
+ c.HAFloor, c.DataPrefix, c.DataBucket = &floor, &prefix, &bucket
+ if configure != nil {
+ configure(c)
+ }
+ })
+ f := h.f
+ f.version = "v0.35.0"
+ f.haTake = map[string]any{}
+ f.fixed = map[string]fixedEdges{"adi": {haTake: int64(1), age: 5 * time.Second}}
+ f.templateRelease = "v0.35.0"
+ f.pointers = map[string][]byte{"stable": floorFixture(t, "router-pointer-golden.json")}
+ f.held = newHeldFake(f)
+ return h
+}
+
+func (h *harness) depart(kind, tx string) error {
+ return h.locked(func(e *Engine) error { return e.Depart(bg, fakeIID, kind, tx) })
+}
+
+func (h *harness) cancelDrain(iid, tx string) error {
+ return h.locked(func(e *Engine) error { return e.CancelDrain(bg, iid, tx) })
+}
+
+// verbs is HeldBase.verbs: every group write and box action asked of the
+// provider, answered or not, in order.
+func (h *harness) verbs() []string {
+ out := []string{}
+ for _, c := range h.f.calls {
+ switch c.Op {
+ case "minimum", "enter", "exit", "terminate", "desired":
+ out = append(out, c.Op)
+ case "session":
+ if v := c.Args["verb"]; v != "status" {
+ out = append(out, v.(string))
+ }
+ }
+ }
+ return out
+}
+
+func (h *harness) mustH4() {
+ h.t.Helper()
+ if len(h.f.held.h4) != 0 || h.f.states[fakePeer] == "Terminated" {
+ h.t.Fatalf("H4 violated: %v, peer %s", h.f.held.h4, h.f.states[fakePeer])
+ }
+ if len(h.f.violations) != 0 {
+ h.t.Fatalf("protocol breaches: %v", h.f.violations)
+ }
+}
+
+func drainCancelText(tx string) string {
+ return Text("drain_cancel", "config", "/etc/carlos-group/test.json", "iid", fakeIID, "transaction", tx)
+}
+
+// mustReturned is assert_returned: after a failed drain the member is
+// back in service with the shape restored, nothing was stopped or
+// terminated, and the fence stays for drain --cancel.
+func (h *harness) mustReturned(tx string) {
+ h.t.Helper()
+ f := h.f
+ if f.states[fakeIID] != "InService" {
+ h.t.Fatalf("member %s", f.states[fakeIID])
+ }
+ if f.minimum != f.maximum || f.desired != f.maximum {
+ h.t.Fatalf("shape %d %d %d", f.minimum, f.desired, f.maximum)
+ }
+ for _, v := range []string{"terminate", "edge-stop", "fence-clear"} {
+ if countOf(h.verbs(), v) != 0 {
+ h.t.Fatalf("%s sent: %v", v, h.verbs())
+ }
+ }
+ if f.held.fence != tx {
+ h.t.Fatalf("fence %q, want %q", f.held.fence, tx)
+ }
+ if h.activeTx() != "" {
+ h.t.Fatalf("transaction %s still open", h.activeTx())
+ }
+ if !strings.Contains(h.out.String(), drainCancelText(tx)) {
+ h.t.Fatalf("output lacks the cancel-drain instruction: %s", h.out.String())
+ }
+ if done, _ := h.txJournal(tx).Last("done", nil); done["outcome"] != "drain-failed" {
+ h.t.Fatalf("done %v", done)
+ }
+ h.mustH4()
+}
+
+// drainReasons is the last drain-failed row's reasons.
+func (h *harness) drainReasons(tx string) []any {
+ h.t.Helper()
+ row, ok := h.txJournal(tx).Last("drain-failed", nil)
+ if !ok {
+ h.t.Fatal("no drain-failed row")
+ }
+ r, _ := row["reasons"].([]any)
+ return r
+}
+
+func (h *harness) mustDrainReasons(tx string, want ...string) {
+ h.t.Helper()
+ got := h.drainReasons(tx)
+ w := make([]any, len(want))
+ for i, s := range want {
+ w[i] = s
+ }
+ if !reflect.DeepEqual(got, w) {
+ h.t.Fatalf("drain-failed reasons %v, want %v", got, w)
+ }
+}
+
+func rowsOf(j *Journal, kind string) []Row {
+ var out []Row
+ for _, r := range j.Rows() {
+ if r["kind"] == kind {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+func indexOfKind(j *Journal, kind string) int {
+ for i, r := range j.Rows() {
+ if r["kind"] == kind {
+ return i
+ }
+ }
+ return -1
+}
+
+func refusedWith(t *testing.T, err error, key string) {
+ t.Helper()
+ if refusalKey(err) != key {
+ t.Fatalf("err = %v, want the %s refusal", err, key)
+ }
+}
+
+// test_replace_order_restores_shape_and_watches.
+func TestDepartReplaceOrderRestoresShapeAndWatches(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatalf("%v\n%s", err, h.out.String())
+ }
+ f := h.f
+ want := []string{"minimum", "enter", "drain", "edge-stop", "terminate", "desired", "minimum"}
+ if !reflect.DeepEqual(h.verbs(), want) {
+ t.Fatalf("verbs %v, want %v", h.verbs(), want)
+ }
+ if f.minimum != 2 || f.desired != 2 || f.maximum != 2 {
+ t.Fatalf("shape %d %d %d", f.minimum, f.desired, f.maximum)
+ }
+ if f.states[fakeIID] != "Terminated" || f.states[replacementIID] != "InService" || f.launches != 0 {
+ t.Fatalf("states %v launches %d", f.states, f.launches)
+ }
+ if !f.held.departed[ref(fakeIID)] {
+ t.Fatal("the member's edges file was never seen gone")
+ }
+ h.mustH4()
+ if h.activeTx() != "" {
+ t.Fatal("transaction still open")
+ }
+ j := h.txJournal(heldTx)
+ // The H5 check is the last thing before the stop, and the stop is
+ // proven before the provider call.
+ if !(indexOfKind(j, "drained") < indexOfKind(j, "pre-action-checked") &&
+ indexOfKind(j, "pre-action-checked") < indexOfKind(j, "edge-stopped")) {
+ t.Fatal("drained, pre-action-checked and edge-stopped out of order")
+ }
+ terminate, _ := j.Last("intent", map[string]any{"op": "terminate"})
+ stopped, _ := j.Last("edge-stopped", nil)
+ if rowSeq(stopped) >= rowSeq(terminate) {
+ t.Fatal("terminate before the stop was proven")
+ }
+ if !sameValue(terminate["args"], map[string]any{"iid": fakeIID, "decrement": false}) {
+ t.Fatalf("terminate args %v", terminate["args"])
+ }
+ floor, _ := j.Last("floor", nil)
+ live, _ := floor["live"].([]any)
+ var names []string
+ for _, l := range live {
+ names = append(names, l.(string))
+ }
+ sort.Strings(names)
+ if floor["rule"] != "drain" || !reflect.DeepEqual(names, []string{"adi", ref(fakeIID), ref(fakePeer)}) {
+ t.Fatalf("floor %v", floor)
+ }
+ for _, k := range []string{"fence-moot", "replacement-admitted"} {
+ if _, ok := j.Last(k, nil); !ok {
+ t.Fatalf("no %s row", k)
+ }
+ }
+ report, _ := j.Last("report", nil)
+ if !sameValue(report["hosts_moved"], 1) || !sameValue(report["longest_hold_ms"], 1500) ||
+ !sameValue(report["todays_answer"], 0) || report["replacement"] != replacementIID {
+ t.Fatalf("report %v", report)
+ }
+ if done, _ := j.Last("done", nil); done["outcome"] != "replaced" {
+ t.Fatalf("done %v", done)
+ }
+ for _, s := range []string{Text("rule_drain"), Text("fence_moot"), Text("replaced")} {
+ if !strings.Contains(h.out.String(), s) {
+ t.Fatalf("output lacks %q", s)
+ }
+ }
+ // Store calls, counted: each lock sweep is one delimiter listing, one
+ // exact-key listing per host (3 here) and one GET per lock that exists
+ // (idle has none). It runs twice per transaction, before and after the
+ // edge stop, never on a timer. (The script counted one listing page
+ // per host; release.Store pages inside ListDirs.)
+ ops := h.f.ops()
+ if countOf(ops, "lock_hosts") != 2 || countOf(ops, "lock_list") != 2*3 || countOf(ops, "lock_get") != 2*2 {
+ t.Fatalf("lock reads: hosts %d keys %d gets %d", countOf(ops, "lock_hosts"), countOf(ops, "lock_list"),
+ countOf(ops, "lock_get"))
+ }
+}
+
+// test_replace_resumes_after_every_write: a death before or after any of
+// the seven writes is resumed to a finished replace, and a terminate cut
+// before it reached the provider is sent again.
+func TestDepartReplaceResumesAfterEveryWrite(t *testing.T) {
+ for _, before := range []bool{false, true} {
+ for boundary := 1; boundary <= 7; boundary++ {
+ t.Run(fmt.Sprintf("before=%v/%d", before, boundary), func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.fault, h.f.faultAt, h.f.failBefore = "death", boundary, before
+ if !expectDeath(t, func() { h.depart("replace", heldTx) }) {
+ t.Fatal("no death")
+ }
+ if err := h.resume(); err != nil {
+ t.Fatalf("resume: %v\n%s", err, h.out.String())
+ }
+ f := h.f
+ if f.minimum != 2 || f.desired != 2 || f.states[fakeIID] != "Terminated" ||
+ f.states[replacementIID] != "InService" {
+ t.Fatalf("shape %d %d states %v", f.minimum, f.desired, f.states)
+ }
+ if countOf(f.writes, "terminate") != 1 || h.activeTx() != "" {
+ t.Fatalf("writes %v active %q", f.writes, h.activeTx())
+ }
+ h.mustH4()
+ })
+ }
+ }
+}
+
+// test_failed_drain_returns_member_and_prints_cancel.
+func TestDepartFailedDrainReturnsMemberAndPrintsCancel(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "fail"
+ refusedWith(t, h.depart("replace", heldTx), "drain_failed")
+ if want := []string{"minimum", "enter", "drain", "exit", "minimum"}; !reflect.DeepEqual(h.verbs(), want) {
+ t.Fatalf("verbs %v, want %v", h.verbs(), want)
+ }
+ h.mustReturned(heldTx)
+ if !strings.Contains(h.out.String(), Text("drain_reason", "reason", "the connections did not drain")) {
+ t.Fatalf("output lacks the drain's reason: %s", h.out.String())
+ }
+}
+
+// test_uncertain_drain_session_is_a_failed_drain.
+func TestDepartUncertainDrainSessionIsAFailedDrain(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "uncertain"
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ f := h.f
+ if f.states[fakeIID] != "InService" || f.minimum != 2 || f.desired != 2 || countOf(h.verbs(), "terminate") != 0 {
+ t.Fatalf("states %v shape %d %d verbs %v", f.states, f.minimum, f.desired, h.verbs())
+ }
+ if !strings.Contains(h.out.String(), drainCancelText(heldTx)) {
+ t.Fatal("no cancel-drain instruction")
+ }
+ if f.held.drainCalls != 0 {
+ t.Fatalf("drain calls %d", f.held.drainCalls)
+ }
+ if n := countOf(h.verbs(), "drain"); n != DrainTries {
+ t.Fatalf("drain sessions %d, want %d", n, DrainTries)
+ }
+}
+
+// test_dropped_drain_session_rerun_joins_the_move.
+func TestDepartDroppedDrainSessionRerunJoinsTheMove(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "drop-once"
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if h.f.states[fakeIID] != "Terminated" || h.f.held.drainCalls != 2 {
+ t.Fatalf("state %s drain calls %d", h.f.states[fakeIID], h.f.held.drainCalls)
+ }
+ j := h.txJournal(heldTx)
+ if u, _ := j.Last("drain-uncertain", nil); !sameValue(u["attempt"], 1) {
+ t.Fatalf("drain-uncertain %v", u)
+ }
+ if _, ok := j.Last("drain-failed", nil); ok {
+ t.Fatal("a drain-failed row")
+ }
+}
+
+// cancelThenResume is the operator's recovery from a stop while the drain
+// may still move hosts: cancel-drain, then resume, which returns the
+// member and closes drain-failed.
+func cancelThenResume(t *testing.T, h *harness) {
+ t.Helper()
+ if err := h.cancelDrain(fakeIID, heldTx); err != nil {
+ t.Fatalf("cancel-drain: %v", err)
+ }
+ if h.f.held.fence != "" {
+ t.Fatal("the fence survived cancel-drain")
+ }
+ refusedWith(t, h.resume(), "drain_failed")
+ f := h.f
+ if f.states[fakeIID] != "InService" || f.minimum != 2 || f.desired != 2 ||
+ countOf(h.verbs(), "terminate") != 0 || f.held.fence != "" || h.activeTx() != "" {
+ t.Fatalf("states %v shape %d %d verbs %v fence %q active %q", f.states, f.minimum, f.desired,
+ h.verbs(), f.held.fence, h.activeTx())
+ }
+}
+
+// test_failed_drain_never_returns_a_member_still_moving: every session
+// drops while the agent's move runs, so the member stays in Standby;
+// cancel-drain works on the stopped transaction; the return completes.
+func TestDepartFailedDrainNeverReturnsAMemberStillMoving(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "drop-running"
+ err := h.depart("replace", heldTx)
+ if !isStop(err, "drain-moving") {
+ t.Fatalf("depart = %v", err)
+ }
+ if h.f.held.drainCalls != DrainTries || h.f.states[fakeIID] != "Standby" ||
+ countOf(h.verbs(), "exit") != 0 || countOf(h.verbs(), "terminate") != 0 || h.activeTx() != heldTx {
+ t.Fatalf("drain calls %d state %s verbs %v active %q", h.f.held.drainCalls, h.f.states[fakeIID],
+ h.verbs(), h.activeTx())
+ }
+ cancelThenResume(t, h)
+}
+
+// test_remote_timeout_reruns_and_joins: the remote bound's exit 124 is
+// not a failed drain.
+func TestDepartRemoteTimeoutRerunsAndJoins(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "remote-timeout"
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if h.f.states[fakeIID] != "Terminated" || h.f.held.drainCalls != 2 {
+ t.Fatalf("state %s drain calls %d", h.f.states[fakeIID], h.f.held.drainCalls)
+ }
+ j := h.txJournal(heldTx)
+ if u, _ := j.Last("drain-uncertain", nil); !sameValue(u["attempt"], 1) {
+ t.Fatalf("drain-uncertain %v", u)
+ }
+ if _, ok := j.Last("drain-failed", nil); ok {
+ t.Fatal("a drain-failed row")
+ }
+}
+
+// test_unknown_drain_status_never_returns_the_member: every session drops
+// while the move runs, and status cannot reach the agent: unknown is not
+// proof the move ended.
+func TestDepartUnknownDrainStatusNeverReturnsTheMember(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "drop-running"
+ h.f.held.statusDrain = func(map[string]any) map[string]any {
+ return map[string]any{"state": "unknown", "incarnation": nil, "transaction": nil, "step": nil,
+ "result": nil, "error": "context deadline exceeded"}
+ }
+ if err := h.depart("replace", heldTx); !isStop(err, "drain-moving") {
+ t.Fatalf("depart = %v", err)
+ }
+ if h.f.states[fakeIID] != "Standby" || countOf(h.verbs(), "exit") != 0 || h.activeTx() != heldTx {
+ t.Fatalf("state %s verbs %v active %q", h.f.states[fakeIID], h.verbs(), h.activeTx())
+ }
+ row, _ := h.txJournal(heldTx).Last("return-refused-moving", nil)
+ if d, _ := row["drain"].(map[string]any); d["state"] != "unknown" {
+ t.Fatalf("return-refused-moving %v", row)
+ }
+ if !strings.Contains(h.out.String(), Text("drain_moving", "config", "/etc/carlos-group/test.json",
+ "iid", fakeIID, "transaction", heldTx)) {
+ t.Fatal("no drain-moving instruction")
+ }
+ h.f.held.statusDrain = nil
+ cancelThenResume(t, h)
+}
+
+// test_dropped_sessions_after_a_finished_move_return_fenced.
+func TestDepartDroppedSessionsAfterAFinishedMoveReturnFenced(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "drop-done"
+ refusedWith(t, h.depart("replace", heldTx), "drain_failed")
+ if h.f.held.drainCalls != DrainTries {
+ t.Fatalf("drain calls %d", h.f.held.drainCalls)
+ }
+ h.mustReturned(heldTx)
+}
+
+// test_lock_still_naming_member_refuses_action.
+func TestDepartLockStillNamingMemberRefusesAction(t *testing.T) {
+ for _, owner := range []string{
+ fmt.Sprintf("box/v1;ref=%s;iid=%s;pid=9;ha=1", ref(fakeIID), fakeIID),
+ fmt.Sprintf("box/v1;ref=other;iid=%s;pid=9;ha=1", fakeIID),
+ ref(fakeIID) + ":4242",
+ } {
+ t.Run(owner, func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ l := heldLock(ref(fakePeer), fakePeer)
+ l["owner"] = owner
+ h.f.held.locks["blog"] = l
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustReturned(heldTx)
+ h.mustDrainReasons(heldTx, Text("lock_held", "hosts", "blog"))
+ })
+ }
+}
+
+// test_marker_and_other_owner_locks_pass.
+func TestDepartMarkerAndOtherOwnerLocksPass(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.locks["a"] = heldMarker(ref(fakeIID))
+ h.f.held.locks["b"] = heldLock(ref(fakeIID)+"x", fakePeer)
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if h.f.states[fakeIID] != "Terminated" {
+ t.Fatalf("state %s", h.f.states[fakeIID])
+ }
+ // Every host was listed: shop, blog, idle, a and b.
+ row, _ := h.txJournal(heldTx).Last("response", map[string]any{"op": "lock_hosts"})
+ if !sameValue(row["result"], []any{"a", "b", "blog", "idle", "shop"}) {
+ t.Fatalf("hosts %v", row["result"])
+ }
+}
+
+// test_stale_incarnation_refuses_action: the agent no longer reports this
+// drain.
+func TestDepartStaleIncarnationRefusesAction(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.afterDrain = func() { h.f.held.drainState = idleDrain(heldRestarted) }
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustReturned(heldTx)
+ h.mustDrainReasons(heldTx, Text("drain_void"))
+}
+
+// test_failed_drain_after_agent_restart_still_returns: the drain fails
+// because the agent restarted; the member still returns, fenced.
+func TestDepartFailedDrainAfterAgentRestartStillReturns(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.afterDrain = h.f.restartAgent
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustReturned(heldTx)
+ if h.f.edge(fakeIID)["identity"] == "boot-"+fakeIID+":100:100" {
+ t.Fatal("the agent did not restart")
+ }
+ if h.f.held.tenantStart() {
+ t.Fatal("a fenced member started a tenant")
+ }
+}
+
+// test_lock_sweep_bucket_is_the_config: the member's edges file names
+// another bucket: refuse, never sweep it.
+func TestDepartLockSweepBucketIsTheConfig(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.edgesBody = func(r string, body map[string]any) {
+ if r == ref(fakeIID) {
+ body["data_bucket"] = "other-bucket"
+ }
+ }
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustReturned(heldTx)
+ if n := countOf(h.f.ops(), "lock_hosts") + countOf(h.f.ops(), "lock_list"); n != 0 {
+ t.Fatalf("%d data bucket listings", n)
+ }
+ h.mustDrainReasons(heldTx, Text("data_bucket_mismatch", "bucket", "other-bucket"))
+}
+
+// test_lock_sweep_must_see_moved_hosts: the drain moved blog; a sweep
+// that finds no blog lock looked in the wrong place.
+func TestDepartLockSweepMustSeeMovedHosts(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.locks["blog"] = nil
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustReturned(heldTx)
+ h.mustDrainReasons(heldTx, Text("lock_sweep_missed", "host", "blog"))
+}
+
+// test_changed_incarnation_with_finished_drain_refuses: a second agent
+// that reports the same finished drain is still void.
+func TestDepartChangedIncarnationWithFinishedDrainRefuses(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.afterDrain = func() { h.f.held.drainState["incarnation"] = heldRestarted }
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustReturned(heldTx)
+ h.mustDrainReasons(heldTx, Text("incarnation"))
+}
+
+// test_missing_fence_refuses_action.
+func TestDepartMissingFenceRefusesAction(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.afterDrain = func() { h.f.held.fence = "" }
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ if h.f.states[fakeIID] != "InService" || countOf(h.verbs(), "terminate") != 0 {
+ t.Fatalf("state %s verbs %v", h.f.states[fakeIID], h.verbs())
+ }
+ h.mustDrainReasons(heldTx, Text("fence_missing"))
+}
+
+// test_edge_still_running_holds_standby_until_proven.
+func TestDepartEdgeStillRunningHoldsStandbyUntilProven(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.edgeStops = false
+ refusedWith(t, h.depart("replace", heldTx), "edge_running")
+ f := h.f
+ if f.states[fakeIID] != "Standby" || f.minimum != 1 || f.desired != 1 || countOf(h.verbs(), "terminate") != 0 ||
+ h.activeTx() != heldTx {
+ t.Fatalf("state %s shape %d %d verbs %v", f.states[fakeIID], f.minimum, f.desired, h.verbs())
+ }
+ f.held.edgeStops = true
+ if err := h.resume(); err != nil {
+ t.Fatal(err)
+ }
+ if f.states[fakeIID] != "Terminated" || countOf(h.verbs(), "edge-stop") != 2 {
+ t.Fatalf("state %s verbs %v", f.states[fakeIID], h.verbs())
+ }
+ // The resumed stop read the locks again after the edge was gone.
+ j := h.txJournal(heldTx)
+ stops := rowsOf(j, "edge-stopped")
+ last := rowSeq(stops[len(stops)-1])
+ read := false
+ for _, r := range j.Rows() {
+ if r["kind"] == "intent" && r["op"] == "lock_hosts" && rowSeq(r) > last {
+ read = true
+ }
+ }
+ if !read {
+ t.Fatal("no lock sweep after the proven stop")
+ }
+ h.mustH4()
+}
+
+// Go-only: the stop is proven only by MainPID 0 and an inactive or failed
+// unit; either half alone holds the member in Standby.
+func TestDepartEdgeStopNeedsMainPIDZeroAndInactive(t *testing.T) {
+ for _, answer := range []map[string]any{
+ {"main_pid": int64(4242), "active_state": "inactive"},
+ {"main_pid": int64(4242), "active_state": "failed"},
+ {"main_pid": int64(0), "active_state": "deactivating"},
+ } {
+ t.Run(fmt.Sprint(answer), func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.edgeStops, h.f.held.edgeStopAnswer = false, answer
+ refusedWith(t, h.depart("replace", heldTx), "edge_running")
+ if h.f.states[fakeIID] != "Standby" || countOf(h.verbs(), "terminate") != 0 {
+ t.Fatalf("state %s verbs %v", h.f.states[fakeIID], h.verbs())
+ }
+ })
+ }
+}
+
+// Go-only: a fence of another transaction is no fence of this one, before
+// the action and after the stop.
+func TestDepartOtherTransactionsFenceRefuses(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.afterDrain = func() { h.f.held.fence = "other-tx" }
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustDrainReasons(heldTx, Text("fence_missing"))
+ h = newHeldHarness(t, 2, nil)
+ h.f.before = func(op string, args map[string]any) error {
+ if op == "session" && args["verb"] == "edge-stop" {
+ h.f.held.fence = "other-tx"
+ }
+ return nil
+ }
+ refusedWith(t, h.depart("replace", heldTx), "fence_missing")
+ if h.f.states[fakeIID] != "Standby" || countOf(h.verbs(), "terminate") != 0 {
+ t.Fatalf("state %s verbs %v", h.f.states[fakeIID], h.verbs())
+ }
+}
+
+// Go-only: the report must be this transaction's finished, fenced move
+// from a known incarnation; anything else is a failed drain naming the
+// report's own reasons when it gives some for this transaction.
+func TestDepartDrainReportMustBeThisFencedMove(t *testing.T) {
+ cases := map[string]struct {
+ edit func(r map[string]any)
+ want []string
+ }{
+ "other fence": {func(r map[string]any) { r["fence"] = "other-tx" }, []string{Text("drain_report")}},
+ "other step": {func(r map[string]any) { r["step"] = "quiesce" }, []string{Text("drain_report")}},
+ "short incarnation": {func(r map[string]any) { r["incarnation"] = "1234" }, []string{Text("drain_report")}},
+ "other transaction": {func(r map[string]any) { r["transaction"], r["reasons"] = "other-tx", []any{"x"} }, []string{Text("drain_report")}},
+ "reasons of this one": {func(r map[string]any) { r["result"], r["reasons"] = "failed", []any{"a", "b"} }, []string{"a", "b"}},
+ "no report": {func(r map[string]any) { delete(r, "v") }, nil},
+ }
+ for name, c := range cases {
+ t.Run(name, func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.reportEdit = c.edit
+ if name == "no report" {
+ h.f.held.drainMode = "refused"
+ c.want = []string{Text("drain_report")}
+ }
+ refusedWith(t, h.depart("replace", heldTx), "drain_failed")
+ h.mustDrainReasons(heldTx, c.want...)
+ if _, ok := h.txJournal(heldTx).Last("drained", nil); ok {
+ t.Fatal("a drained row")
+ }
+ })
+ }
+}
+
+// Go-only: before the action the agent must report this transaction's
+// move finished ok; a move it reports running or failed voids the drain.
+func TestDepartPreActionNeedsTheFinishedMove(t *testing.T) {
+ for _, result := range []string{"running", "failed"} {
+ t.Run(result, func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.afterDrain = func() { h.f.held.drainState["result"] = result }
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ h.mustDrainReasons(heldTx, Text("drain_void"))
+ })
+ }
+}
+
+// test_restart_after_last_check_is_fenced_and_stopped: the provider call
+// is delayed by 30 s and the agent restarts after the tool's final check;
+// its tenant start is refused by the fence, which is still this
+// transaction's when the provider acts.
+func TestDepartRestartAfterLastCheckIsFencedAndStopped(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ var finalCheck int64 = -1
+ h.afterEvent = func(kind string, row Row) {
+ if kind == "edge-stopped" {
+ finalCheck = rowSeq(row)
+ }
+ }
+ var start *bool
+ fence := ""
+ h.f.before = func(op string, _ map[string]any) error {
+ if op == "terminate" && start == nil {
+ h.f.sleep(30 * time.Second)
+ h.f.restartAgent()
+ s := h.f.held.tenantStart()
+ start, fence = &s, h.f.held.fence
+ }
+ return nil
+ }
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if finalCheck < 0 || start == nil || *start || fence != heldTx || h.f.states[fakeIID] != "Terminated" {
+ t.Fatalf("final check %d start %v fence %q state %s", finalCheck, start, fence, h.f.states[fakeIID])
+ }
+ h.mustH4()
+}
+
+// test_entering_standby_is_waited_for.
+func TestDepartEnteringStandbyIsWaitedFor(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.enteringPolls = 3
+ h.f.after = func(name string) {
+ if name == "enter" {
+ // Entry is asynchronous: still registered while it settles.
+ h.f.states[fakeIID], h.f.tg[fakeIID] = "EnteringStandby", "draining"
+ }
+ }
+ var polls []string
+ h.f.wrap = func(op string, _ map[string]any, result any, err error) (any, error) {
+ if op == "group" && err == nil {
+ polls = append(polls, result.(GroupView).Members[fakeIID].Raw)
+ }
+ return result, err
+ }
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if countOf(polls, "EnteringStandby") == 0 || h.f.states[fakeIID] != "Terminated" {
+ t.Fatalf("polls %v state %s", polls, h.f.states[fakeIID])
+ }
+ // Nothing ran against the member before the settled Standby state.
+ if want := []string{"minimum", "enter", "drain", "edge-stop", "terminate", "desired", "minimum"}; !reflect.DeepEqual(h.verbs(), want) {
+ t.Fatalf("verbs %v", h.verbs())
+ }
+}
+
+// cutTerminateRows is cut_terminate_rows: the process dies writing the
+// terminate's error row, so the journal keeps only its intent.
+func cutTerminateRows(h *harness) {
+ h.beforeEvent = func(kind string, data map[string]any) {
+ if kind == "error" && data["op"] == "terminate" {
+ panic(fakeDeath{"cut"})
+ }
+ }
+}
+
+func mustUnanswered(t *testing.T, h *harness) {
+ t.Helper()
+ j := h.txJournal(heldTx)
+ if _, ok := j.Last("intent", map[string]any{"op": "terminate"}); !ok {
+ t.Fatal("no terminate intent")
+ }
+ for _, k := range []string{"error", "response"} {
+ if _, ok := j.Last(k, map[string]any{"op": "terminate"}); ok {
+ t.Fatalf("a terminate %s row", k)
+ }
+ }
+}
+
+// test_hard_cut_after_terminate_intent_resumes: the process dies after
+// the durable terminate intent and before any error or response row.
+func TestDepartHardCutAfterTerminateIntentResumes(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.fault, h.f.faultAt, h.f.failBefore = "death", 5, true
+ cutTerminateRows(h)
+ if !expectDeath(t, func() { h.depart("replace", heldTx) }) {
+ t.Fatal("no death")
+ }
+ mustUnanswered(t, h)
+ if h.f.states[fakeIID] != "Standby" {
+ t.Fatalf("state %s", h.f.states[fakeIID])
+ }
+ h.beforeEvent = nil
+ if err := h.resume(); err != nil {
+ t.Fatal(err)
+ }
+ f := h.f
+ if countOf(f.writes, "terminate") != 1 || f.states[fakeIID] != "Terminated" || f.minimum != 2 || f.desired != 2 ||
+ h.activeTx() != "" {
+ t.Fatalf("writes %v state %s shape %d %d", f.writes, f.states[fakeIID], f.minimum, f.desired)
+ }
+ h.mustH4()
+}
+
+// test_sent_terminate_is_not_repeated: a cut after the provider received
+// the terminate, before any row: the member still reads Standby for a
+// while, but the provider's activity shows the terminate, so resume waits
+// instead of resending.
+func TestDepartSentTerminateIsNotRepeated(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.fault, h.f.faultAt = "death", 5
+ cutTerminateRows(h)
+ if !expectDeath(t, func() { h.depart("replace", heldTx) }) {
+ t.Fatal("no death")
+ }
+ f := h.f
+ if countOf(f.writes, "terminate") != 1 {
+ t.Fatalf("writes %v", f.writes)
+ }
+ f.states[fakeIID] = "Standby"
+ f.held.terminatedAt = time.Time{}
+ f.activity = append(f.activity, Activity{ID: "terminate-1", Kind: "terminate", Status: "InProgress",
+ Time: f.now.UnixMilli()})
+ f.held.settles = append(f.held.settles, termSettle{at: f.now.Add(20 * time.Second)})
+ h.beforeEvent = nil
+ if err := h.resume(); err != nil {
+ t.Fatal(err)
+ }
+ if countOf(f.writes, "terminate") != 1 || f.states[fakeIID] != "Terminated" || h.activeTx() != "" {
+ t.Fatalf("writes %v state %s", f.writes, f.states[fakeIID])
+ }
+}
+
+// test_failed_or_cancelled_activity_after_unanswered_intent_is_retried.
+func TestDepartFailedOrCancelledActivityAfterUnansweredIntentIsRetried(t *testing.T) {
+ for _, status := range []string{"Failed", "Cancelled"} {
+ t.Run(status, func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.outcomes = []termOutcome{{status: status}}
+ h.f.fault, h.f.faultAt = "death", 5
+ cutTerminateRows(h)
+ if !expectDeath(t, func() { h.depart("replace", heldTx) }) {
+ t.Fatal("no death")
+ }
+ mustUnanswered(t, h)
+ if h.f.states[fakeIID] != "Standby" {
+ t.Fatalf("state %s", h.f.states[fakeIID])
+ }
+ h.beforeEvent = nil
+ start := len(h.f.calls)
+ if err := h.resume(); err != nil {
+ t.Fatal(err)
+ }
+ f := h.f
+ if f.states[fakeIID] != "Terminated" || countOf(f.writes, "terminate") != 2 {
+ t.Fatalf("state %s writes %v", f.states[fakeIID], f.writes)
+ }
+ // The retry re-ran the stop proof, the fence read and the lock
+ // sweep before the provider call.
+ var after []string
+ for _, c := range f.calls[start:] {
+ name := c.Op
+ if c.Op == "session" {
+ name = "session:" + c.Args["verb"].(string)
+ }
+ after = append(after, name)
+ }
+ second := indexOf(after, "terminate", 0)
+ stop := indexOf(after, "session:edge-stop", 0)
+ if stop < 0 || stop > second || indexOf(after, "session:status", stop) > second ||
+ indexOf(after, "session:status", stop) < 0 || indexOf(after, "lock_hosts", stop) > second ||
+ indexOf(after, "lock_hosts", stop) < 0 {
+ t.Fatalf("calls after resume %v", after)
+ }
+ if f.minimum != 2 || f.desired != 2 {
+ t.Fatalf("shape %d %d", f.minimum, f.desired)
+ }
+ row, _ := h.txJournal(heldTx).Last("terminate-decision", map[string]any{"action": "retry"})
+ facts, _ := row["facts"].(map[string]any)
+ acts, _ := facts["activities"].([]any)
+ if len(acts) == 0 || acts[len(acts)-1].(map[string]any)["status"] != status {
+ t.Fatalf("retry decision %v", row)
+ }
+ h.mustH4()
+ })
+ }
+}
+
+func indexOf(xs []string, x string, from int) int {
+ for i := from; i < len(xs); i++ {
+ if xs[i] == x {
+ return i
+ }
+ }
+ return -1
+}
+
+// test_quick_failure_then_accepted_retry_is_not_resent: the first attempt
+// fails at once; the retry, inside the 5 s skew allowance, is accepted but
+// its activity is not listed for 20 s. The old Failed activity must not
+// resend or stop it.
+func TestDepartQuickFailureThenAcceptedRetryIsNotResent(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.outcomes = []termOutcome{{status: "Failed"}, {lagging: true}}
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if countOf(h.f.writes, "terminate") != 2 || h.f.states[fakeIID] != "Terminated" {
+ t.Fatalf("writes %v state %s", h.f.writes, h.f.states[fakeIID])
+ }
+ j := h.txJournal(heldTx)
+ var intents []Row
+ for _, r := range rowsOf(j, "intent") {
+ if r["op"] == "terminate" {
+ intents = append(intents, r)
+ }
+ }
+ if len(intents) != 2 || rowAtMS(intents[1])-rowAtMS(intents[0]) >= 5000 {
+ t.Fatalf("intents %v", intents)
+ }
+ var waits []map[string]any
+ for _, r := range rowsOf(j, "terminate-decision") {
+ if r["action"] == "wait" {
+ waits = append(waits, r["facts"].(map[string]any))
+ }
+ }
+ if len(waits) == 0 || waits[0]["activity_id"] != "terminate-lagging" {
+ t.Fatalf("waits %v", waits)
+ }
+ // The first attempt's Failed activity is known as a previous one.
+ retry, _ := j.Last("terminate-decision", map[string]any{"action": "retry"})
+ acts := retry["facts"].(map[string]any)["activities"].([]any)
+ failed := acts[len(acts)-1].(map[string]any)
+ if failed["status"] != "Failed" || !containsValue(waits[0]["previous_ids"], failed["id"].(string)) {
+ t.Fatalf("failed %v previous %v", failed, waits[0]["previous_ids"])
+ }
+ resp, _ := j.Last("response", map[string]any{"op": "terminate"})
+ if resp["result"].(map[string]any)["activity"] != "terminate-lagging" {
+ t.Fatalf("response %v", resp)
+ }
+ h.mustH4()
+}
+
+// test_persistent_failure_is_an_explicit_recoverable_fail.
+func TestDepartPersistentFailureIsAnExplicitRecoverableFail(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ for i := 0; i < 1+TerminateRetries; i++ {
+ h.f.held.outcomes = append(h.f.held.outcomes, termOutcome{status: "Failed"})
+ }
+ refusedWith(t, h.depart("replace", heldTx), "terminate_failed")
+ f := h.f
+ if countOf(f.writes, "terminate") != 1+TerminateRetries || f.states[fakeIID] != "Standby" ||
+ h.activeTx() != heldTx || !f.now.Before(fakeStart.Add(standbyWait)) {
+ t.Fatalf("writes %v state %s now %v", f.writes, f.states[fakeIID], f.now)
+ }
+ // The provider is fixed: resume decides afresh and completes.
+ if err := h.resume(); err != nil {
+ t.Fatal(err)
+ }
+ if f.states[fakeIID] != "Terminated" || f.minimum != 2 || f.desired != 2 || h.activeTx() != "" {
+ t.Fatalf("state %s shape %d %d", f.states[fakeIID], f.minimum, f.desired)
+ }
+}
+
+// test_provider_changing_desired_on_terminate_fails: the provider check
+// behind H4 is a failed probe, which blocks further rolls.
+func TestDepartProviderChangingDesiredOnTerminateFails(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.after = func(name string) {
+ if name == "terminate" {
+ h.f.desired++
+ }
+ }
+ if err := h.depart("replace", heldTx); !isStop(err, "failed-probe") {
+ t.Fatalf("depart = %v", err)
+ }
+ if !blockedFlag(h) || countOf(h.verbs(), "desired") != 0 {
+ t.Fatalf("blocked %v verbs %v", blockedFlag(h), h.verbs())
+ }
+}
+
+// CancelDrainTests.
+
+func failedDrain(t *testing.T) *harness {
+ t.Helper()
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "fail"
+ if err := h.depart("replace", heldTx); !isRefusal(err) {
+ t.Fatalf("depart = %v", err)
+ }
+ if h.f.held.fence != heldTx {
+ t.Fatalf("fence %q", h.f.held.fence)
+ }
+ return h
+}
+
+// test_cancel_lifts_fence_after_failed_drain.
+func TestCancelDrainLiftsFenceAfterFailedDrain(t *testing.T) {
+ h := failedDrain(t)
+ if err := h.cancelDrain(fakeIID, heldTx); err != nil {
+ t.Fatal(err)
+ }
+ if h.f.held.fence != "" || !h.f.held.tenantStart() || !strings.Contains(h.out.String(), Text("cancelled")) {
+ t.Fatalf("fence %q output %s", h.f.held.fence, h.out.String())
+ }
+ j := h.txJournal(heldTx)
+ if _, ok := j.Last("drain-cancelled", nil); !ok {
+ t.Fatal("no drain-cancelled row")
+ }
+ intent, _ := j.Last("intent", map[string]any{"op": "session"})
+ if !sameValue(intent["args"], map[string]any{"iid": fakeIID, "verb": "drain-cancel", "transaction": heldTx}) {
+ t.Fatalf("intent %v", intent)
+ }
+ if h.activeTx() != "" {
+ t.Fatal("cancel-drain opened a transaction")
+ }
+}
+
+// test_refused_cancel_keeps_fence.
+func TestCancelDrainRefusedKeepsFence(t *testing.T) {
+ h := failedDrain(t)
+ h.f.held.cancel = "refused"
+ err := h.cancelDrain(fakeIID, heldTx)
+ refusedWith(t, err, "cancel_failed")
+ if !strings.Contains(err.Error(), "the fence stays") || h.f.held.fence != heldTx {
+ t.Fatalf("err %v fence %q", err, h.f.held.fence)
+ }
+ if _, ok := h.txJournal(heldTx).Last("drain-cancel-failed", nil); !ok {
+ t.Fatal("no drain-cancel-failed row")
+ }
+}
+
+// test_cancel_proven_by_status: the verb exits 0 but status still shows
+// the fence: not cancelled.
+func TestCancelDrainProvenByStatus(t *testing.T) {
+ h := failedDrain(t)
+ h.f.held.cancel = "status-disagrees"
+ refusedWith(t, h.cancelDrain(fakeIID, heldTx), "cancel_failed")
+ if strings.Contains(h.out.String(), Text("cancelled")) {
+ t.Fatal("said cancelled")
+ }
+ if _, ok := h.txJournal(heldTx).Last("drain-cancelled", nil); ok {
+ t.Fatal("a drain-cancelled row")
+ }
+}
+
+// test_cancel_only_for_a_failed_drain_of_this_member.
+func TestCancelDrainOnlyForAFailedDrainOfThisMember(t *testing.T) {
+ h := failedDrain(t)
+ refusedWith(t, h.cancelDrain(fakePeer, heldTx), "cancel_refused")
+ if err := h.cancelDrain(fakeIID, "missing"); err == nil {
+ t.Fatal("cancel-drain of a missing journal")
+ }
+ for _, tx := range []string{"-x", "a b", ""} {
+ refusedWith(t, h.cancelDrain(fakeIID, tx), "record")
+ }
+ h = newHeldHarness(t, 2, nil)
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ refusedWith(t, h.cancelDrain(fakeIID, heldTx), "cancel_refused")
+ if countOf(h.verbs(), "drain-cancel") != 0 {
+ t.Fatal("drain-cancel sent")
+ }
+}
+
+// The departure halves of FloorTests: a floor below the rule closes the
+// transaction floor-refused before any write; one that cannot be read
+// refuses with no rule and leaves the transaction for resume or abandon.
+
+func mustFloorRefused(t *testing.T, h *harness, reason string) {
+ t.Helper()
+ refusedWith(t, h.depart("replace", heldTx), "floor_refused")
+ if len(h.verbs()) != 0 || h.activeTx() != "" {
+ t.Fatalf("verbs %v active %q", h.verbs(), h.activeTx())
+ }
+ out := h.out.String()
+ if !strings.Contains(out, Text("rule_dr4")) || !strings.Contains(out, reason) {
+ t.Fatalf("output %s lacks the rule or %q", out, reason)
+ }
+ j := h.txJournal(heldTx)
+ done, _ := j.Last("done", nil)
+ floor, _ := j.Last("floor", nil)
+ if done["outcome"] != "floor-refused" || floor["rule"] != "dr4" {
+ t.Fatalf("done %v floor %v", done, floor)
+ }
+}
+
+func TestDepartFloorRefused(t *testing.T) {
+ t.Run("member without ha_take", func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.haTake[ref(fakePeer)] = nil
+ mustFloorRefused(t, h, Text("floor_box", "box", ref(fakePeer)))
+ })
+ t.Run("member with other ha_take", func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.haTake[ref(fakeIID)] = int64(2)
+ mustFloorRefused(t, h, Text("floor_box", "box", ref(fakeIID)))
+ })
+ t.Run("fixed forwarder without ha_take", func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.fixed["adi"] = fixedEdges{age: 5 * time.Second}
+ mustFloorRefused(t, h, Text("floor_box", "box", "adi"))
+ })
+ t.Run("old pinned template", func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.templateRelease = "v0.34.9"
+ mustFloorRefused(t, h, Text("floor_template", "release", "v0.34.9"))
+ })
+ for _, key := range []string{"ha_floor", "data_prefix", "data_bucket"} {
+ t.Run("no "+key, func(t *testing.T) {
+ h := newHeldHarness(t, 2, func(c *Config) {
+ switch key {
+ case "ha_floor":
+ c.HAFloor = nil
+ case "data_prefix":
+ c.DataPrefix = nil
+ default:
+ c.DataBucket = nil
+ }
+ })
+ mustFloorRefused(t, h, Text("floor_config"))
+ })
+ }
+}
+
+// assert_floor_error at the departure: unreadable edges files and an
+// uncomparable template refuse before any write and record no rule.
+func TestDepartFloorErrorRefusesWithoutDR4(t *testing.T) {
+ cases := map[string]struct {
+ setup func(h *harness)
+ reason string
+ }{
+ "uncomparable template": {func(h *harness) { h.f.templateRelease = "v0.35.0-rc1" },
+ Text("floor_template", "release", "v0.35.0-rc1")},
+ "unreadable edges file": {func(h *harness) {
+ h.f.wrap = func(op string, args map[string]any, result any, err error) (any, error) {
+ if op == "edges" && args["box_ref"] == "adi" {
+ return nil, Uncertain{Key: "api"}
+ }
+ return result, err
+ }
+ }, Text("floor_unreadable", "key", "control/edges/adi.json")},
+ }
+ for name, c := range cases {
+ t.Run(name, func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ c.setup(h)
+ refusedWith(t, h.depart("replace", heldTx), "floor_error")
+ if len(h.verbs()) != 0 || strings.Contains(h.out.String(), Text("rule_dr4")) ||
+ !strings.Contains(h.out.String(), c.reason) {
+ t.Fatalf("verbs %v output %s", h.verbs(), h.out.String())
+ }
+ j := h.txJournal(heldTx)
+ if _, ok := j.Last("floor", nil); ok {
+ t.Fatal("a floor row")
+ }
+ if _, ok := j.Last("floor-error", nil); !ok {
+ t.Fatal("no floor-error row")
+ }
+ // The transaction stays open; nothing was written, so abandon closes it.
+ if h.activeTx() != heldTx {
+ t.Fatalf("active %q", h.activeTx())
+ }
+ if err := h.locked(func(e *Engine) error { return e.Abandon(bg, heldTx) }); err != nil {
+ t.Fatalf("abandon: %v", err)
+ }
+ })
+ }
+}
+
+// test_stale_box_is_not_live, through a whole replace.
+func TestDepartStaleBoxIsNotLive(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.fixed["old"] = fixedEdges{age: 16 * time.Minute}
+ if err := h.depart("replace", heldTx); err != nil {
+ t.Fatal(err)
+ }
+ floor, _ := h.txJournal(heldTx).Last("floor", nil)
+ if h.f.states[fakeIID] != "Terminated" || containsValue(floor["live"], "old") {
+ t.Fatalf("state %s floor %v", h.f.states[fakeIID], floor)
+ }
+}
+
+// RemoveTests and RemoveMinimumTests.
+
+func removeHarness(t *testing.T, pools map[string]any) *harness {
+ h := newHeldHarness(t, 3, nil)
+ h.f.held.pools = pools
+ return h
+}
+
+// test_remove_leaves_n_minus_one_and_names_box_count.
+func TestDepartRemoveLeavesNMinusOneAndNamesBoxCount(t *testing.T) {
+ third := ref(fmt.Sprintf("i-%017x", 2))
+ h := removeHarness(t, map[string]any{ref(fakeIID): []any{"shop"}, ref(fakePeer): []any{"shop"}, third: []any{"blog"}})
+ if err := h.depart("remove", heldTx); err != nil {
+ t.Fatalf("%v\n%s", err, h.out.String())
+ }
+ f := h.f
+ if want := []string{"minimum", "enter", "drain", "edge-stop", "terminate"}; !reflect.DeepEqual(h.verbs(), want) {
+ t.Fatalf("verbs %v", h.verbs())
+ }
+ if f.minimum != 2 || f.desired != 2 || f.maximum != 3 || f.states[fakeIID] != "Terminated" {
+ t.Fatalf("shape %d %d %d state %s", f.minimum, f.desired, f.maximum, f.states[fakeIID])
+ }
+ if _, ok := f.states[replacementIID]; ok {
+ t.Fatal("a replacement launched")
+ }
+ h.mustH4()
+ if !strings.Contains(h.out.String(), Text("removed", "n", "2")) {
+ t.Fatalf("output %s", h.out.String())
+ }
+ if done, _ := h.txJournal(heldTx).Last("done", nil); done["outcome"] != "removed" {
+ t.Fatalf("done %v", done)
+ }
+}
+
+func mustPreflightRefused(t *testing.T, h *harness, err error, key string) {
+ t.Helper()
+ refusedWith(t, err, key)
+ if len(h.verbs()) != 0 {
+ t.Fatalf("verbs %v", h.verbs())
+ }
+ if done, _ := h.txJournal(heldTx).Last("done", nil); done["outcome"] != "preflight-refused" {
+ t.Fatalf("done %v", done)
+ }
+}
+
+// test_remove_refuses_an_unserved_pool.
+func TestDepartRemoveRefusesAnUnservedPool(t *testing.T) {
+ third := ref(fmt.Sprintf("i-%017x", 2))
+ h := removeHarness(t, map[string]any{ref(fakeIID): []any{"shop", "blog"}, ref(fakePeer): []any{"shop"}, third: nil})
+ err := h.depart("remove", heldTx)
+ mustPreflightRefused(t, h, err, "remove_pools")
+ if err.Error() != Text("remove_pools", "pool", "blog") {
+ t.Fatalf("err %v", err)
+ }
+}
+
+// test_remove_refuses_unknown_member_pools.
+func TestDepartRemoveRefusesUnknownMemberPools(t *testing.T) {
+ h := removeHarness(t, map[string]any{ref(fakeIID): "shop"})
+ mustPreflightRefused(t, h, h.depart("remove", heldTx), "remove_pools_unknown")
+}
+
+// test_remove_needs_two_survivors.
+func TestDepartRemoveNeedsTwoSurvivors(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ mustPreflightRefused(t, h, h.depart("remove", heldTx), "remove_minimum")
+}
+
+// Go-only: the begin row names the kind and the caller; a chosen
+// transaction must be one the box verbs take and unused; the kind must be
+// replace or remove.
+func TestDepartBeginRowAndArguments(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ refusedWith(t, h.depart("roll", heldTx), "unsupported")
+ for _, tx := range []string{"-x", "probe-x", "a b", strings.Repeat("x", 81)} {
+ refusedWith(t, h.depart("replace", tx), "record")
+ }
+ if len(h.f.calls) != 0 {
+ t.Fatalf("calls %v", h.f.ops())
+ }
+ if err := h.depart("replace", ""); err != nil {
+ t.Fatal(err)
+ }
+ tx := h.onlyTx()
+ if !regexpHex32(tx) {
+ t.Fatalf("generated transaction %q", tx)
+ }
+ begin := h.txJournal(tx).Rows()[0]
+ if !sameValue(begin["header"], map[string]any{"kind": "replace"}) || begin["caller_user_id"] != h.f.userID {
+ t.Fatalf("begin %v", begin)
+ }
+ // A finished transaction's id is taken.
+ refusedWith(t, h.depart("replace", tx), "record")
+}
+
+func regexpHex32(s string) bool {
+ if len(s) != 32 {
+ return false
+ }
+ for _, c := range s {
+ if !strings.ContainsRune("0123456789abcdef", c) {
+ return false
+ }
+ }
+ return true
+}
+
+// Review Focus 3: another account's transaction has a member parked
+// (min != max): replace refuses on shape before any write.
+func TestDepartRefusesForeignTransactionShape(t *testing.T) {
+ h := newHeldHarness(t, 3, nil)
+ other := h.f.order[2]
+ h.f.minimum, h.f.desired = 2, 2
+ h.f.states[other], h.f.tg[other] = "Standby", "unused"
+ mustPreflightRefused(t, h, h.depart("replace", heldTx), "shape")
+ if len(h.f.writes) != 0 || h.activeTx() != "" {
+ t.Fatalf("writes %v active %q", h.f.writes, h.activeTx())
+ }
+}
+
+// DrainedRollTests: the roll drains when the floor holds.
+
+func (h *harness) heldRoll() error { return h.runRollTx("t6-roll") }
+
+// test_roll_drains_before_apply_and_lifts_fence_after_exit.
+func TestDrainedRollDrainsBeforeApplyAndLiftsFenceAfterExit(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ var applyFence string
+ var clearSeen []any
+ h.f.before = func(op string, args map[string]any) error {
+ if op == "session" && args["verb"] == "fence-clear" {
+ clearSeen = []any{h.f.states[fakeIID], h.f.minimum, h.f.desired}
+ }
+ if op == "session" && args["verb"] == "apply" {
+ applyFence = h.f.held.fence
+ }
+ return nil
+ }
+ if err := h.heldRoll(); err != nil {
+ t.Fatalf("%v\n%s", err, h.out.String())
+ }
+ f := h.f
+ want := []string{"prepare", "minimum", "enter", "drain", "permit", "apply", "exit", "fence-clear", "minimum", "revoke"}
+ if !reflect.DeepEqual(f.writes, want) {
+ t.Fatalf("writes %v", f.writes)
+ }
+ // apply restarted the edge behind the fence; the fence is lifted only
+ // after ExitStandby, and before minimum is restored.
+ if applyFence != "t6-roll" || !reflect.DeepEqual(clearSeen, []any{"InService", 1, 2}) || f.held.fence != "" {
+ t.Fatalf("apply fence %q fence-clear seen %v fence %q", applyFence, clearSeen, f.held.fence)
+ }
+ if f.minimum != 2 || f.desired != 2 || f.boxes[fakeIID]["binary_sha256"] != newSHA || h.activeTx() != "" {
+ t.Fatalf("shape %d %d binary %v", f.minimum, f.desired, f.boxes[fakeIID]["binary_sha256"])
+ }
+ var line string
+ for _, l := range strings.Split(h.out.String(), "\n") {
+ if strings.HasPrefix(l, "{") {
+ line = l
+ break
+ }
+ }
+ var summary map[string]any
+ if err := json.Unmarshal([]byte(line), &summary); err != nil {
+ t.Fatalf("summary %q: %v", line, err)
+ }
+ wantSummary := map[string]any{"transaction": "t6-roll", "transaction_kind": "roll", "member": fakeIID,
+ "hosts_moved": 1.0, "hosts_released": 0.0, "longest_hold_ms": 1500.0, "todays_answer": 0.0,
+ "connections_closed_at_bound": 0.0}
+ if !reflect.DeepEqual(summary, wantSummary) {
+ t.Fatalf("summary %v", summary)
+ }
+ if !strings.Contains(line, `"hosts_moved": 1, `) {
+ t.Fatalf("summary is not Python's json.dumps: %s", line)
+ }
+ j := h.txJournal("t6-roll")
+ report, _ := j.Last("report", nil)
+ floor, _ := j.Last("floor", nil)
+ checked, _ := j.Last("pre-action-checked", nil)
+ apply, _ := j.Last("intent", map[string]any{"op": "session", "args": map[string]any{"iid": fakeIID, "verb": "apply"}})
+ if !sameValue(report["hosts_moved"], 1) || floor["rule"] != "drain" || apply == nil || rowSeq(checked) >= rowSeq(apply) {
+ t.Fatalf("report %v floor %v checked %v apply %v", report, floor, checked, apply)
+ }
+ h.mustH4()
+}
+
+// test_roll_failed_drain_returns_unchanged.
+func TestDrainedRollFailedDrainReturnsUnchanged(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.drainMode = "fail"
+ refusedWith(t, h.heldRoll(), "drain_failed")
+ if want := []string{"prepare", "minimum", "enter", "drain", "exit", "minimum"}; !reflect.DeepEqual(h.f.writes, want) {
+ t.Fatalf("writes %v", h.f.writes)
+ }
+ if h.f.boxes[fakeIID]["binary_sha256"] != oldSHA {
+ t.Fatal("the artifact changed")
+ }
+ h.mustReturned("t6-roll")
+}
+
+// test_roll_lock_after_permit_returns_and_revokes.
+func TestDrainedRollLockAfterPermitReturnsAndRevokes(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.held.locks["blog"] = heldLock(ref(fakeIID), fakeIID)
+ if err := h.heldRoll(); !isRefusal(err) {
+ t.Fatalf("roll = %v", err)
+ }
+ want := []string{"prepare", "minimum", "enter", "drain", "permit", "exit", "minimum", "revoke"}
+ if !reflect.DeepEqual(h.f.writes, want) {
+ t.Fatalf("writes %v", h.f.writes)
+ }
+ if h.f.boxes[fakeIID]["binary_sha256"] != oldSHA {
+ t.Fatal("the artifact changed")
+ }
+ h.mustReturned("t6-roll")
+}
+
+// test_roll_below_floor_uses_dr4_and_says_so.
+func TestDrainedRollBelowFloorUsesDR4AndSaysSo(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.haTake[ref(fakePeer)] = nil
+ if err := h.heldRoll(); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(h.f.writes, rollOrder) {
+ t.Fatalf("writes %v", h.f.writes)
+ }
+ out := h.out.String()
+ if !strings.Contains(out, Text("rule_dr4")) || !strings.Contains(out, Text("floor_box", "box", ref(fakePeer))) {
+ t.Fatalf("output %s", out)
+ }
+}
+
+// test_roll_to_release_below_floor_uses_dr4.
+func TestDrainedRollToReleaseBelowFloorUsesDR4(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.version = "v0.34.0"
+ if err := h.heldRoll(); err != nil {
+ t.Fatal(err)
+ }
+ if countOf(h.f.writes, "drain") != 0 || !strings.Contains(h.out.String(), Text("floor_version", "release", "v0.34.0")) {
+ t.Fatalf("writes %v output %s", h.f.writes, h.out.String())
+ }
+}
+
+// test_drained_roll_resumes_after_every_write.
+func TestDrainedRollResumesAfterEveryWrite(t *testing.T) {
+ for boundary := 1; boundary <= 10; boundary++ {
+ t.Run(fmt.Sprint(boundary), func(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ h.f.fault, h.f.faultAt = "death", boundary
+ if !expectDeath(t, func() { h.heldRoll() }) {
+ t.Fatal("no death")
+ }
+ if err := h.resume(); err != nil {
+ t.Fatalf("resume: %v\n%s", err, h.out.String())
+ }
+ f := h.f
+ if f.minimum != 2 || f.desired != 2 || f.states[fakeIID] != "InService" || f.held.fence != "" ||
+ h.activeTx() != "" {
+ t.Fatalf("shape %d %d state %s fence %q active %q", f.minimum, f.desired, f.states[fakeIID],
+ f.held.fence, h.activeTx())
+ }
+ h.mustH4()
+ })
+ }
+}
+
+// test_listing_error_refuses_roll_without_dr4: once the store answers,
+// resume chooses the rule and drains.
+func TestDrainedRollListingErrorRefusesWithoutDR4(t *testing.T) {
+ h := newHeldHarness(t, 2, nil)
+ failing := func(op string, _ map[string]any, result any, err error) (any, error) {
+ if op == "edges_list" {
+ return nil, Uncertain{Key: "api"}
+ }
+ return result, err
+ }
+ h.f.wrap = failing
+ if err := h.heldRoll(); err == nil {
+ t.Fatal("roll passed an unreadable floor")
+ }
+ if !reflect.DeepEqual(h.f.writes, []string{"prepare"}) || strings.Contains(h.out.String(), Text("rule_dr4")) ||
+ h.activeTx() != "t6-roll" {
+ t.Fatalf("writes %v active %q", h.f.writes, h.activeTx())
+ }
+ if _, ok := h.txJournal("t6-roll").Last("floor", nil); ok {
+ t.Fatal("a floor row")
+ }
+ h.f.wrap = nil
+ if err := h.resume(); err != nil {
+ t.Fatal(err)
+ }
+ if countOf(h.f.writes, "drain") == 0 || h.activeTx() != "" {
+ t.Fatalf("writes %v", h.f.writes)
+ }
+}
+
+// The drain summary is Python's json.dumps(sort_keys=True): ", " and ": "
+// separators, None as null.
+func TestDrainSummaryLine(t *testing.T) {
+ got, err := pythonDumps(map[string]any{"b": nil, "a": []any{int64(1), "x"}, "c": json.Number("1.5")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := `{"a": [1, "x"], "b": null, "c": 1.5}`; got != want {
+ t.Fatalf("got %s, want %s", got, want)
+ }
+ if _, err := pythonDumps(map[string]any{"x": math.Inf(1)}); err == nil {
+ t.Fatal("encoded an infinite number")
+ }
+}
diff --git a/internal/grouproll/fake_test.go b/internal/grouproll/fake_test.go
index 4f901bb27..76f97cc40 100644
--- a/internal/grouproll/fake_test.go
+++ b/internal/grouproll/fake_test.go
@@ -131,6 +131,10 @@ type fake struct {
haTake map[string]any
fixed map[string]fixedEdges
pointers map[string][]byte
+
+ // held is the planned handovers' provider and agent (the held
+ // branch's HeldFake); nil keeps the roll fake as it was.
+ held *heldFake
}
// fixedEdges is a box outside the group: its ha_take (nil: none) and how
@@ -256,6 +260,9 @@ func (f *fake) sleep(d time.Duration) {
f.tg[replacement] = "initial"
f.deadline = time.Time{}
}
+ if f.held != nil {
+ f.heldSleep()
+ }
}
func copyArgs(args map[string]any) map[string]any {
@@ -526,6 +533,10 @@ func (f *fake) SetMinimum(ctx context.Context, n int) (WriteResult, error) {
func (f *fake) RaiseDesired(ctx context.Context, n int) (WriteResult, error) {
r, err := f.request("desired", map[string]any{"value": n}, func() (any, error) {
+ // The adapter's own H4 guard: this call only raises desired.
+ if n < f.desired || n > f.maximum {
+ return nil, Refusal{Key: "h4"}
+ }
f.desired = n
return WriteResult{Response: map[string]any{}}, nil
})
@@ -580,13 +591,17 @@ func (f *fake) Unpark(ctx context.Context, iid string) (WriteResult, error) {
return r.(WriteResult), nil
}
-// Terminate removes a parked member without decrement. Task 10's depart
-// tests extend it (activities, settle and replacement launches).
+// Terminate removes a parked member without decrement. With held set it
+// is HeldFake's: queued outcomes first, then a terminate the group shows
+// at once, whose departure and replacement follow in sleep.
func (f *fake) Terminate(ctx context.Context, iid string) (WriteResult, error) {
r, err := f.request("terminate", map[string]any{"iid": iid, "decrement": false}, func() (any, error) {
if f.states[iid] != "Standby" || f.desired != f.minimum {
return nil, Refusal{Key: "h4"}
}
+ if f.held != nil {
+ return f.heldTerminate(iid), nil
+ }
id := fmt.Sprintf("terminate-%d", len(f.activity))
f.activity = append(f.activity, Activity{ID: id, Kind: "terminate", Status: "Successful", Time: f.now.UnixMilli()})
f.states[iid] = "Terminated"
@@ -670,6 +685,11 @@ func (f *fake) session(iid, verb string, a BoxArgs) (any, error) {
if !ok {
return nil, Refusal{Key: "remote"}
}
+ if f.held != nil {
+ if r, err, ok := f.heldSession(iid, verb, a); ok {
+ return r, err
+ }
+ }
switch verb {
case "status":
p := s["permit"].(map[string]any)
@@ -729,6 +749,11 @@ func (f *fake) session(iid, verb string, a BoxArgs) (any, error) {
}
e["identity"], e["started_at"] = verb+"-process", stamp(f.now)
f.now = f.now.Add(time.Second)
+ if f.held != nil {
+ // A restarted agent: a new incarnation that is not draining.
+ f.held.incarnation = heldRestarted
+ f.held.drainState = idleDrain(heldRestarted)
+ }
if f.outage {
f.admitted = false
h := s["health"].(map[string]any)
@@ -756,13 +781,20 @@ type fakeStore struct {
// floor must skip.
func (s fakeStore) List(ctx context.Context, prefix string) ([]string, error) {
f := s.f
+ if f.held != nil && s.bucket == f.held.dataBucket {
+ return s.lockList(prefix)
+ }
r, err := f.request("edges_list", map[string]any{"prefix": prefix}, func() (any, error) {
if s.bucket != f.c.Bucket || prefix != "control/edges/" {
return nil, Uncertain{Key: "api"}
}
var keys []string
for _, iid := range sortedKeys(f.boxes) {
- keys = append(keys, "control/edges/"+f.boxes[iid]["box_ref"].(string)+".json")
+ ref := f.boxes[iid]["box_ref"].(string)
+ if f.held != nil && f.held.departed[ref] {
+ continue
+ }
+ keys = append(keys, "control/edges/"+ref+".json")
}
for _, ref := range sortedKeys(f.fixed) {
keys = append(keys, "control/edges/"+ref+".json")
@@ -777,6 +809,9 @@ func (s fakeStore) List(ctx context.Context, prefix string) ([]string, error) {
func (s fakeStore) Get(ctx context.Context, key string) ([]byte, string, error) {
f := s.f
+ if f.held != nil && s.bucket == f.held.dataBucket {
+ return s.lockGet(key)
+ }
if channel, ok := strings.CutPrefix(key, "control/system/router/"); ok {
channel = strings.TrimSuffix(channel, ".json")
r, err := f.request("release_pointer", map[string]any{"channel": channel}, func() (any, error) {
@@ -852,6 +887,14 @@ func (s fakeStore) Get(ctx context.Context, key string) ([]byte, string, error)
e["ha_take"] = take
}
}
+ if f.held != nil {
+ if pools, ok := f.held.pools[ref]; ok {
+ e["served_pools"] = pools
+ }
+ if f.held.edgesBody != nil {
+ f.held.edgesBody(ref, e)
+ }
+ }
return e, nil
})
if err != nil {
@@ -909,8 +952,19 @@ func newHarness(t *testing.T, n int) *harness {
// 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()
+ return newHarnessWith(t, root, n, nil)
+}
+
+// newHarnessWith is newHarnessAt with the config changed by configure
+// before the state opens, so the journals record the config the engine
+// runs with.
+func newHarnessWith(t *testing.T, root string, n int, configure func(c *Config)) *harness {
t.Helper()
f := newFake(t, n)
+ if configure != nil {
+ configure(&f.c)
+ }
h := &harness{t: t, f: f, c: f.c, root: root}
s, err := OpenState(h.root, h.c, false)
if err != nil {
@@ -968,3 +1022,431 @@ func (h *harness) planLog() *Journal {
h.t.Cleanup(func() { j.Close() })
return j
}
+
+// The planned handovers' fake: held-floor-sha-map's HeldFake
+// (scripts/region_group_held_test.py). The member's agent drains, fences
+// and stops its edge; the data bucket holds the region's host locks; a
+// terminate leaves the group after 30 s, its edges file after
+// departureDelay, and a replacement launches when fewer members serve than
+// desired.
+
+const replacementIID = "i-0bbbbbbbbbbbbbbbb"
+
+var (
+ heldIncarnation = strings.Repeat("1", 32)
+ heldRestarted = strings.Repeat("2", 32)
+)
+
+// termOutcome is one queued terminate's provider answer: an activity with
+// status listed at once (none when lagging), which settles after after
+// (0: never) into a group showing the member terminating.
+type termOutcome struct {
+ status string
+ after time.Duration
+ lagging bool
+}
+
+type termSettle struct {
+ at time.Time
+ id string // the activity that turns Successful; "" lists none
+}
+
+type heldFake struct {
+ dataBucket string
+ locks map[string]any // host: its lock.json body; nil is no lock
+ drainMode string // ok, fail, refused, uncertain, remote-timeout, drop-once, drop-running, drop-done
+ drainCalls int
+ afterDrain func()
+ reportEdit func(report map[string]any) // changes the drain's report before it is printed
+ incarnation string
+ drainState map[string]any
+ statusDrain func(map[string]any) map[string]any // what status reports of the drain (nil: the truth)
+ fence string // the fence's transaction; "" when absent
+ edgeStops bool
+ edgeStopAnswer map[string]any // what a refused stop reports (nil: MainPID 4242, active)
+ h4 []string
+ departureDelay time.Duration
+ terminatedAt time.Time
+ departureAt time.Time
+ departed map[string]bool
+ launchDelay time.Duration
+ launchedAt time.Time
+ pools map[string]any // box ref: served_pools (absent: the fixture's)
+ enteringPolls int
+ cancel string // "" succeeds, "refused", or "status-disagrees"
+ starts []bool
+ outcomes []termOutcome
+ settles []termSettle
+ edgesBody func(ref string, body map[string]any)
+}
+
+func idleDrain(incarnation string) map[string]any {
+ return map[string]any{"state": "known", "incarnation": incarnation, "transaction": nil, "step": nil,
+ "result": "none", "error": nil}
+}
+
+func moveDrain(incarnation, tx, result string) map[string]any {
+ return map[string]any{"state": "known", "incarnation": incarnation, "transaction": tx, "step": "move",
+ "result": result, "error": nil}
+}
+
+// heldMarker and heldLock are the Python test's marker and held_lock.
+func heldMarker(box string) map[string]any {
+ return map[string]any{"generation": int64(3), "expires_at": "1970-01-01T00:00:00Z",
+ "owner": "released/v1;ref=" + box,
+ "carlos_release": map[string]any{"box": box, "lifetime": "l1", "clean": true}}
+}
+
+func heldLock(ref, iid string) map[string]any {
+ return map[string]any{"generation": int64(4), "expires_at": "2030-01-01T00:00:00Z",
+ "owner": fmt.Sprintf("box/v1;ref=%s;iid=%s;pid=7;ha=1", ref, iid)}
+}
+
+// newHeldFake is HeldFake.__init__ over f.
+func newHeldFake(f *fake) *heldFake {
+ return &heldFake{
+ dataBucket: "example-bucket",
+ locks: map[string]any{"shop": heldMarker(ref(fakePeer)), "blog": heldLock(ref(fakePeer), fakePeer),
+ "idle": nil},
+ drainMode: "ok", incarnation: heldIncarnation, drainState: idleDrain(heldIncarnation),
+ edgeStops: true, departureDelay: 120 * time.Second, departed: map[string]bool{},
+ launchDelay: 60 * time.Second, pools: map[string]any{},
+ }
+}
+
+// tenantStart is the agent's start gate: refused while a fence is present.
+func (h *heldFake) tenantStart() bool {
+ allowed := h.fence == ""
+ h.starts = append(h.starts, allowed)
+ return allowed
+}
+
+// restartAgent is a restarted edge: a new process and incarnation, not
+// draining.
+func (f *fake) restartAgent() {
+ s := f.boxes[fakeIID]
+ e := s["edge"].(map[string]any)
+ pid, _ := e["pid"].(int64)
+ if pid == 0 {
+ pid = 299
+ }
+ e["state"], e["pid"], e["identity"] = "known", pid+1, fmt.Sprintf("restarted-%d", len(f.held.starts))
+ e["started_at"] = stamp(f.now)
+ s["health"] = map[string]any{"state": "healthy", "code": int64(200), "error": nil}
+ f.held.incarnation = heldRestarted
+ f.held.drainState = idleDrain(heldRestarted)
+}
+
+func (f *fake) addMember(iid, state string) {
+ f.states[iid] = state
+ f.tg[iid] = "initial"
+ if state == "InService" {
+ f.tg[iid] = "healthy"
+ }
+ f.boxes[iid] = f.box(iid)
+ f.published[iid] = f.now.Add(-5 * time.Second)
+ f.order = append(f.order, iid)
+}
+
+// heldTerminating is the provider acting on a received terminate.
+func (f *fake) heldTerminating() {
+ f.states[fakeIID] = "Terminating"
+ delete(f.tg, fakeIID)
+ f.held.terminatedAt = f.now
+ f.held.departureAt = f.now.Add(f.held.departureDelay)
+}
+
+func (f *fake) heldTerminate(iid string) WriteResult {
+ h := f.held
+ if len(h.outcomes) > 0 {
+ o := h.outcomes[0]
+ h.outcomes = h.outcomes[1:]
+ if o.lagging {
+ // Accepted, but the activity and the group lag for 20 s.
+ h.settles = append(h.settles, termSettle{at: f.now.Add(20 * time.Second)})
+ return WriteResult{Activity: "terminate-lagging"}
+ }
+ id := fmt.Sprintf("terminate-%d", len(f.activity))
+ f.activity = append(f.activity, Activity{ID: id, Kind: "terminate", Status: o.status, Time: f.now.UnixMilli()})
+ if o.after > 0 {
+ h.settles = append(h.settles, termSettle{at: f.now.Add(o.after), id: id})
+ }
+ return WriteResult{Activity: id}
+ }
+ f.heldTerminating()
+ return WriteResult{Activity: fmt.Sprintf("terminate-ok-%d", len(f.activity))}
+}
+
+// terminateDecrement is the H4 mutant's terminate: with decrement, which
+// lowers desired, and the provider punishes it by terminating a peer.
+func (f *fake) terminateDecrement(iid string) (WriteResult, error) {
+ r, err := f.request("terminate", map[string]any{"iid": iid, "decrement": true}, func() (any, error) {
+ f.held.h4 = append(f.held.h4, "terminate with decrement")
+ f.states[fakePeer] = "Terminated"
+ delete(f.tg, fakePeer)
+ f.desired--
+ return f.heldTerminate(iid), nil
+ })
+ if err != nil {
+ return WriteResult{}, err
+ }
+ return r.(WriteResult), nil
+}
+
+// settleTerminates is the provider catching up with every terminate it
+// received (the simulation's operator fixing the provider).
+func (f *fake) settleTerminates() {
+ for i := range f.held.settles {
+ f.held.settles[i].at = f.now
+ }
+ f.heldSleep()
+}
+
+func (f *fake) heldSleep() {
+ h := f.held
+ if f.states[fakeIID] == "EnteringStandby" {
+ h.enteringPolls--
+ if h.enteringPolls <= 0 {
+ f.states[fakeIID], f.tg[fakeIID] = "Standby", "unused"
+ }
+ }
+ var later []termSettle
+ for _, st := range h.settles {
+ if f.now.Before(st.at) {
+ later = append(later, st)
+ continue
+ }
+ for i := range f.activity {
+ if st.id != "" && f.activity[i].ID == st.id {
+ f.activity[i].Status = "Successful"
+ }
+ }
+ if f.states[fakeIID] == "Standby" {
+ f.heldTerminating()
+ }
+ }
+ h.settles = later
+ if !h.terminatedAt.IsZero() && !f.now.Before(h.terminatedAt.Add(30*time.Second)) {
+ f.states[fakeIID] = "Terminated"
+ }
+ if !h.departureAt.IsZero() && !f.now.Before(h.departureAt) {
+ h.departed[ref(fakeIID)] = true
+ }
+ serving := 0
+ for _, st := range f.states {
+ if st == "InService" || st == "Pending" || st == "PreInService" {
+ serving++
+ }
+ }
+ if _, ok := f.states[replacementIID]; !ok && serving < f.desired {
+ f.addMember(replacementIID, "Pending")
+ f.edge(replacementIID)["started_at"] = stamp(f.now)
+ f.published[replacementIID] = f.now.Add(2 * time.Second)
+ h.launchedAt = f.now
+ }
+ if f.states[replacementIID] == "Pending" && !f.now.Before(h.launchedAt.Add(h.launchDelay)) {
+ f.states[replacementIID] = "InService"
+ }
+ if f.states[replacementIID] == "InService" && !f.now.Before(h.launchedAt.Add(h.launchDelay+20*time.Second)) {
+ f.tg[replacementIID] = "healthy"
+ }
+}
+
+// heldSession is HeldFake.session: the drain verbs, and status with the
+// fence and drain sections. ok is false for the verbs the roll fake runs.
+func (f *fake) heldSession(iid, verb string, a BoxArgs) (r any, err error, ok bool) {
+ h := f.held
+ s := f.boxes[iid]
+ mine := iid == fakeIID
+ if verb == "status" {
+ fence := map[string]any{"state": "absent", "transaction": nil, "error": nil}
+ drain := idleDrain(strings.Repeat("9", 32))
+ if mine {
+ if h.fence != "" {
+ fence = map[string]any{"state": "present", "transaction": h.fence, "error": nil}
+ }
+ drain = copyArgs(h.drainState)
+ if h.statusDrain != nil {
+ drain = h.statusDrain(drain)
+ }
+ }
+ s["fence"], s["drain"] = fence, drain
+ return nil, nil, false
+ }
+ switch verb {
+ case "drain", "drain-cancel", "fence-clear", "edge-stop":
+ default:
+ return nil, nil, false
+ }
+ if !mine {
+ f.violate("%s on another member %s", verb, iid)
+ return nil, Refusal{Key: "remote"}, true
+ }
+ tx := a.Transaction
+ status := func() (any, error, bool) {
+ r, err := f.session(iid, "status", BoxArgs{})
+ return r, err, true
+ }
+ switch verb {
+ case "drain":
+ if f.states[fakeIID] != "Standby" || f.tg[fakeIID] != "unused" || f.desired != f.minimum ||
+ f.minimum != f.maximum-1 {
+ f.violate("drain outside Standby: %v %v %d %d %d", f.states[fakeIID], f.tg[fakeIID],
+ f.minimum, f.desired, f.maximum)
+ return nil, Refusal{Key: "remote"}, true
+ }
+ switch h.drainMode {
+ case "uncertain":
+ return nil, Uncertain{Key: "remote"}, true
+ case "refused":
+ // The verb refused before any report (a fence of another
+ // transaction, say).
+ h.drainCalls++
+ return map[string]any{"exit": int64(1), "report": nil}, nil, true
+ case "remote-timeout":
+ if h.drainCalls == 0 {
+ // The remote bound killed the verb (exit 124); the move goes on.
+ h.drainCalls = 1
+ h.fence = tx
+ h.drainState = moveDrain(h.incarnation, tx, "running")
+ return nil, Uncertain{Key: "remote", Timeout: true}, true
+ }
+ }
+ h.drainCalls++
+ switch h.drainMode {
+ case "drop-once", "drop-running", "drop-done":
+ // The session drops; the agent's move step goes on.
+ h.fence = tx
+ result := "running"
+ if h.drainMode == "drop-done" {
+ result = "ok"
+ }
+ h.drainState = moveDrain(h.incarnation, tx, result)
+ if h.drainMode != "drop-once" || h.drainCalls == 1 {
+ return nil, Uncertain{Key: "remote"}, true
+ }
+ }
+ okDrain := h.drainMode == "ok" || h.drainMode == "drop-once" || h.drainMode == "remote-timeout"
+ if h.fence != "" && h.fence != tx {
+ f.violate("drain under another transaction's fence %s", h.fence)
+ }
+ h.fence = tx
+ result, exit, reasons := "ok", int64(0), []any{}
+ if !okDrain {
+ result, exit, reasons = "failed", 1, []any{"the connections did not drain"}
+ }
+ h.drainState = moveDrain(h.incarnation, tx, result)
+ report := map[string]any{"v": int64(1), "transaction": tx, "incarnation": h.incarnation, "step": "move",
+ "result": result, "reasons": reasons, "fence": tx,
+ "moved": []any{map[string]any{"host": "blog", "holder": ref(fakePeer), "gen": int64(4), "confirmed": "take"}},
+ "released": []any{}, "unclean": []any{}, "left": []any{},
+ "holds": map[string]any{"longest_ms": int64(1500), "todays_answer": int64(0), "refused_at_once": int64(0)},
+ "connections_closed_at_bound": int64(0)}
+ if h.afterDrain != nil {
+ h.afterDrain()
+ }
+ if h.reportEdit != nil {
+ h.reportEdit(report)
+ }
+ return map[string]any{"exit": exit, "report": report}, nil, true
+ case "drain-cancel":
+ if h.cancel == "refused" {
+ return map[string]any{"exit": int64(1),
+ "detail": "group-maintenance: the edge runs but its drain socket does not answer; the fence stays"}, nil, true
+ }
+ if h.fence != "" && h.fence != tx {
+ f.violate("drain-cancel of another transaction's fence %s", h.fence)
+ }
+ if h.cancel != "status-disagrees" {
+ h.fence = ""
+ }
+ h.drainState = idleDrain(h.incarnation)
+ h.statusDrain = nil
+ return status()
+ case "fence-clear":
+ if h.fence != "" && h.fence != tx {
+ f.violate("fence-clear of another transaction's fence %s", h.fence)
+ }
+ h.fence = ""
+ return status()
+ }
+ // edge-stop
+ if !h.edgeStops {
+ if h.edgeStopAnswer != nil {
+ return copyArgs(h.edgeStopAnswer), nil, true
+ }
+ return map[string]any{"main_pid": int64(4242), "active_state": "active"}, nil, true
+ }
+ e := s["edge"].(map[string]any)
+ e["state"], e["pid"], e["identity"] = "unknown", nil, nil
+ s["health"] = map[string]any{"state": "unhealthy", "code": nil, "error": nil}
+ // The drain socket went with the agent.
+ h.drainState = map[string]any{"state": "unknown", "incarnation": nil, "transaction": nil, "step": nil,
+ "result": nil, "error": "dial"}
+ return map[string]any{"main_pid": int64(0), "active_state": "inactive"}, nil, true
+}
+
+// The data bucket: the region's host locks, as HeldFake's list-objects-v2
+// (a delimiter listing of hosts, then an exact-key listing per lock) and
+// get-object answer them.
+
+func (s fakeStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ f := s.f
+ r, err := f.request("lock_hosts", map[string]any{"bucket": s.bucket, "prefix": prefix}, func() (any, error) {
+ if f.held == nil || s.bucket != f.held.dataBucket || prefix != "instances/" {
+ f.violate("lock listing of %s/%s", s.bucket, prefix)
+ return nil, Uncertain{Key: "api"}
+ }
+ var out []string
+ for _, host := range sortedKeys(f.held.locks) {
+ out = append(out, "instances/"+host+"/")
+ }
+ return out, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return r.([]string), nil
+}
+
+func lockHost(key string) (string, bool) {
+ rest, ok := strings.CutPrefix(key, "instances/")
+ if !ok {
+ return "", false
+ }
+ return strings.CutSuffix(rest, "/lock.json")
+}
+
+func (s fakeStore) lockList(prefix string) ([]string, error) {
+ f := s.f
+ r, err := f.request("lock_list", map[string]any{"key": prefix}, func() (any, error) {
+ host, ok := lockHost(prefix)
+ if !ok {
+ f.violate("lock key listing of %s", prefix)
+ return nil, Uncertain{Key: "api"}
+ }
+ if f.held.locks[host] == nil {
+ return []string{}, nil
+ }
+ return []string{prefix}, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return r.([]string), nil
+}
+
+func (s fakeStore) lockGet(key string) ([]byte, string, error) {
+ f := s.f
+ r, err := f.request("lock_get", map[string]any{"key": key}, func() (any, error) {
+ host, ok := lockHost(key)
+ if !ok || f.held.locks[host] == nil {
+ return nil, os.ErrNotExist
+ }
+ return json.Marshal(f.held.locks[host])
+ })
+ if err != nil {
+ return nil, "", err
+ }
+ return r.([]byte), "etag", nil
+}
diff --git a/internal/grouproll/roll.go b/internal/grouproll/roll.go
index db56917a8..877e5244a 100644
--- a/internal/grouproll/roll.go
+++ b/internal/grouproll/roll.go
@@ -57,6 +57,13 @@ type seams struct {
beforeAlert func(ctx context.Context, e *Engine) // a provider call before a resumable stop
onDiverged func(ctx context.Context, e *Engine) // a provider call on a return hook
skipDivergence bool // the divergence flag is not written
+
+ // The planned handovers' mutants (depart.go).
+ terminateDecrement func(ctx context.Context, iid string) (WriteResult, error) // terminate with decrement
+ terminateFirst bool // terminate before the edge stop
+ skipSecondSweep bool // no lock sweep after the stop
+ unparkUnknownDrain bool // unknown drain status passes the return
+ restoreDesiredEarly bool // desired restored before the terminate check
}
// observed are the loop observations classify reads beside the journal
@@ -1351,7 +1358,7 @@ func (e *Engine) refuseWhileMoving(status map[string]any) error {
}
tx := e.hStr("transaction")
running := d["transaction"] == tx && d["step"] == "move" && d["result"] == "running"
- if d["state"] == "known" && !running {
+ if (d["state"] == "known" || e.seams.unparkUnknownDrain) && !running {
return nil
}
if _, err := e.event("return-refused-moving", map[string]any{"drain": d}); err != nil {
@@ -1394,7 +1401,7 @@ func (e *Engine) finishReturn(ctx context.Context, ready *readiness) error {
}
failedDrain := e.unchanged()
if e.has("drained", nil) && !failedDrain {
- if err := e.drainSummary(); err != nil {
+ if err := e.drainSummary(nil); err != nil {
return err
}
}