carlos / platform Public

region HA sim: model the planned handover, I9 to I11 and its mutations

Task 7 of the held-requests build (spec §25.10, r4 §25.15). Each seed now
also runs one operator transaction (roll, replace or remove) on member A
of its own 2 to 5 box world, one step per second, after the lease walk.

Modelled: Standby and the group's desired capacity; the acknowledged
withdrawal with slow and missing acknowledgements; quiescence of acquires
in flight when the drain starts; moves with holds, admission tickets and
the in-flight drain; takes that win or lose the marker race and take
timeouts; the redirect kept for the whole drain with its coalesced lock
read; direct requests, hops, marked streams and cross-region first boxes;
whole-copy replay and the shared attempt counter; resets after a send and
dial failures before it; lease loss mid-move; stale holder caches; agent
restarts and a reboot between the report and the action; the start fence,
the edge stop and a delayed terminate. Every acquire still goes through
hafresh.DecideAcquire and every release through the world's marker path.

New invariants: I9 (no request reaches two apps; no truncated replay),
I10 (every held request answered within its bound plus one forward),
I11 (no provider action while a lease names its box or an acquire on it
is in flight; the group terminates only A), plus H1, FA and WD. I1 and I4
are the existing checks, plus no onward forward.

Thirteen new rules, each with a deterministic witness.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e1e10cf47628d8c64f2e69a70cc84e5f3aa1a59f parent 1fc00d1
3 files changed, +2,384 −0
  • internal/sim/regionha/handover_test.go +2,062 −0
  • internal/sim/regionha/handover_witness_test.go +321 −0
  • internal/sim/regionha/world_test.go +1 −0

Intent

Human

<task-notification> <task-id>a8303ed4bc3147d03</task-id> <tool-use-id>toolu_01MaPPxWNQFoNDQ2gEaXnaMu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a8303ed4bc3147d03.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6: roll tool" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. N2 is fixed: a terminate attempt is now decided only by its own activity, so a previous attempt's failure can no longer resend it, spend its retries, or stop it early. Commit: `1fc00d18` region HA: a terminate attempt is decided by its own activity (not pushed). The census test passes unchanged, since the Python scripts aren't census units. The fix: - **Answered attempt:** if its response named an activity ID, only that activity decides it. Until AWS lists that activity, the attempt waits up to 120 s, then retries. - **Otherwise:** the 5 s clock-skew allowance only counts activities whose IDs no earlier attempt owns. Earlier attempts own the IDs their responses named and those listed when they were decided. Tests: - 288 Python tests pass, run with the sandbox off after the known bwrap start failure. - 39 of 39 mutations are caught, including three new ones on the activity-ID logic. - The table test now covers more than 30,000 rows, including previous activities 1 s before the intent, with the ID known or not. - The case you specified passes: answered with the intent at 1000, now 1001, and only a previous Failed at 999 returns wait. - A new flow test covers a quick failure followed by an accepted retry whose activity shows up 20 s late. Exactly 2 terminates are sent. Concerns: none new. `git commit` warned about `.git/packed-refs.lock` in rounds 2 and 3. That's an empty lock file from 08:15 that I didn't create, probably another session's. Both commits landed and the branch points at them; I left the lock alone. Still owed: the live dev call (the operator policy must be applied first) and the runbook. Report (fix round 3 appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-6-report.md</result> <usage><subagent_tokens>463086</subagent_tokens><tool_uses>23</tool_uses><duration_ms>1763583</duration_ms></usage> </task-notification>

Attributed to this commit: 12.0 g CO₂e (1,552,145 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-held-build, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/sim/regionha/handover_test.go b/internal/sim/regionha/handover_test.go
new file mode 100644
index 000000000..47500086b
--- /dev/null
+++ b/internal/sim/regionha/handover_test.go
@@ -0,0 +1,2062 @@
+package regionha
+
+import (
+ "fmt"
+ "math/rand"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// The planned handover (spec §25, with r4's rulings in §25.15; §25.10's
+// simulation paragraph; plan Task 7).
+//
+// One seed runs one operator transaction on member A of a region of 2 to 5
+// boxes: roll, replace or remove. It runs on its own world, after the
+// lease walk (runHandoverScenario), the way the group and duty scenarios
+// do. One step of this model is one second: a drain lasts minutes, a hold
+// seconds. The world's minute ticks still run underneath (renewals, held
+// releases), every 60 seconds.
+//
+// What is real and what is modelled. Every acquire, by a successor's take,
+// a third box, a hop receiver or a first box that a handover answer names,
+// goes through the world's HA acquire, so hafresh.DecideAcquire decides it.
+// Every release is the world's releaseHAClean with its marker. The I1
+// oracle is the world's: at most one running unit of a host, and every
+// replica write from the lease holder. Everything else is a model of the
+// protocol, not of the production code: MoveState and its holds, the
+// admission tickets, the redirect and its coalesced lock read, the first
+// box's body copy and attempt counter, the acknowledged withdrawal, the
+// drain report, the start fence, the roll tool's steps and the group's
+// desired capacity.
+//
+// Rulings the model follows (progress.md): always-on workers are released,
+// not taken (the model has none, so nothing takes one); cross-region first
+// boxes replay only bodyless requests (Q2); a handover answer is followed
+// only on attempt 1 (H3); desired capacity is lowered only by A's Standby
+// (H4); the provider action runs only on a current-incarnation report, with
+// the fence held and the edge stopped (H5, R3.1); MoveState registers an
+// admission ticket and a move waits for tickets within 10 s (R3.2); a hop
+// for a moving host that is not replayable or is a second attempt is
+// answered at once (R3.3); the redirect is kept for the whole drain and is
+// checked by a coalesced lock read (R3.4).
+//
+// Invariants:
+//
+// - I1 and I4 as the lease walk checks them, plus: a hop receiver never
+// forwards, and no request makes more than two forward attempts.
+// - I9, no unsafe replay: no request reaches two apps' handlers, and no
+// app gets a body the first box could not send whole.
+// - I10, bounded hold: every held request is answered within its bound
+// plus one forward (that forward's own 30 s bound), and every request
+// is answered.
+// - I11, lock-free action: no provider action (edge stop, roll's apply,
+// terminate at dispatch and as it lands, and any termination the group
+// makes) runs while a lease names its box or an acquire on it is in
+// flight; the group terminates only the member the transaction targets.
+// - H1, one handover decision: the tenant pipeline (gate, accounting)
+// runs once per request; no request enters A's app for a host that is
+// moving there, or without an admission ticket.
+// - FA, F-A in every phase: no request is held for a host whose lease A
+// lost.
+// - WD, acknowledged withdrawal (§25.4 step 1): no box places a wake on A
+// after A closed its start gate for the drain.
+
+const (
+ hoClientBound = 30 // s, a client request's hold (wakeWaitBound)
+ hoHopBound = 25 // s, a hop's hold
+ hoForward = 30 // s, one forward's own bound (the hop header timeout)
+ hoInflight = 10 // s, a moving host's in-flight drain
+ hoAskEvery = 5 // s, between acknowledgement asks
+ hoAckBound = 120 // s, a missing acknowledgement fails the drain
+ hoTakeWait = 40 // s, the take's wait
+ hoConnBound = 60 // s, the connection drain
+ hoLockEvery = 5 // s, the redirect's coalesced lock read
+ hoWidth = 4 // moves at a time
+ hoMaxSec = 1500
+)
+
+func init() {
+ allRules = append(allRules,
+ // §25.10's mutations
+ "take-authorizes-acquire", // the take bypasses DecideAcquire (I1)
+ "handover-authorizes-acquire", // a handover answer naming the first box bypasses DecideAcquire (I1)
+ "movestate-after-gate", // the tenant pipeline runs before MoveState (H1)
+ "movestate-skips-marked", // a marked held-stream request skips MoveState (H1)
+ "hold-after-loss", // MoveState checks the hold before the loss latch (F-A)
+ "replay-without-copy", // a hop is marked replayable without a whole copy (H2, I9)
+ "replay-after-reset", // a request is sent again after a reset after its send (H2, I9)
+ "handover-on-second-attempt", // the retry paths do not share the attempt counter (H3, I4)
+ "desired-lowered-elsewhere", // the terminate lowers desired too (H4, I11)
+ "report-before-quiescence", // the drain reports before in-flight acquires settle (H5, I11)
+ "action-on-stale-report", // the tool acts on the drain verb's report without reading again (H5, I11)
+ "place-before-acks", // the drain goes on before every acknowledgement (§25.4 step 1, WD)
+ "fence-lift-on-unknown", // the tool lifts the fence on an unknown edge state (R3.1, I11)
+ )
+}
+
+// hoPub is one publication of A's edges file, as far as the drain goes.
+type hoPub struct{ Draining, Drained bool }
+
+// hoNode is a box as a first box and a folder of A's edges file: a region
+// box, or (b nil) a cross-region first box that views the region.
+type hoNode struct {
+ b *box
+ name string
+ cache map[string]string // the holder cache, host -> ref
+ seen int // the generation of A's edges file this node folded
+ foldOK int // the second from which its fold of A's current publication succeeds; -1 never
+ reset bool // its next hop's connection resets after the send
+ dial bool // its next hop's dial fails, before the send
+}
+
+// hoReq is one request.
+type hoReq struct {
+ ID int
+ Host string
+ Kind string // client, marked (an edge-held stream's request)
+ Body string // none, small (known length, at most 64 KiB), large, unknown
+ Work int // seconds it runs in A's app
+ First *hoNode
+ Whole bool // the first box read the body whole before its first send
+ Replayable bool // X-Carlos-Replayable: 1
+ Sends int // forward attempts the first box made
+ Label int // the attempt number its last hop carried
+ Path string
+ PathSends map[string]int
+ Delivered []int
+ Truncated bool
+ Pipeline int
+ GatedBy *box
+ Ticket bool
+ HeldAt int
+ HeldHop bool
+ Bound int
+ Answered bool
+ Answer string
+ At int
+}
+
+type hoApp struct {
+ r *hoReq
+ until int
+}
+
+type hoWait struct {
+ r *hoReq
+ b *box
+}
+
+type hoMove struct {
+ Host string
+ State string // holding, releasing, taken, failed
+ Stage string // inflight, release, take, done
+ At int
+ ReleaseAt int
+ AnswerAt int
+ Succ *box
+ Timeout bool
+ Holder string
+ Gen int64
+}
+
+type hoLockRead struct {
+ At int
+ View hafresh.View
+}
+
+type hoReport struct {
+ Inc int
+ OK bool
+ Step string
+}
+
+// hoKnobs are a transaction's faults and timings, drawn once per seed (or
+// set by a witness). The model never draws anything else from them.
+type hoKnobs struct {
+ Kind string
+ Start int
+ AckDelay map[string]int // per node: seconds after the publication its fold succeeds; -1 never
+ Ack2Delay map[string]int
+ PendingFor int
+ Release map[string]sleepOpts
+ ReleaseLat map[string]int
+ TakeLat map[string]int
+ Race map[string]bool
+ RestoreFails map[string]bool
+ ReportDelay int
+ Reboot int // seconds into the report wait that A reboots; -1 never
+ Restart int // the second A's agent crashes; -1 never
+ RestartDown int // seconds it stays down
+ Stop string // proven, unknown-stopped, unknown-running, running
+ Land int // seconds from the terminate's dispatch to its landing
+ EdgeRestart int // seconds after the dispatch a stopped edge restarts; -1 never
+ Poll string // what the tool reads of the member before the terminate lands: unknown, running
+ PendingAtDrain bool // a wake on A is between its GET and its PUT as the drain starts
+ Cancel bool
+ Probe string // the cancel's edge probe when the agent socket is down: absent, unknown
+ LocalRace bool // a third box acquires between a redirect's read and the named first box's acquire
+}
+
+type hoWorld struct {
+ w *world
+ rng *rand.Rand
+ scripted bool
+ k hoKnobs
+ A *box
+ n int
+ txn string
+ nodes []*hoNode
+ nodeOf map[*box]*hoNode
+ remote *hoNode
+ sec int
+
+ pubs []hoPub
+ draining bool
+ drainInc int
+ gate bool
+ fence string
+ connOpen bool
+ moves map[string]*hoMove
+ latch map[string]bool
+ inApp []*hoApp
+ held []*hoReq
+ waiting []*hoWait
+ ready map[*box]map[string]int
+ lockRead map[string]hoLockRead
+ reqs []*hoReq
+ unclean bool
+ failures []string
+ report *hoReport
+
+ phase string
+ phaseAt int
+ stopAnswer string
+ edgeStopped bool
+
+ // the group
+ desired, minimum int
+ standby bool
+ inService map[*box]bool
+
+ // beforeLocal runs once, just before a first box that a handover answer
+ // names acquires (a witness's race).
+ beforeLocal func()
+
+ stats, done map[string]int
+}
+
+// ---- construction ----
+
+func newHO(w *world, rng *rand.Rand, k hoKnobs) *hoWorld {
+ ho := &hoWorld{
+ w: w, rng: rng, scripted: rng == nil, k: k, A: w.boxes[0], n: len(w.boxes), txn: "t1",
+ nodeOf: map[*box]*hoNode{}, pubs: []hoPub{{}}, connOpen: true,
+ moves: map[string]*hoMove{}, latch: map[string]bool{}, ready: map[*box]map[string]int{},
+ lockRead: map[string]hoLockRead{}, phase: "before",
+ inService: map[*box]bool{}, stats: map[string]int{}, done: map[string]int{},
+ }
+ for _, b := range w.boxes {
+ nd := &hoNode{b: b, name: b.Self.Ref, cache: map[string]string{}}
+ ho.nodes = append(ho.nodes, nd)
+ ho.nodeOf[b] = nd
+ ho.ready[b] = map[string]int{}
+ ho.inService[b] = true
+ }
+ ho.remote = &hoNode{name: "remote", cache: map[string]string{}}
+ ho.nodes = append(ho.nodes, ho.remote)
+ ho.desired, ho.minimum = ho.n, ho.n
+ return ho
+}
+
+func (ho *hoWorld) fail(inv, format string, args ...any) {
+ ho.w.fail(inv, "[s%d] "+format, append([]any{ho.sec}, args...)...)
+}
+
+func (ho *hoWorld) logf(format string, args ...any) {
+ ho.w.logf("ho s%d: "+format, append([]any{ho.sec}, args...)...)
+}
+
+func (ho *hoWorld) event(name string) { ho.w.event(name) }
+
+func (ho *hoWorld) live(x *box) bool {
+ return x != nil && !ho.w.isTerminated(x) && x.Agent == agentUp
+}
+
+// leaseOwner is the live lease's owner in v: a lease that is not a marker
+// and has not expired.
+func (ho *hoWorld) leaseOwner(v hafresh.View) *box {
+ if v.Absent || v.Lock.Release != nil || !ho.w.now().Before(v.Lock.ExpiresAt) {
+ return nil
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ if !ok {
+ return nil
+ }
+ return ho.w.boxRef(o.Ref)
+}
+
+// namesBox: v is a lease (not a marker), live or expired, naming x.
+func namesBox(v hafresh.View, x *box) bool {
+ if v.Absent || v.Lock.Release != nil {
+ return false
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ return ok && o.Ref == x.Self.Ref
+}
+
+// ---- A's edges file and the folds ----
+
+// publish is a new publication of A's edges file; each node's fold of it
+// succeeds delay[node] seconds later (-1 never; nil: within 2 s).
+func (ho *hoWorld) publish(p hoPub, delay map[string]int) {
+ ho.pubs = append(ho.pubs, p)
+ for _, nd := range ho.nodes {
+ if nd.b == ho.A {
+ nd.seen = len(ho.pubs) - 1
+ continue
+ }
+ d := 1
+ if delay != nil {
+ d = delay[nd.name]
+ }
+ if d < 0 {
+ nd.foldOK = -1
+ } else {
+ nd.foldOK = ho.sec + d
+ }
+ }
+ ho.logf("A publishes edges generation %d %+v", len(ho.pubs)-1, p)
+}
+
+// fold is one fold read of A's edges file by nd.
+func (ho *hoWorld) fold(nd *hoNode) bool {
+ if nd.b != nil && !ho.live(nd.b) || nd.foldOK < 0 || ho.sec < nd.foldOK || nd.seen == len(ho.pubs)-1 {
+ return false
+ }
+ nd.seen = len(ho.pubs) - 1
+ if ho.pubs[nd.seen].Drained {
+ // §25.4 step 4: peers drop holder-cache entries naming A.
+ for h, ref := range nd.cache {
+ if ref == ho.A.Self.Ref {
+ delete(nd.cache, h)
+ }
+ }
+ }
+ return true
+}
+
+// denied: nd's placement treats x as local-denied.
+func (ho *hoWorld) denied(nd *hoNode, x *box) bool {
+ if x != ho.A {
+ return false
+ }
+ if nd.b == ho.A {
+ return ho.draining
+ }
+ return ho.pubs[nd.seen].Draining
+}
+
+// acks is one acknowledgement round's progress (§25.4 steps 1 and 4): A
+// asks every live node that views the region every 5 s; a node answers
+// once it has folded A's current publication. done once all have; failed
+// once one is missing at 120 s.
+func (ho *hoWorld) acks() (done, failed bool) {
+ el := ho.sec - ho.phaseAt - 1
+ if el < 0 || el%hoAskEvery != 0 {
+ return false, false
+ }
+ all := true
+ for _, nd := range ho.nodes {
+ if nd.b == ho.A {
+ continue
+ }
+ if nd.b != nil && !ho.live(nd.b) {
+ all = false
+ continue
+ }
+ ho.fold(nd)
+ if nd.seen != len(ho.pubs)-1 {
+ all = false
+ }
+ }
+ if all {
+ return true, false
+ }
+ if !on("place-before-acks") {
+ ho.event("ho-acks-skipped")
+ return true, false
+ }
+ if el >= hoAckBound {
+ return false, true
+ }
+ if el > 0 {
+ ho.event("ho-ack-slow")
+ }
+ return false, false
+}
+
+// ---- requests ----
+
+func (ho *hoWorld) req(kind string, fb *hoNode, h, body string, work int) *hoReq {
+ r := &hoReq{ID: len(ho.reqs) + 1, Host: h, Kind: kind, Body: body, Work: work, First: fb, HeldAt: -1, PathSends: map[string]int{}}
+ if kind == "marked" {
+ r.Body = "none"
+ }
+ ho.reqs = append(ho.reqs, r)
+ return r
+}
+
+// arrive is a request's arrival at its first box.
+func (ho *hoWorld) arrive(r *hoReq) {
+ ho.logf("request %d (%s %s body %s) arrives at %s", r.ID, r.Kind, r.Host, r.Body, r.First.name)
+ if r.First.b == ho.A {
+ ho.finish(r.First, r, ho.atA(r, false))
+ return
+ }
+ ho.route(r.First, r)
+}
+
+// answer is the first box's answer to the client: app (an app answered),
+// today (today's 503 or 502), fa (F-A's 503 holder none), cut (the app
+// was cut at a bound) or reset.
+func (ho *hoWorld) answer(r *hoReq, kind string) {
+ if r.Answered {
+ ho.fail("MODEL", "request %d answered twice (%s, then %s)", r.ID, r.Answer, kind)
+ return
+ }
+ r.Answered, r.Answer, r.At = true, kind, ho.sec
+ ho.event("ho-answer-" + kind)
+ ho.logf("request %d: %s", r.ID, kind)
+ if r.Pipeline > 1 {
+ ho.fail("H1", "request %d for %s ran the tenant pipeline %d times", r.ID, r.Host, r.Pipeline)
+ }
+ if r.HeldAt >= 0 && r.At-r.HeldAt > r.Bound+hoForward {
+ ho.fail("I10", "request %d for %s was held at second %d and answered at %d, past its %d s bound plus one forward", r.ID, r.Host, r.HeldAt, r.At, r.Bound)
+ }
+}
+
+// finish is the first box acting on what its last attempt (or its own
+// serving) answered.
+func (ho *hoWorld) finish(fb *hoNode, r *hoReq, res string) {
+ if r.Answered || res == "pending" {
+ return
+ }
+ switch {
+ case strings.HasPrefix(res, "named:"):
+ // §6.4's 503 naming the holder; §6.5's one retry for a bodyless GET.
+ ref := strings.TrimPrefix(res, "named:")
+ y := ho.w.boxRef(ref)
+ if fb.b != y {
+ fb.cache[r.Host] = ref
+ }
+ if r.Sends == 1 && r.Body == "none" && ho.live(y) && fb.b != y {
+ ho.event("ho-retry-named")
+ ho.send(fb, r, y, "retry")
+ return
+ }
+ ho.answer(r, "today")
+ case strings.HasPrefix(res, "handover:"):
+ ref := strings.TrimPrefix(res, "handover:")
+ if r.Label != 1 { // H3: only an answer to the first attempt is followed
+ ho.event("ho-handover-not-followed")
+ ho.answer(r, "today")
+ return
+ }
+ y := ho.w.boxRef(ref)
+ if !ho.live(y) || y == ho.A {
+ ho.answer(r, "today")
+ return
+ }
+ ho.event("ho-handover-followed")
+ if fb.b == y {
+ // The ref names this box: serve locally, which spends no attempt.
+ ho.event("ho-handover-local")
+ delete(fb.cache, r.Host)
+ if f := ho.beforeLocal; f != nil {
+ ho.beforeLocal = nil
+ f()
+ } else if ho.k.LocalRace {
+ ho.localRace(y, r.Host)
+ }
+ var local string
+ if e := y.Entries[r.Host]; e != nil && e.Releasing == nil {
+ local = ho.serve(y, r)
+ } else {
+ local = ho.wakeAt(y, r, true)
+ }
+ if strings.HasPrefix(local, "named:") {
+ z := ho.w.boxRef(strings.TrimPrefix(local, "named:"))
+ if r.Sends < 2 && ho.live(z) && z != y {
+ ho.send(fb, r, z, "handover")
+ return
+ }
+ local = "today"
+ }
+ ho.finish(fb, r, local)
+ return
+ }
+ fb.cache[r.Host] = ref
+ ho.send(fb, r, y, "handover")
+ default:
+ ho.answer(r, res)
+ }
+}
+
+// route is the first box's front forward (fb is not A).
+func (ho *hoWorld) route(fb *hoNode, r *hoReq) {
+ h := r.Host
+ if x := fb.b; x != nil {
+ if e := x.Entries[h]; e != nil && e.Releasing == nil {
+ ho.finish(fb, r, ho.serve(x, r))
+ return
+ }
+ }
+ t := ho.target(fb, h)
+ switch {
+ case t == nil:
+ ho.answer(r, "today")
+ case t == fb.b:
+ ho.finish(fb, r, ho.wakeAt(t, r, false))
+ default:
+ ho.send(fb, r, t, "front")
+ }
+}
+
+// target is where fb sends a request for h: its holder cache, else the
+// lock's live (or expired) owner, else its placement choice.
+func (ho *hoWorld) target(fb *hoNode, h string) *box {
+ w := ho.w
+ if ref := fb.cache[h]; ref != "" {
+ if y := w.boxRef(ref); ho.live(y) && y != fb.b {
+ return y
+ }
+ delete(fb.cache, h)
+ }
+ v := w.view(h)
+ if fb.b == nil {
+ // A cross-region first box with no cache entry backhauls to a box
+ // of the region it does not deny, which names the holder (§25.5).
+ var in []*box
+ for _, x := range w.boxes {
+ if ho.live(x) && !ho.denied(fb, x) {
+ in = append(in, x)
+ }
+ }
+ if len(in) == 0 {
+ return nil
+ }
+ x := in[len(ho.reqs)%len(in)]
+ if x == ho.A {
+ ho.placedOnA(fb, h)
+ }
+ return x
+ }
+ if o := ho.leaseOwner(v); o != nil {
+ if o != fb.b {
+ fb.cache[h] = o.Self.Ref
+ }
+ return o
+ }
+ if !v.Absent && v.Lock.Release == nil {
+ o, _ := hafresh.ParseOwner(v.Lock.Owner)
+ if y := w.boxRef(o.Ref); ho.live(y) {
+ return y
+ }
+ return nil
+ }
+ return ho.place(fb, h, v)
+}
+
+// place is fb's placement of a wake of h: §6.3 rule 1 (a clean marker's
+// releaser), else the roomiest box, over the boxes its fold does not deny.
+// A cross-region first box's choice is where it backhauls.
+func (ho *hoWorld) place(fb *hoNode, h string, v hafresh.View) *box {
+ var choice *box
+ if !v.Absent && v.Lock.Release != nil && v.Lock.Release.Clean {
+ if x := ho.w.boxRef(v.Lock.Release.Box); ho.live(x) && !ho.denied(fb, x) {
+ choice = x
+ }
+ }
+ if choice == nil {
+ for _, x := range ho.w.boxes {
+ if !ho.live(x) || ho.denied(fb, x) {
+ continue
+ }
+ if choice == nil || len(x.Entries) < len(choice.Entries) {
+ choice = x
+ }
+ }
+ }
+ if choice == ho.A {
+ ho.placedOnA(fb, h)
+ }
+ return choice
+}
+
+// placedOnA is WD, as fb chooses A for h.
+func (ho *hoWorld) placedOnA(fb *hoNode, h string) {
+ ho.event("ho-placed-on-A")
+ if ho.gate && ho.draining && ho.drainInc == ho.A.PID {
+ ho.fail("WD", "%s placed a wake of %s on A after A closed its start gate for the drain", fb.name, h)
+ }
+}
+
+// send is one forward attempt by the first box fb to x.
+func (ho *hoWorld) send(fb *hoNode, r *hoReq, x *box, path string) {
+ if fb != r.First {
+ ho.fail("I4", "request %d: %s forwards a request it received as a hop", r.ID, fb.name)
+ return
+ }
+ r.Sends++
+ r.PathSends[path]++
+ r.Path = path
+ r.Label = r.Sends
+ if !on("handover-on-second-attempt") {
+ r.Label = r.PathSends[path] // each retry path counts its own attempts
+ }
+ if r.Sends > 2 {
+ ho.fail("I4", "request %d for %s: forward attempt %d by %s", r.ID, r.Host, r.Sends, fb.name)
+ }
+ if r.Sends == 1 {
+ // H2: the whole body, at most 64 KiB, read before the first send;
+ // a cross-region first box replays only bodyless requests (Q2).
+ r.Whole = r.Body == "none" || r.Body == "small"
+ r.Replayable = r.Body == "none" || r.Body == "small" && fb.b != nil
+ if !on("replay-without-copy") {
+ r.Replayable = true
+ }
+ } else if !r.Whole {
+ r.Truncated = true // the body went into the first send; no copy is left
+ }
+ ho.logf("request %d: %s sends attempt %d (label %d, %s) to box%d", r.ID, fb.name, r.Sends, r.Label, path, x.ID)
+ if fb.dial {
+ fb.dial = false
+ ho.event("ho-dial-before-send")
+ ho.answer(r, "today")
+ return
+ }
+ res := ho.receive(x, r)
+ if fb.reset && res != "pending" {
+ fb.reset = false
+ ho.event("ho-reset-after-send")
+ ho.logf("request %d: the connection to box%d resets after the send", r.ID, x.ID)
+ if !on("replay-after-reset") && r.Whole && r.Sends < 2 {
+ ho.send(fb, r, x, "reset")
+ return
+ }
+ res = "reset"
+ }
+ if strings.HasPrefix(res, "handover:") {
+ ho.event("ho-handover-answer")
+ }
+ ho.finish(fb, r, res)
+}
+
+// receive is a hop's receiver. It never forwards.
+func (ho *hoWorld) receive(x *box, r *hoReq) string {
+ if !ho.live(x) {
+ return "today" // the dial is refused
+ }
+ if x == ho.A {
+ return ho.atA(r, true)
+ }
+ return ho.ordinary(x, r)
+}
+
+// ordinary is a receiver's §6.4 answer: serve, acquire, or name the holder.
+func (ho *hoWorld) ordinary(x *box, r *hoReq) string {
+ h := r.Host
+ if e := x.Entries[h]; e != nil {
+ if e.Releasing != nil {
+ return "today"
+ }
+ return ho.serve(x, r)
+ }
+ v := ho.w.view(h)
+ if o := ho.leaseOwner(v); o != nil && o != x {
+ return "named:" + o.Self.Ref
+ }
+ return ho.wakeAt(x, r, false)
+}
+
+// atA is A's front door for h: MoveState (H1), then today's path.
+func (ho *hoWorld) atA(r *hoReq, hop bool) string {
+ A, h := ho.A, r.Host
+ if !ho.live(A) {
+ return "today"
+ }
+ if !on("movestate-after-gate") && r.GatedBy == nil {
+ r.Pipeline++
+ r.GatedBy = A
+ }
+ st, consulted := "none", false
+ if r.Kind != "marked" || on("movestate-skips-marked") {
+ st, consulted = ho.moveState(h), true
+ }
+ switch st {
+ case "lost":
+ ho.event("ho-fa")
+ return "fa"
+ case "holding", "releasing":
+ if hop && !(r.Replayable && r.Label == 1) {
+ // R3.3: refused at once through the bounded exit, never queued.
+ ho.event("ho-refused-at-once")
+ return "today"
+ }
+ r.HeldAt, r.HeldHop, r.Bound = ho.sec, hop, hoClientBound
+ if hop {
+ r.Bound = hoHopBound
+ }
+ ho.held = append(ho.held, r)
+ ho.event("ho-held")
+ ho.logf("request %d held on A (%s %s)", r.ID, h, st)
+ return "pending"
+ case "taken":
+ m := ho.moves[h]
+ if hop {
+ ref := ho.redirect(h)
+ if ref != "" && r.Replayable && r.Label == 1 {
+ ho.event("ho-redirect")
+ return "handover:" + ref
+ }
+ ho.event("ho-refused-at-once")
+ return "today"
+ }
+ // A client request at A goes to the confirmed holder, A's first attempt.
+ y := ho.w.boxRef(m.Holder)
+ if !ho.live(y) {
+ return "today"
+ }
+ ho.send(ho.nodeOf[A], r, y, "front")
+ return "pending"
+ }
+ r.Ticket = consulted
+ if e := A.Entries[h]; e != nil {
+ if e.Releasing != nil {
+ return "today"
+ }
+ return ho.serve(A, r)
+ }
+ if hop {
+ return ho.ordinary(A, r)
+ }
+ ho.route(ho.nodeOf[A], r)
+ return "pending"
+}
+
+// moveState is MoveState(h) on A (§25.5): the loss latch first.
+func (ho *hoWorld) moveState(h string) string {
+ if on("hold-after-loss") && ho.latch[h] {
+ return "lost"
+ }
+ if m := ho.moves[h]; m != nil && (m.State == "holding" || m.State == "releasing" || m.State == "taken") {
+ return m.State
+ }
+ if ho.latch[h] {
+ return "lost"
+ }
+ return "none"
+}
+
+// redirect is the taken host's answer to a hop (R3.4): one coalesced lock
+// read per host per 5 s; the current owner, or A's placement choice over a
+// marker; "" otherwise.
+func (ho *hoWorld) redirect(h string) string {
+ lr, ok := ho.lockRead[h]
+ if !ok || ho.sec-lr.At >= hoLockEvery {
+ lr = hoLockRead{At: ho.sec, View: ho.w.view(h)}
+ ho.lockRead[h] = lr
+ ho.event("ho-redirect-read")
+ }
+ v := lr.View
+ if !v.Absent && v.Lock.Release == nil {
+ o, okk := hafresh.ParseOwner(v.Lock.Owner)
+ if y := ho.w.boxRef(o.Ref); okk && y != ho.A && ho.live(y) && ho.w.now().Before(v.Lock.ExpiresAt) {
+ return y.Self.Ref
+ }
+ return ""
+ }
+ if !v.Absent {
+ if c := ho.place(ho.nodeOf[ho.A], h, v); c != nil && c != ho.A {
+ return c.Self.Ref
+ }
+ }
+ return ""
+}
+
+// wakeAt is a wake of h at x for r: x's start gate, then the HA acquire.
+func (ho *hoWorld) wakeAt(x *box, r *hoReq, handover bool) string {
+ h := r.Host
+ if x == ho.A && (ho.fence != "" || ho.gate) {
+ ho.event("ho-start-refused")
+ if ho.fence != "" && !ho.draining {
+ ho.event("ho-start-refused-fenced")
+ }
+ return "today"
+ }
+ if !ho.live(x) || x.Pending[h] != nil {
+ return "today"
+ }
+ var res string
+ if handover && !on("handover-authorizes-acquire") {
+ res = ho.force(x, h)
+ } else {
+ res = ho.w.wake(x, h, wakeOpts{}, nil)
+ }
+ ho.logf("box%d wakes %s: %s", x.ID, h, res)
+ if res == "served" {
+ if x == ho.A {
+ r.Ticket = true
+ }
+ return ho.serve(x, r)
+ }
+ if o := ho.leaseOwner(ho.w.view(h)); o != nil && o != x {
+ return "named:" + o.Self.Ref
+ }
+ return "today"
+}
+
+// beginPending is a wake on A between its GET and its PUT: the first host
+// A may acquire.
+func (ho *hoWorld) beginPending() bool {
+ A := ho.A
+ for _, h := range ho.w.hosts {
+ if !ho.live(A) || !idle(A, h) {
+ continue
+ }
+ v := ho.w.view(h)
+ if ho.w.classify(A, h, v) != "" {
+ continue
+ }
+ A.Pending[h] = &pending{View: v, At: ho.w.step}
+ ho.event("ho-pending-begun")
+ ho.logf("A reads %s and classifies it; the PUT is pending", h)
+ return true
+ }
+ return false
+}
+
+// localRace is a third box acquiring h between a redirect's lock read
+// and the acquire of the first box it named.
+func (ho *hoWorld) localRace(y *box, h string) {
+ if ho.leaseOwner(ho.w.view(h)) != nil {
+ return
+ }
+ for _, d := range ho.w.boxes {
+ if d != y && d != ho.A && ho.live(d) && d.Entries[h] == nil && d.Pending[h] == nil {
+ ho.event("ho-local-raced")
+ ho.logf("box%d wakes %s first: %s", d.ID, h, ho.w.wake(d, h, wakeOpts{}, nil))
+ return
+ }
+ }
+}
+
+// force is an acquire some mutation authorizes outside DecideAcquire: a PUT
+// over whatever lock it read, then a restore and the wake.
+func (ho *hoWorld) force(x *box, h string) string {
+ w := ho.w
+ e := w.take(x, h, w.view(h), true)
+ if e == nil {
+ return "refused: contended"
+ }
+ x.AcquiredHere[h] = true
+ l := w.local(x, h)
+ w.setAside(l)
+ w.restore(l, h)
+ w.startWake(x, h, e, l)
+ ho.event("ho-forced-acquire")
+ return "served"
+}
+
+// serve is x's tenant pipeline and app for r.
+func (ho *hoWorld) serve(x *box, r *hoReq) string {
+ h := r.Host
+ if at, ok := ho.ready[x][h]; ok && at > ho.sec {
+ ho.waiting = append(ho.waiting, &hoWait{r: r, b: x})
+ ho.event("ho-wait-restore")
+ return "pending"
+ }
+ if r.GatedBy != x {
+ r.Pipeline++
+ }
+ r.Delivered = append(r.Delivered, x.ID)
+ if len(r.Delivered) > 1 {
+ ho.fail("I9", "request %d for %s reached the apps of boxes %v", r.ID, h, r.Delivered)
+ }
+ if r.Truncated {
+ ho.fail("I9", "request %d for %s (body %s) was sent again without a whole copy; box%d's app got a truncated body", r.ID, h, r.Body, x.ID)
+ }
+ if x == ho.A {
+ if m := ho.moves[h]; m != nil && (m.State == "holding" || m.State == "releasing") {
+ ho.fail("H1", "request %d (%s) entered A's app for %s while it was %s", r.ID, r.Kind, h, m.State)
+ }
+ if !r.Ticket {
+ ho.fail("H1", "request %d (%s) entered A's app for %s with no admission ticket", r.ID, r.Kind, h)
+ }
+ ho.inApp = append(ho.inApp, &hoApp{r: r, until: ho.sec + r.Work})
+ return "pending"
+ }
+ ho.write(x, h)
+ return "app"
+}
+
+func (ho *hoWorld) write(x *box, h string) {
+ if e := x.Entries[h]; e != nil && e.Releasing == nil && x.Local[h] != nil {
+ ho.w.tenantWrite(x, h, false)
+ ho.w.sync(x, h, false)
+ }
+}
+
+// tickets is the number of admitted requests running in A's app for h.
+func (ho *hoWorld) tickets(h string) int {
+ n := 0
+ for _, a := range ho.inApp {
+ if a.r.Host == h {
+ n++
+ }
+ }
+ return n
+}
+
+// cutApp stops h's app on A: the requests still in it are cut.
+func (ho *hoWorld) cutApp(h, why string) {
+ keep := ho.inApp[:0]
+ for _, a := range ho.inApp {
+ if a.r.Host != h {
+ keep = append(keep, a)
+ continue
+ }
+ if !a.r.Ticket {
+ ho.fail("H1", "request %d was in A's app for %s at the stop without a ticket", a.r.ID, h)
+ }
+ ho.event("ho-cut")
+ ho.finish(a.r.First, a.r, "cut")
+ }
+ ho.inApp = keep
+ ho.logf("A stops %s's app (%s)", h, why)
+}
+
+// endHolds answers every request held for h (all hosts when h is "").
+func (ho *hoWorld) endHolds(h, res string) {
+ var hs []*hoReq
+ keep := ho.held[:0]
+ for _, r := range ho.held {
+ if h == "" || r.Host == h {
+ hs = append(hs, r)
+ } else {
+ keep = append(keep, r)
+ }
+ }
+ ho.held = keep
+ for _, r := range hs {
+ ho.finish(r.First, r, res)
+ }
+}
+
+// ---- the timers: apps, bounds, waits ----
+
+func (ho *hoWorld) timers() {
+ for _, nd := range ho.nodes {
+ ho.fold(nd) // the change index: a fold that can succeed does
+ }
+ var doneApps []*hoApp
+ keep := ho.inApp[:0]
+ for _, a := range ho.inApp {
+ if ho.sec >= a.until {
+ doneApps = append(doneApps, a)
+ } else {
+ keep = append(keep, a)
+ }
+ }
+ ho.inApp = keep
+ for _, a := range doneApps {
+ ho.write(ho.A, a.r.Host)
+ ho.finish(a.r.First, a.r, "app")
+ }
+ var expired []*hoReq
+ hk := ho.held[:0]
+ for _, r := range ho.held {
+ if ho.latch[r.Host] {
+ ho.fail("FA", "request %d is held on A for %s, whose lease A lost", r.ID, r.Host)
+ }
+ if ho.sec >= r.HeldAt+r.Bound {
+ expired = append(expired, r)
+ } else {
+ hk = append(hk, r)
+ }
+ }
+ ho.held = hk
+ for _, r := range expired {
+ ho.event("ho-hold-bound")
+ ho.finish(r.First, r, "today")
+ }
+ var ready []*hoWait
+ wk := ho.waiting[:0]
+ for _, x := range ho.waiting {
+ if ho.ready[x.b][x.r.Host] <= ho.sec {
+ ready = append(ready, x)
+ } else {
+ wk = append(wk, x)
+ }
+ }
+ ho.waiting = wk
+ for _, x := range ready {
+ if e := x.b.Entries[x.r.Host]; e == nil || !ho.live(x.b) {
+ ho.finish(x.r.First, x.r, "today")
+ continue
+ }
+ ho.finish(x.r.First, x.r, ho.serve(x.b, x.r))
+ }
+}
+
+// ---- A's agent ----
+
+// loseLease is a failed renewal's latch on A for h (F-A, §6.7): the
+// activator stops the instance; the lock still names A.
+func (ho *hoWorld) loseLease(h string) bool {
+ A := ho.A
+ if A.Entries[h] == nil || ho.latch[h] || !ho.live(A) {
+ return false
+ }
+ ho.latch[h] = true
+ ho.event("ho-lease-loss")
+ ho.logf("A loses its lease of %s", h)
+ if on("hold-after-loss") {
+ ho.endHolds(h, "fa")
+ }
+ ho.cutApp(h, "lease lost")
+ ho.w.stopMain(A, h)
+ delete(A.Entries, h)
+ return true
+}
+
+// agentDown is A's agent dying (crash or reboot): its memory goes, so the
+// drain is void (H5); held and running requests lose their connections.
+func (ho *hoWorld) agentDown(reboot bool) {
+ A := ho.A
+ ho.w.crash(A)
+ ho.draining, ho.gate = false, false
+ ho.moves = map[string]*hoMove{}
+ ho.latch = map[string]bool{}
+ ho.lockRead = map[string]hoLockRead{}
+ ho.endHolds("", "reset")
+ apps := ho.inApp
+ ho.inApp = nil
+ for _, a := range apps {
+ ho.finish(a.r.First, a.r, "reset")
+ }
+ wk := ho.waiting[:0]
+ var lost []*hoWait
+ for _, x := range ho.waiting {
+ if x.b == A || x.r.First == ho.nodeOf[A] {
+ lost = append(lost, x)
+ } else {
+ wk = append(wk, x)
+ }
+ }
+ ho.waiting = wk
+ for _, x := range lost {
+ ho.finish(x.r.First, x.r, "reset")
+ }
+ if reboot {
+ ho.fence = "" // /run is a tmpfs
+ }
+ switch ho.phase {
+ case "withdraw", "quiesce", "move", "conn":
+ ho.drainFail("the agent restarted")
+ }
+}
+
+// agentUp starts a new incarnation of A's agent: not draining, behind the
+// fence if one is present; it publishes a fresh edges file.
+func (ho *hoWorld) agentUp() {
+ ho.w.restart(ho.A, true)
+ ho.publish(hoPub{}, nil)
+ ho.logf("A's agent is pid %d (fence %q)", ho.A.PID, ho.fence)
+}
+
+func (ho *hoWorld) drainFail(why string) {
+ ho.failures = append(ho.failures, why)
+ ho.event("ho-drain-failed")
+ ho.logf("the drain fails: %s", why)
+ ho.endHolds("", "today")
+ for _, m := range ho.moves {
+ if m.State == "holding" || m.State == "releasing" {
+ m.State, m.Stage = "failed", "done"
+ }
+ }
+ ho.report = &hoReport{Inc: ho.A.PID, OK: false, Step: "move"}
+ ho.next("failed")
+}
+
+func (ho *hoWorld) next(phase string) {
+ ho.logf("phase %s -> %s", ho.phase, phase)
+ ho.phase, ho.phaseAt = phase, ho.sec
+}
+
+// awakeOnA lists A's awake hosts in name order.
+func (ho *hoWorld) awakeOnA() []string {
+ var hs []string
+ for _, h := range ho.w.hosts {
+ if ho.A.Entries[h] != nil {
+ hs = append(hs, h)
+ }
+ }
+ return hs
+}
+
+// stepMoves runs the moves (§25.4 step 3) and reports whether all ended.
+func (ho *hoWorld) stepMoves() bool {
+ A := ho.A
+ active := 0
+ for _, m := range ho.moves {
+ if m.Stage != "done" {
+ active++
+ }
+ }
+ for _, h := range ho.awakeOnA() {
+ if active >= hoWidth {
+ break
+ }
+ if ho.moves[h] != nil || ho.latch[h] {
+ continue
+ }
+ ho.moves[h] = &hoMove{Host: h, State: "holding", Stage: "inflight", At: ho.sec}
+ ho.event("ho-move-start")
+ ho.logf("A holds %s", h)
+ active++
+ }
+ hs := make([]string, 0, len(ho.moves))
+ for h := range ho.moves {
+ hs = append(hs, h)
+ }
+ sort.Strings(hs)
+ for _, h := range hs {
+ ho.stepMove(ho.moves[h])
+ }
+ for _, m := range ho.moves {
+ if m.Stage != "done" {
+ return false
+ }
+ }
+ for _, h := range ho.awakeOnA() {
+ if ho.moves[h] == nil && !ho.latch[h] {
+ return false
+ }
+ }
+ return len(A.Pending) == 0 || !on("report-before-quiescence")
+}
+
+func (ho *hoWorld) moveFail(m *hoMove, why string) {
+ m.State, m.Stage = "failed", "done"
+ ho.failures = append(ho.failures, m.Host+": "+why)
+ ho.event("ho-move-failed")
+ ho.logf("the move of %s fails: %s", m.Host, why)
+ ho.endHolds(m.Host, "today")
+}
+
+func (ho *hoWorld) stepMove(m *hoMove) {
+ A, w, h, k := ho.A, ho.w, m.Host, &ho.k
+ if m.Stage == "done" {
+ return
+ }
+ if ho.latch[h] {
+ ho.moveFail(m, "the lease was lost; no marker")
+ return
+ }
+ switch m.Stage {
+ case "inflight":
+ if ho.tickets(h) > 0 && ho.sec-m.At < hoInflight {
+ return
+ }
+ ho.cutApp(h, "the move's stop")
+ m.State, m.Stage, m.ReleaseAt = "releasing", "release", ho.sec+1+k.ReleaseLat[h]
+ case "release":
+ if ho.sec < m.ReleaseAt {
+ return
+ }
+ e := A.Entries[h]
+ if e == nil {
+ ho.moveFail(m, "nothing to release")
+ return
+ }
+ if e.Releasing == nil {
+ w.sleep(A, h, k.Release[h])
+ }
+ if A.Entries[h] != nil {
+ if ho.sec-m.ReleaseAt > 30 {
+ ho.moveFail(m, "the release is held")
+ }
+ return
+ }
+ v := w.view(h)
+ if v.Absent || v.Lock.Release == nil || v.Lock.Release.Box != A.Self.Ref {
+ ho.moveFail(m, "left without a marker")
+ return
+ }
+ if !v.Lock.Release.Clean {
+ ho.unclean = true
+ ho.event("ho-unclean-release")
+ }
+ m.Stage, m.At = "take", ho.sec
+ ho.startTake(m)
+ case "take":
+ if ho.sec < m.AnswerAt {
+ return
+ }
+ v := w.view(h)
+ holder := ho.leaseOwner(v)
+ if m.Timeout {
+ // ruling 72: one coalesced re-read; a non-draining in-view owner is the confirmed holder
+ ho.event("ho-take-timeout")
+ }
+ if holder == nil || holder == A || !ho.live(holder) {
+ ho.moveFail(m, "the take names no holder")
+ return
+ }
+ m.Holder, m.Gen, m.State, m.Stage = holder.Self.Ref, v.Lock.Generation, "taken", "done"
+ ho.event("ho-moved")
+ if holder != m.Succ {
+ ho.event("ho-take-lost-race")
+ }
+ ho.logf("%s is taken by %s (gen %d)", h, m.Holder, m.Gen)
+ ho.releaseHolds(h, holder)
+ }
+}
+
+// startTake sends the take (§25.7) to the roomiest eligible successor.
+func (ho *hoWorld) startTake(m *hoMove) {
+ A, w, h, k := ho.A, ho.w, m.Host, &ho.k
+ if k.Race[h] {
+ // A third box wins the marker: a request it received first.
+ for _, d := range w.boxes {
+ if d != A && ho.live(d) && d.Entries[h] == nil {
+ ho.event("ho-take-raced")
+ ho.logf("box%d wakes %s first: %s", d.ID, h, w.wake(d, h, wakeOpts{}, nil))
+ break
+ }
+ }
+ }
+ var succ *box
+ for _, x := range w.boxes {
+ if x == A || !ho.live(x) || x.Entries[h] != nil {
+ continue
+ }
+ if succ == nil || len(x.Entries) < len(succ.Entries) {
+ succ = x
+ }
+ }
+ m.Succ = succ
+ m.AnswerAt = ho.sec + 1
+ if succ == nil {
+ return
+ }
+ var res string
+ if !on("take-authorizes-acquire") {
+ res = ho.force(succ, h)
+ } else {
+ res = w.wake(succ, h, wakeOpts{RestoreFails: k.RestoreFails[h]}, nil)
+ }
+ ho.logf("take of %s at box%d: %s", h, succ.ID, res)
+ if res == "served" {
+ lat := k.TakeLat[h]
+ ho.ready[succ][h] = ho.sec + lat
+ if lat > hoTakeWait {
+ m.AnswerAt, m.Timeout = ho.sec+hoTakeWait, true
+ } else {
+ m.AnswerAt = ho.sec + max(lat, 1)
+ }
+ }
+}
+
+// releaseHolds releases h's held requests to the confirmed holder (§25.5).
+func (ho *hoWorld) releaseHolds(h string, holder *box) {
+ var hs []*hoReq
+ keep := ho.held[:0]
+ for _, r := range ho.held {
+ if r.Host == h {
+ hs = append(hs, r)
+ } else {
+ keep = append(keep, r)
+ }
+ }
+ ho.held = keep
+ for _, r := range hs {
+ ho.event("ho-hold-released")
+ if r.HeldHop {
+ ho.finish(r.First, r, "handover:"+holder.Self.Ref)
+ continue
+ }
+ ho.send(ho.nodeOf[ho.A], r, holder, "front")
+ }
+}
+
+// ---- the group and the provider (§25.6, H4) ----
+
+func (ho *hoWorld) inServiceCount() int {
+ n := 0
+ for _, b := range ho.w.boxes {
+ if ho.inService[b] && !ho.w.isTerminated(b) {
+ n++
+ }
+ }
+ return n
+}
+
+// react is the group matching desired: a scale-in terminates an InService
+// instance of its choice (the fake provider picks one other than A).
+func (ho *hoWorld) react() {
+ for ho.inServiceCount() > ho.desired {
+ var victim *box
+ for _, b := range ho.w.boxes {
+ if ho.inService[b] && !ho.w.isTerminated(b) && b != ho.A {
+ victim = b
+ break
+ }
+ }
+ if victim == nil {
+ return
+ }
+ ho.fail("I11", "the group terminated box%d, which the transaction did not target (desired %d)", victim.ID, ho.desired)
+ ho.lockFree(victim, "the group's scale-in")
+ ho.w.terminate(victim)
+ delete(ho.inService, victim)
+ }
+ if ho.inServiceCount() < ho.desired {
+ ho.event("ho-replacement-launched")
+ }
+}
+
+// lockFree is I11 at a provider action on x.
+func (ho *hoWorld) lockFree(x *box, what string) {
+ for _, h := range ho.w.hosts {
+ if namesBox(ho.w.view(h), x) {
+ ho.fail("I11", "%s runs while a lease of %s names box%d (lock %s)", what, h, x.ID, ho.w.lockString(h))
+ }
+ }
+ for h := range x.Pending {
+ ho.fail("I11", "%s runs while an acquire of %s on box%d is in flight", what, h, x.ID)
+ }
+}
+
+// lockSweep is the tool's re-read (§25.6 step 4): every lock naming A must
+// be a marker or have another owner.
+func (ho *hoWorld) lockSweep() bool {
+ ok := true
+ for _, h := range ho.w.hosts {
+ if namesBox(ho.w.view(h), ho.A) {
+ ok = false
+ }
+ }
+ return ok
+}
+
+// liftOK: the tool lifts the fence only on a proven observation.
+func liftOK(obs, proven string) bool {
+ return obs == proven || obs == "unknown" && !on("fence-lift-on-unknown")
+}
+
+// ---- the transaction ----
+
+func (ho *hoWorld) txnStep() {
+ A, k := ho.A, &ho.k
+ el := ho.sec - ho.phaseAt
+ switch ho.phase {
+ case "before":
+ if ho.sec >= k.Start {
+ ho.minimum = ho.n - 1
+ ho.next("standby")
+ }
+ case "standby":
+ if el >= 1 {
+ // H4: EnterStandby of A with decrement is the one call that lowers desired.
+ ho.standby, ho.desired = true, ho.desired-1
+ delete(ho.inService, A)
+ ho.react()
+ ho.event("ho-standby")
+ if k.PendingAtDrain {
+ ho.beginPending()
+ }
+ ho.draining, ho.drainInc = true, A.PID
+ ho.publish(hoPub{Draining: true}, k.AckDelay)
+ ho.next("withdraw")
+ }
+ case "withdraw":
+ done, failed := ho.acks()
+ if failed {
+ ho.event("ho-drain-failed-ack")
+ ho.drainFail("an acknowledgement is missing")
+ return
+ }
+ if done {
+ ho.fence = ho.txn
+ ho.gate = true
+ ho.event("ho-withdrawn")
+ ho.next("quiesce")
+ }
+ case "quiesce":
+ if !on("report-before-quiescence") {
+ ho.next("move")
+ return
+ }
+ if len(A.Pending) > 0 && el < k.PendingFor {
+ return
+ }
+ hs := make([]string, 0, len(A.Pending))
+ for h := range A.Pending {
+ hs = append(hs, h)
+ }
+ sort.Strings(hs)
+ for _, h := range hs {
+ pd := A.Pending[h]
+ delete(A.Pending, h)
+ ho.event("ho-pending-settled")
+ ho.logf("A settles its pending acquire of %s: %s", h, ho.w.wake(A, h, wakeOpts{}, pd))
+ }
+ ho.next("move")
+ case "move":
+ if ho.sec-ho.phaseAt > 900+60*len(ho.w.hosts)/20 {
+ ho.drainFail("the drain deadline passed")
+ return
+ }
+ if !ho.stepMoves() {
+ return
+ }
+ if len(ho.failures) > 0 {
+ ho.drainFail("a move failed")
+ return
+ }
+ ho.connOpen = false
+ ho.publish(hoPub{Draining: true, Drained: true}, k.Ack2Delay)
+ ho.next("conn")
+ case "conn":
+ done, failed := ho.acks()
+ if failed {
+ ho.event("ho-drain-failed-ack")
+ ho.drainFail("an acknowledgement of drained is missing")
+ return
+ }
+ if !done {
+ return
+ }
+ // A's forwards still waiting on a restoring holder, up to 60 s.
+ inflight := false
+ for _, x := range ho.waiting {
+ if x.r.First == ho.nodeOf[A] {
+ inflight = true
+ }
+ }
+ if inflight && el < hoConnBound {
+ return
+ }
+ ho.closeForwards()
+ // EndDrainMoves: the redirects go once drained is acknowledged.
+ for h, m := range ho.moves {
+ if m.State == "taken" {
+ delete(ho.moves, h)
+ }
+ }
+ ho.report = &hoReport{Inc: A.PID, OK: !ho.unclean && len(ho.failures) == 0, Step: "move"}
+ if !ho.report.OK {
+ ho.drainFail("an unclean release")
+ return
+ }
+ ho.event("ho-drained")
+ ho.next("report")
+ case "report":
+ if k.Reboot >= 0 && el == k.Reboot && ho.live(A) {
+ ho.event("ho-reboot")
+ ho.agentDown(true)
+ ho.agentUp()
+ }
+ if el < k.ReportDelay {
+ return
+ }
+ ho.next("precheck")
+ ho.txnStep()
+ case "precheck":
+ if on("action-on-stale-report") {
+ ok := ho.report != nil && ho.report.OK && ho.live(A) && A.PID == ho.report.Inc &&
+ ho.draining && ho.drainInc == A.PID && ho.fence == ho.txn
+ ok = ho.lockSweep() && ok
+ if !ok {
+ ho.event("ho-precheck-refused")
+ ho.drainFail("the pre-action check failed")
+ return
+ }
+ }
+ if k.Kind == "roll" {
+ ho.next("apply")
+ } else {
+ ho.next("edge-stop")
+ }
+ ho.txnStep()
+ case "apply":
+ // roll: apply restarts the edge behind the fence.
+ ho.lockFree(A, "roll's apply")
+ ho.event("ho-roll-applied")
+ ho.agentDown(false)
+ ho.agentUp()
+ ho.next("exit")
+ case "exit":
+ if el >= 1 {
+ ho.standby, ho.desired = false, ho.desired+1
+ ho.inService[A] = true
+ ho.next("fence-clear")
+ }
+ case "fence-clear":
+ if el >= 1 {
+ ho.fence = ""
+ ho.minimum = ho.n
+ ho.react()
+ ho.next("done")
+ }
+ case "edge-stop":
+ ho.lockFree(A, "the edge stop")
+ ho.edgeStop()
+ if ho.stopAnswer != "proven" || ho.fence != ho.txn {
+ ho.event("ho-edge-stop-unproven")
+ ho.next("done") // the tool alerts and holds A, stopped and fenced, in Standby
+ return
+ }
+ ho.next("terminate")
+ case "terminate":
+ if el < 1 {
+ return
+ }
+ ho.lockFree(A, "the terminate's dispatch")
+ dec := !on("desired-lowered-elsewhere")
+ if dec {
+ ho.desired--
+ ho.react()
+ }
+ ho.event("ho-terminate-dispatched")
+ ho.next("watch")
+ case "watch":
+ if k.EdgeRestart >= 0 && el == k.EdgeRestart && A.Agent == agentDown && !ho.w.isTerminated(A) {
+ ho.event("ho-edge-restart")
+ ho.agentUp()
+ }
+ if el >= 1 && el < k.Land && ho.fence != "" && liftOK(k.Poll, "terminated") {
+ ho.event("ho-fence-lifted-early")
+ ho.fence = ""
+ }
+ if el < k.Land {
+ return
+ }
+ ho.lockFree(A, "the terminate as it lands")
+ ho.w.terminate(A)
+ delete(ho.inService, A)
+ ho.fence = "" // moot: it lived in the member's /run
+ if k.Kind == "replace" {
+ ho.desired, ho.minimum = ho.n, ho.n
+ ho.event("ho-replaced")
+ } else {
+ ho.minimum = ho.n - 1
+ ho.event("ho-removed")
+ }
+ ho.react()
+ ho.next("done")
+ case "failed":
+ if el < 1 {
+ return
+ }
+ if ho.standby {
+ ho.standby, ho.desired = false, ho.desired+1
+ ho.inService[A] = true
+ }
+ ho.minimum = ho.n
+ ho.react()
+ if k.Cancel {
+ ho.next("cancel")
+ } else {
+ ho.next("done")
+ }
+ case "cancel":
+ if el < 5 {
+ return
+ }
+ ho.cancel()
+ ho.next("done")
+ }
+}
+
+// edgeStop is the tool's stop of carlos-edge.service under the fence
+// (R3.1), with its answer.
+func (ho *hoWorld) edgeStop() {
+ A, w := ho.A, ho.w
+ stopped := ho.k.Stop == "proven" || ho.k.Stop == "unknown-stopped"
+ if stopped && ho.live(A) {
+ // The edge's shutdown (T1) releases what is awake; an acquire whose
+ // PUT is in flight lands with no process behind it.
+ for _, h := range ho.awakeOnA() {
+ if A.Entries[h].Releasing == nil {
+ w.sleep(A, h, sleepOpts{})
+ }
+ }
+ for h, pd := range A.Pending {
+ w.take(A, h, pd.View, true)
+ delete(A.Pending, h)
+ }
+ ho.agentDown(false)
+ A.Units = map[string][]*unit{}
+ ho.edgeStopped = true
+ }
+ switch ho.k.Stop {
+ case "proven":
+ ho.stopAnswer = "proven"
+ case "running":
+ ho.stopAnswer = "running"
+ default:
+ ho.stopAnswer = "unknown"
+ }
+ ho.logf("the edge stop answers %s", ho.stopAnswer)
+}
+
+// cancel is drain --cancel after a failed drain.
+func (ho *hoWorld) cancel() {
+ ho.event("ho-cancel")
+ if ho.live(ho.A) {
+ ho.draining, ho.gate = false, false
+ ho.moves = map[string]*hoMove{}
+ ho.publish(hoPub{}, nil)
+ ho.fence = ""
+ return
+ }
+ if liftOK(ho.k.Probe, "absent") {
+ ho.fence = ""
+ }
+}
+
+// closeForwards cuts A's forwards still open at the connection drain's bound.
+func (ho *hoWorld) closeForwards() {
+ wk := ho.waiting[:0]
+ var cut []*hoWait
+ for _, x := range ho.waiting {
+ if x.r.First == ho.nodeOf[ho.A] {
+ cut = append(cut, x)
+ } else {
+ wk = append(wk, x)
+ }
+ }
+ ho.waiting = wk
+ for _, x := range cut {
+ ho.event("ho-cut")
+ ho.finish(x.r.First, x.r, "cut")
+ }
+}
+
+// ---- the clock ----
+
+// second is one second: the clock, the timers, the transaction, then I1's
+// state check.
+func (ho *hoWorld) second(background func()) {
+ ho.sec++
+ w := ho.w
+ if ho.sec%60 == 0 {
+ w.requestOffset = 0
+ w.advance(1)
+ } else {
+ w.requestOffset = time.Duration(ho.sec%60) * time.Second
+ }
+ if ho.k.Restart >= 0 && ho.sec == ho.k.Restart && ho.live(ho.A) && ho.phase != "done" {
+ ho.event("ho-agent-restart")
+ ho.agentDown(false)
+ }
+ if ho.k.Restart >= 0 && ho.sec == ho.k.Restart+ho.k.RestartDown && ho.A.Agent == agentDown && !w.isTerminated(ho.A) && !ho.edgeStopped {
+ ho.agentUp()
+ }
+ ho.timers()
+ if ho.phase != "done" {
+ ho.txnStep()
+ }
+ if background != nil {
+ background()
+ }
+ w.check()
+}
+
+// settle runs the clock with no new requests until every request is
+// answered, then I10's last half: nothing is left unanswered.
+func (ho *hoWorld) settle() {
+ for i := 0; i < 200 && (len(ho.held) > 0 || len(ho.inApp) > 0 || len(ho.waiting) > 0 || ho.phase != "done"); i++ {
+ ho.second(nil)
+ }
+ for _, r := range ho.reqs {
+ if !r.Answered {
+ ho.fail("I10", "request %d for %s was never answered (held at %d)", r.ID, r.Host, r.HeldAt)
+ }
+ }
+}
+
+// ---- the random walk ----
+
+func (ho *hoWorld) pickHost() string { return ho.w.hosts[ho.rng.Intn(len(ho.w.hosts))] }
+
+func (ho *hoWorld) pickBody() string {
+ switch n := ho.rng.Intn(100); {
+ case n < 50:
+ return "none"
+ case n < 75:
+ return "small"
+ case n < 90:
+ return "large"
+ }
+ return "unknown"
+}
+
+// peer is a random live region box other than A.
+func (ho *hoWorld) peer() *box {
+ var ps []*box
+ for _, b := range ho.w.boxes {
+ if b != ho.A && ho.live(b) {
+ ps = append(ps, b)
+ }
+ }
+ if len(ps) == 0 {
+ return nil
+ }
+ return ps[ho.rng.Intn(len(ps))]
+}
+
+type hoAction struct {
+ name string
+ weight int
+ run func(*hoWorld) bool
+}
+
+var hoActions = []hoAction{
+ // a client request through the NLB, at a region box other than A
+ {"ho-request", 30, func(ho *hoWorld) bool {
+ p, h, body, work := ho.peer(), ho.pickHost(), ho.pickBody(), ho.rng.Intn(12)
+ if p == nil {
+ return false
+ }
+ ho.arrive(ho.req("client", ho.nodeOf[p], h, body, work))
+ return true
+ }},
+ // a request at a region box for a host no box holds: a cold wake
+ {"ho-cold-request", 6, func(ho *hoWorld) bool {
+ p, body, work := ho.peer(), ho.pickBody(), ho.rng.Intn(12)
+ if p == nil {
+ return false
+ }
+ var cold []string
+ for _, h := range ho.w.hosts {
+ if ho.leaseOwner(ho.w.view(h)) == nil && !ho.w.holds(h) {
+ cold = append(cold, h)
+ }
+ }
+ if len(cold) == 0 {
+ return false
+ }
+ ho.arrive(ho.req("client", ho.nodeOf[p], cold[len(ho.reqs)%len(cold)], body, work))
+ return true
+ }},
+ // a client request on a keep-alive connection to A opened before Standby
+ {"ho-direct", 10, func(ho *hoWorld) bool {
+ h, body, work, marked := ho.pickHost(), ho.pickBody(), ho.rng.Intn(12), ho.rng.Intn(3) == 0
+ if !ho.connOpen || !ho.live(ho.A) {
+ return false
+ }
+ kind := "client"
+ if marked {
+ kind = "marked"
+ }
+ ho.arrive(ho.req(kind, ho.nodeOf[ho.A], h, body, work))
+ return true
+ }},
+ // a marked held-stream request (an SSE reconnect) at a region box
+ {"ho-marked", 5, func(ho *hoWorld) bool {
+ p, h, work := ho.peer(), ho.pickHost(), ho.rng.Intn(12)
+ if p == nil {
+ return false
+ }
+ ho.arrive(ho.req("marked", ho.nodeOf[p], h, "none", work))
+ return true
+ }},
+ // a request whose first box is in another region (backhaul)
+ {"ho-remote", 8, func(ho *hoWorld) bool {
+ h, body, work := ho.pickHost(), ho.pickBody(), ho.rng.Intn(12)
+ ho.arrive(ho.req("client", ho.remote, h, body, work))
+ return true
+ }},
+ // a stale holder-cache entry: a node caches a box that does not hold h
+ {"ho-stale-cache", 4, func(ho *hoWorld) bool {
+ nd, h, x := ho.nodes[ho.rng.Intn(len(ho.nodes))], ho.pickHost(), ho.w.boxes[ho.rng.Intn(len(ho.w.boxes))]
+ if x == nd.b || x.Entries[h] != nil {
+ return false
+ }
+ nd.cache[h] = x.Self.Ref
+ return true
+ }},
+ // a node folds A's edges file (the change index)
+ {"ho-fold", 10, func(ho *hoWorld) bool {
+ return ho.fold(ho.nodes[ho.rng.Intn(len(ho.nodes))])
+ }},
+ // a holder other than A sleeps a host (the successor sleeping, R3.4)
+ {"ho-holder-sleeps", 3, func(ho *hoWorld) bool {
+ p, h := ho.peer(), ho.pickHost()
+ if p == nil || p.Entries[h] == nil || p.Entries[h].Releasing != nil || ho.ready[p][h] > ho.sec {
+ return false
+ }
+ ho.w.sleep(p, h, sleepOpts{})
+ return true
+ }},
+ // a box other than A wakes a host (a race with a take or a redirect)
+ {"ho-third-box", 3, func(ho *hoWorld) bool {
+ p, h := ho.peer(), ho.pickHost()
+ if p == nil || p.Entries[h] != nil || p.Pending[h] != nil || ho.leaseOwner(ho.w.view(h)) != nil {
+ return false
+ }
+ ho.event("ho-third-box-wake")
+ ho.logf("box%d wakes %s: %s", p.ID, h, ho.w.wake(p, h, wakeOpts{}, nil))
+ return true
+ }},
+ // an acquire on A between its GET and its PUT (a wake in flight)
+ {"ho-wake-begin", 3, func(ho *hoWorld) bool {
+ if !ho.live(ho.A) || ho.gate || ho.fence != "" {
+ return false
+ }
+ return ho.beginPending()
+ }},
+ {"ho-wake-finish", 3, func(ho *hoWorld) bool {
+ A, h := ho.A, ho.pickHost()
+ pd := A.Pending[h]
+ if pd == nil || ho.draining || !ho.live(A) {
+ return false
+ }
+ delete(A.Pending, h)
+ ho.logf("A's pending acquire of %s: %s", h, ho.w.wake(A, h, wakeOpts{}, pd))
+ return true
+ }},
+ // a reset after a send, on a node's next hop
+ {"ho-reset", 3, func(ho *hoWorld) bool {
+ ho.nodes[ho.rng.Intn(len(ho.nodes))].reset = true
+ return true
+ }},
+ // a dial failure before a send, on a node's next hop
+ {"ho-dial", 2, func(ho *hoWorld) bool {
+ ho.nodes[ho.rng.Intn(len(ho.nodes))].dial = true
+ return true
+ }},
+ // A loses a lease mid-move (F-A)
+ {"ho-lease-loss", 3, func(ho *hoWorld) bool {
+ h, moving := ho.pickHost(), ho.rng.Intn(10) < 7
+ if ho.phase != "move" {
+ return false
+ }
+ if moving {
+ for _, x := range ho.w.hosts {
+ if m := ho.moves[x]; m != nil && m.State == "holding" {
+ h = x
+ }
+ }
+ }
+ return ho.loseLease(h)
+ }},
+ // a node still caches A for a host (a peer that did not drop A yet)
+ {"ho-cache-names-a", 4, func(ho *hoWorld) bool {
+ nd, h := ho.nodes[1+ho.rng.Intn(len(ho.nodes)-1)], ho.pickHost()
+ nd.cache[h] = ho.A.Self.Ref
+ return true
+ }},
+ // the successor of a taken host sleeps it (R3.4)
+ {"ho-successor-sleeps", 4, func(ho *hoWorld) bool {
+ h := ho.pickHost()
+ m := ho.moves[h]
+ if m == nil || m.State != "taken" {
+ return false
+ }
+ y := ho.w.boxRef(m.Holder)
+ if !ho.live(y) || y.Entries[h] == nil || y.Entries[h].Releasing != nil || ho.ready[y][h] > ho.sec {
+ return false
+ }
+ ho.event("ho-successor-slept")
+ ho.w.sleep(y, h, sleepOpts{})
+ return true
+ }},
+ {"ho-idle", 15, func(ho *hoWorld) bool { return true }},
+}
+
+func (ho *hoWorld) background() {
+ total := 0
+ for _, a := range hoActions {
+ total += a.weight
+ }
+ n := ho.rng.Intn(total)
+ for _, a := range hoActions {
+ if n < a.weight {
+ ho.stats[a.name]++
+ if a.run(ho) {
+ ho.done[a.name]++
+ }
+ ho.w.check()
+ return
+ }
+ n -= a.weight
+ }
+}
+
+// randomKnobs draws one transaction's faults.
+func randomKnobs(rng *rand.Rand, n int, hosts []string, nodes []string) hoKnobs {
+ k := hoKnobs{
+ Start: rng.Intn(20), AckDelay: map[string]int{}, Ack2Delay: map[string]int{},
+ Release: map[string]sleepOpts{}, ReleaseLat: map[string]int{}, TakeLat: map[string]int{},
+ Race: map[string]bool{}, RestoreFails: map[string]bool{},
+ PendingFor: 1 + rng.Intn(3), ReportDelay: 1 + rng.Intn(10), Reboot: -1, Restart: -1,
+ Land: 2 + rng.Intn(20), EdgeRestart: -1, Poll: "running", Probe: "absent",
+ }
+ switch x := rng.Intn(10); {
+ case x < 4:
+ k.Kind = "roll"
+ case x < 8 || n < 3:
+ k.Kind = "replace"
+ default:
+ k.Kind = "remove"
+ }
+ ackFault := rng.Intn(100)
+ for _, nd := range nodes {
+ k.AckDelay[nd], k.Ack2Delay[nd] = rng.Intn(3), rng.Intn(3)
+ if ackFault < 25 && rng.Intn(2) == 0 {
+ k.AckDelay[nd] = 6 + rng.Intn(80) // slow
+ }
+ if ackFault < 25 && rng.Intn(3) == 0 {
+ k.Ack2Delay[nd] = 6 + rng.Intn(80)
+ }
+ if ackFault >= 25 && ackFault < 30 && rng.Intn(2) == 0 {
+ k.AckDelay[nd] = -1 // missing
+ }
+ }
+ for _, h := range hosts {
+ k.ReleaseLat[h] = rng.Intn(3)
+ k.TakeLat[h] = 1 + rng.Intn(8)
+ if rng.Intn(10) == 0 {
+ k.TakeLat[h] = 30 + rng.Intn(20) // slow restores, some past the take wait
+ }
+ k.Race[h] = rng.Intn(5) == 0
+ k.RestoreFails[h] = rng.Intn(25) == 0
+ switch rng.Intn(30) {
+ case 0:
+ k.Release[h] = sleepOpts{MarkerFails: true}
+ case 1:
+ k.Release[h] = sleepOpts{SyncFails: true}
+ case 2:
+ k.Release[h] = sleepOpts{FinalIncomplete: true}
+ }
+ }
+ if rng.Intn(10) == 0 {
+ k.Restart = 20 + rng.Intn(300)
+ k.RestartDown = rng.Intn(20)
+ }
+ if rng.Intn(4) == 0 {
+ k.Reboot = rng.Intn(k.ReportDelay)
+ k.ReportDelay += 10
+ }
+ switch x := rng.Intn(20); {
+ case x == 0:
+ k.Stop = "running"
+ case x == 1:
+ k.Stop = "unknown-stopped"
+ case x == 2:
+ k.Stop = "unknown-running"
+ default:
+ k.Stop = "proven"
+ }
+ if rng.Intn(2) == 0 {
+ k.Land += 10
+ k.EdgeRestart = 1 + rng.Intn(3)
+ }
+ if rng.Intn(2) == 0 {
+ k.Poll = "unknown"
+ }
+ k.Cancel = rng.Intn(2) == 0
+ if rng.Intn(2) == 0 {
+ k.Probe = "unknown"
+ }
+ k.LocalRace = rng.Intn(3) == 0
+ k.PendingAtDrain = rng.Intn(3) == 0
+ return k
+}
+
+// runHandoverScenario is one seed's transaction, merged into the parent's
+// events, violations and trace.
+func runHandoverScenario(parent *world, seed int64) {
+ ho := newRandomHO(seed)
+ ho.run()
+ for k, v := range ho.w.events {
+ parent.events[k] += v
+ }
+ for k, v := range ho.done {
+ parent.done[k] += v
+ }
+ for k, v := range ho.stats {
+ parent.stats[k] += v
+ }
+ parent.violations = append(parent.violations, ho.w.violations...)
+ if parent.verbose {
+ parent.trace = append(parent.trace, ho.w.trace...)
+ }
+}
+
+func newRandomHO(seed int64) *hoWorld {
+ rng := rand.New(rand.NewSource(seed*1_000_003 + 17))
+ n := 2 + rng.Intn(4)
+ var hosts []string
+ for i := 0; i < 2+rng.Intn(4); i++ {
+ hosts = append(hosts, fmt.Sprintf("h%d", i+1))
+ }
+ w := newWorldN(seed, rand.New(rand.NewSource(seed)), n, hosts)
+ w.scripted = true
+ var names []string
+ for _, b := range w.boxes {
+ names = append(names, b.Self.Ref)
+ }
+ names = append(names, "remote")
+ ho := newHO(w, rng, randomKnobs(rng, n, hosts, names))
+ ho.setup()
+ return ho
+}
+
+// setup gives each host a state: awake on A (at least one), awake on
+// another box, asleep with A's marker, or never woken; and fills the
+// holder caches.
+func (ho *hoWorld) setup() {
+ w, A := ho.w, ho.A
+ for i, h := range w.hosts {
+ x := ho.rng.Intn(8)
+ if i == 0 {
+ x = 0
+ }
+ switch {
+ case x < 3:
+ w.wake(A, h, wakeOpts{}, nil)
+ case x < 5:
+ w.wake(w.boxes[1+ho.rng.Intn(len(w.boxes)-1)], h, wakeOpts{}, nil)
+ case x < 6:
+ w.wake(A, h, wakeOpts{}, nil)
+ w.sleep(A, h, sleepOpts{})
+ }
+ }
+ for _, nd := range ho.nodes {
+ for _, h := range w.hosts {
+ if o := ho.leaseOwner(w.view(h)); o != nil && o != nd.b && ho.rng.Intn(10) < 6 {
+ nd.cache[h] = o.Self.Ref
+ }
+ }
+ }
+ ho.logf("setup: %d boxes, hosts %v, kind %s, knobs %+v", len(w.boxes), w.hosts, ho.k.Kind, ho.k)
+}
+
+func (ho *hoWorld) run() {
+ for ho.sec < hoMaxSec && ho.phase != "done" {
+ ho.second(ho.background)
+ }
+ for i := 0; i < 60; i++ {
+ ho.second(ho.background)
+ }
+ ho.settle()
+}
diff --git a/internal/sim/regionha/handover_witness_test.go b/internal/sim/regionha/handover_witness_test.go
new file mode 100644
index 000000000..b941d0c8e
--- /dev/null
+++ b/internal/sim/regionha/handover_witness_test.go
@@ -0,0 +1,321 @@
+package regionha
+
+import "testing"
+
+// Witnesses for the planned handover's rules (handover_test.go). Each is
+// one hand-scheduled transaction on the witness world (A, B, C; host shop,
+// plus blog where a scenario needs a second host). It draws nothing from
+// any RNG.
+
+func init() {
+ witnesses = append(witnesses,
+ witness{"take-authorizes-acquire", "take-authorizes-acquire", "I1",
+ "a third box wins A's marker before the successor's take; a take that bypasses DecideAcquire runs the successor beside it", wHOTake},
+ witness{"handover-authorizes-acquire", "handover-authorizes-acquire", "I1",
+ "after C took and slept shop, C's stale hop reaches A; A's redirect names C; B acquires first; C treating the answer as authority runs beside B", wHOHandoverLocal},
+ witness{"movestate-after-gate", "movestate-after-gate", "H1",
+ "a direct request reaches A while shop moves; with the gate before MoveState, A and the holder both run the tenant pipeline", wHOGate},
+ witness{"movestate-skips-marked", "movestate-skips-marked", "H1",
+ "a marked stream request reaches A while shop moves; skipping MoveState lets it into A's app", wHOMarked},
+ witness{"hold-after-loss", "hold-after-loss", "FA",
+ "a request is held for shop when A loses the lease; checking the hold before the latch keeps it held", wHOLoss},
+ witness{"replay-without-copy", "replay-without-copy", "I9",
+ "C's hop with a large body reaches A while shop moves; marked replayable without a copy, it is held, redirected and sent again truncated", wHOCopy},
+ witness{"replay-after-reset", "replay-after-reset", "I9",
+ "C's hop to B resets after B's app ran it; sending it again reaches B's app twice", wHOReset},
+ witness{"handover-on-second-attempt", "handover-on-second-attempt", "I4",
+ "C's stale cache names B; B names A; C's second attempt reaches A while shop moves; a counter the retry paths do not share follows A's handover answer to a third attempt", wHOAttempt},
+ witness{"desired-lowered-elsewhere", "desired-lowered-elsewhere", "I11",
+ "replace: a terminate that also lowers desired makes the group terminate B, which holds shop", wHODesired},
+ witness{"report-before-quiescence", "report-before-quiescence", "I11",
+ "roll: A's acquire of blog is between GET and PUT as the drain starts; a report before it settles lets apply run with it in flight", wHOQuiesce},
+ witness{"action-on-stale-report", "action-on-stale-report", "I11",
+ "roll: A reboots after its report, losing the fence, and acquires blog; acting on the old report applies while a lease names A", wHOStale},
+ witness{"place-before-acks", "place-before-acks", "WD",
+ "C's acknowledgement is slow; a drain that goes on without it closes A's gate while C still places blog on A (§6.3 rule 1)", wHOAcks},
+ witness{"fence-lift-on-unknown", "fence-lift-on-unknown", "I11",
+ "replace: the stopped edge restarts while the terminate is delayed; lifting the fence on an unknown edge state lets it acquire blog before the terminate lands", wHOFence},
+ )
+}
+
+// hoWitness is a scripted transaction of kind on the witness world, with
+// the extra hosts added, prompt acknowledgements and takes, and no faults.
+func hoWitness(w *world, kind string, extra ...string) *hoWorld {
+ for _, h := range extra {
+ w.hosts = append(w.hosts, h)
+ w.s3[h] = &prefix{}
+ w.owed[h] = map[string]bool{}
+ }
+ k := hoKnobs{
+ Kind: kind, AckDelay: map[string]int{}, Ack2Delay: map[string]int{},
+ Release: map[string]sleepOpts{}, ReleaseLat: map[string]int{}, TakeLat: map[string]int{},
+ Race: map[string]bool{}, RestoreFails: map[string]bool{},
+ PendingFor: 1, ReportDelay: 1, Reboot: -1, Restart: -1, Stop: "proven", Land: 3,
+ EdgeRestart: -1, Poll: "running", Probe: "absent",
+ }
+ for _, h := range w.hosts {
+ k.TakeLat[h] = 1
+ }
+ return newHO(w, nil, k)
+}
+
+// until runs seconds, with no background, until cond holds.
+func (ho *hoWorld) until(t *testing.T, what string, cond func() bool) {
+ for i := 0; i < 600; i++ {
+ if cond() {
+ return
+ }
+ ho.second(nil)
+ }
+ t.Errorf("witness: %s never happened", what)
+}
+
+func (ho *hoWorld) state(h string) string {
+ if m := ho.moves[h]; m != nil {
+ return m.State
+ }
+ return ""
+}
+
+func (ho *hoWorld) moving(h string) func() bool {
+ return func() bool { s := ho.state(h); return s == "holding" || s == "releasing" }
+}
+
+// keepMoving puts a long request into A's app for h, so its move waits
+// the whole in-flight drain.
+func (ho *hoWorld) keepMoving(h string) {
+ ho.arrive(ho.req("client", ho.nodeOf[ho.A], h, "none", 30))
+}
+
+func (ho *hoWorld) finishAll() {
+ for i := 0; i < 600 && ho.phase != "done"; i++ {
+ ho.second(nil)
+ }
+ ho.settle()
+}
+
+func wHOTake(t *testing.T, w *world) {
+ A, _, _ := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.k.Race[sh] = true
+ ho.finishAll()
+ n := 0
+ for _, b := range w.boxes {
+ if b.Entries[sh] != nil {
+ n++
+ }
+ }
+ expect(t, "take-authorizes-acquire", n == 1 && w.events["ho-take-lost-race"] == 1, "one box holds %s after a lost race (%d)", sh, n)
+}
+
+func wHOHandoverLocal(t *testing.T, w *world) {
+ A, B, C := w.abc()
+ ho := hoWitness(w, "roll", "blog")
+ w.wake(A, sh, wakeOpts{}, nil)
+ w.wake(B, "blog", wakeOpts{}, nil) // C is the roomiest successor
+ ho.until(t, "the take", func() bool { return ho.state(sh) == "taken" })
+ if C.Entries[sh] == nil {
+ t.Errorf("setup: C did not take %s", sh)
+ return
+ }
+ w.sleep(C, sh, sleepOpts{})
+ ho.nodeOf[C].cache[sh] = A.Self.Ref
+ ho.beforeLocal = func() { w.logf("B wakes %s first: %s", sh, w.wake(B, sh, wakeOpts{}, nil)) }
+ r := ho.req("client", ho.nodeOf[C], sh, "none", 0)
+ ho.arrive(r)
+ expect(t, "handover-authorizes-acquire", r.Answer == "app" && r.Sends == 2 && w.events["ho-handover-local"] == 1, "the redirected request is served by B on its second attempt: %+v", r)
+ ho.finishAll()
+}
+
+func wHOGate(t *testing.T, w *world) {
+ A, _, _ := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the move", ho.moving(sh))
+ r := ho.req("client", ho.nodeOf[A], sh, "none", 0)
+ ho.arrive(r)
+ ho.finishAll()
+ expect(t, "movestate-after-gate", r.Answer == "app" && r.HeldAt >= 0 && r.Pipeline == 1, "the held request is served once: %+v", r)
+}
+
+func wHOMarked(t *testing.T, w *world) {
+ A, _, _ := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the move", ho.moving(sh))
+ r := ho.req("marked", ho.nodeOf[A], sh, "none", 0)
+ ho.arrive(r)
+ ho.finishAll()
+ expect(t, "movestate-skips-marked", r.Answer == "app" && r.HeldAt >= 0, "the marked request is held, then served: %+v", r)
+}
+
+func wHOLoss(t *testing.T, w *world) {
+ A, _, _ := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the drain", func() bool { return ho.phase == "move" || ho.phase == "quiesce" })
+ ho.keepMoving(sh)
+ ho.until(t, "the move", ho.moving(sh))
+ r := ho.req("client", ho.nodeOf[A], sh, "none", 0)
+ ho.arrive(r)
+ ho.loseLease(sh)
+ ho.second(nil)
+ expect(t, "hold-after-loss", r.Answer == "fa" && r.At == r.HeldAt, "the held request gets F-A's answer at once: %+v", r)
+ ho.finishAll()
+}
+
+func wHOCopy(t *testing.T, w *world) {
+ A, _, C := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the drain", func() bool { return ho.phase == "move" || ho.phase == "quiesce" })
+ ho.keepMoving(sh)
+ ho.until(t, "the move", ho.moving(sh))
+ ho.nodeOf[C].cache[sh] = A.Self.Ref
+ r := ho.req("client", ho.nodeOf[C], sh, "large", 0)
+ ho.arrive(r)
+ expect(t, "replay-without-copy", r.Answer == "today" && r.Sends == 1 && len(r.Delivered) == 0, "a large body is refused at once, never held or sent again: %+v", r)
+ ho.finishAll()
+}
+
+func wHOReset(t *testing.T, w *world) {
+ _, B, C := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(B, sh, wakeOpts{}, nil)
+ ho.nodeOf[C].reset = true
+ r := ho.req("client", ho.nodeOf[C], sh, "small", 0)
+ ho.arrive(r)
+ expect(t, "replay-after-reset", r.Answer == "reset" && len(r.Delivered) == 1, "a reset after the send is not sent again: %+v", r)
+ ho.finishAll()
+}
+
+func wHOAttempt(t *testing.T, w *world) {
+ A, B, C := w.abc()
+ ho := hoWitness(w, "roll")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the drain", func() bool { return ho.phase == "move" || ho.phase == "quiesce" })
+ ho.keepMoving(sh)
+ ho.until(t, "the move", ho.moving(sh))
+ ho.nodeOf[C].cache[sh] = B.Self.Ref
+ r := ho.req("client", ho.nodeOf[C], sh, "none", 0)
+ ho.arrive(r)
+ expect(t, "handover-on-second-attempt", r.Answer == "today" && r.Sends == 2 && r.HeldAt < 0, "a second attempt reaching A is answered at once: %+v", r)
+ ho.finishAll()
+}
+
+func wHODesired(t *testing.T, w *world) {
+ A, B, _ := w.abc()
+ ho := hoWitness(w, "replace")
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.finishAll()
+ expect(t, "desired-lowered-elsewhere", w.isTerminated(A) && !w.isTerminated(B) && ho.desired == 3, "only A is terminated and desired is restored (desired %d)", ho.desired)
+}
+
+func wHOQuiesce(t *testing.T, w *world) {
+ A, _, _ := w.abc()
+ ho := hoWitness(w, "roll", "blog")
+ w.wake(A, sh, wakeOpts{}, nil)
+ if !ho.beginPending() || A.Pending["blog"] == nil {
+ t.Errorf("setup: no pending acquire of blog on A")
+ }
+ ho.finishAll()
+ expect(t, "report-before-quiescence", w.events["ho-pending-settled"] == 1 && w.events["ho-moved"] == 2, "the pending acquire settles and both hosts move")
+}
+
+func wHOStale(t *testing.T, w *world) {
+ A, _, C := w.abc()
+ ho := hoWitness(w, "roll", "blog")
+ ho.k.ReportDelay = 5
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the report", func() bool { return ho.phase == "report" })
+ ho.agentDown(true)
+ ho.agentUp()
+ ho.second(nil)
+ r := ho.req("client", ho.nodeOf[C], "blog", "none", 0)
+ ho.arrive(r)
+ ho.finishAll()
+ expect(t, "action-on-stale-report", w.events["ho-precheck-refused"] == 1 && w.events["ho-roll-applied"] == 0, "the pre-action check refuses after the reboot")
+}
+
+func wHOAcks(t *testing.T, w *world) {
+ A, _, C := w.abc()
+ ho := hoWitness(w, "roll", "blog")
+ ho.k.AckDelay[C.Self.Ref] = 30
+ w.wake(A, sh, wakeOpts{}, nil)
+ w.wake(A, "blog", wakeOpts{}, nil)
+ w.sleep(A, "blog", sleepOpts{})
+ ho.until(t, "the withdrawal", func() bool { return ho.phase == "withdraw" })
+ for i := 0; i < 4; i++ {
+ ho.second(nil)
+ }
+ r := ho.req("client", ho.nodeOf[C], "blog", "none", 0)
+ ho.arrive(r)
+ ho.finishAll()
+ expect(t, "place-before-acks", r.Answer == "app" && w.events["ho-moved"] == 2, "A acquires blog before its gate closes and moves it: %+v", r)
+}
+
+func wHOFence(t *testing.T, w *world) {
+ A, _, C := w.abc()
+ ho := hoWitness(w, "replace", "blog")
+ ho.k.Land, ho.k.EdgeRestart, ho.k.Poll = 10, 2, "unknown"
+ w.wake(A, sh, wakeOpts{}, nil)
+ ho.until(t, "the restart", func() bool { return ho.phase == "watch" && ho.sec-ho.phaseAt >= 4 })
+ r := ho.req("client", ho.nodeOf[C], "blog", "none", 0)
+ ho.arrive(r)
+ ho.finishAll()
+ expect(t, "fence-lift-on-unknown", r.Answer == "today" && w.events["ho-start-refused-fenced"] == 1, "the restarted edge is fenced: %+v", r)
+}
+
+// TestHandoverEveryActionFires: over 200 seeds of the unmutated walk every
+// handover action completes, and every path the handover rules guard is
+// reached. ho-handover-not-followed is left out: A answers a second
+// attempt at once (R3.3), so the first box's own H3 check is defence in
+// depth that the unmutated walk cannot reach.
+func TestHandoverEveryActionFires(t *testing.T) {
+ saved := mutated
+ mutated = ""
+ defer func() { mutated = saved }()
+ done, events := map[string]int{}, map[string]int{}
+ for seed := int64(1); seed <= 200; seed++ {
+ ho := newRandomHO(seed)
+ ho.run()
+ for k, v := range ho.done {
+ done[k] += v
+ }
+ for k, v := range ho.w.events {
+ events[k] += v
+ }
+ if len(ho.w.violations) > 0 {
+ t.Errorf("seed %d: %v", seed, ho.w.violations)
+ }
+ }
+ names := map[string]bool{}
+ for _, a := range hoActions {
+ if names[a.name] {
+ t.Errorf("action %q registered twice", a.name)
+ }
+ names[a.name] = true
+ if done[a.name] == 0 {
+ t.Errorf("action %q never completed over 200 seeds", a.name)
+ }
+ }
+ for _, e := range []string{
+ "ho-standby", "ho-withdrawn", "ho-ack-slow", "ho-drain-failed-ack", "ho-pending-begun", "ho-pending-settled",
+ "ho-move-start", "ho-held", "ho-hold-released", "ho-hold-bound", "ho-refused-at-once", "ho-moved",
+ "ho-take-raced", "ho-take-lost-race", "ho-take-timeout", "ho-move-failed", "ho-unclean-release",
+ "ho-lease-loss", "ho-fa", "ho-cut", "ho-wait-restore",
+ "ho-redirect", "ho-redirect-read", "ho-successor-slept", "ho-handover-answer", "ho-handover-followed",
+ "ho-handover-local", "ho-local-raced", "ho-retry-named",
+ "ho-reset-after-send", "ho-dial-before-send", "ho-placed-on-A", "ho-start-refused", "ho-start-refused-fenced",
+ "ho-drained", "ho-reboot", "ho-agent-restart", "ho-precheck-refused",
+ "ho-roll-applied", "ho-edge-stop-unproven", "ho-terminate-dispatched", "ho-edge-restart",
+ "ho-replaced", "ho-removed", "ho-replacement-launched", "ho-drain-failed", "ho-cancel",
+ "ho-answer-app", "ho-answer-today", "ho-answer-fa", "ho-answer-cut", "ho-answer-reset",
+ } {
+ if events[e] == 0 {
+ t.Errorf("no %s over 200 seeds", e)
+ }
+ }
+ t.Logf("completed: %v", done)
+}
diff --git a/internal/sim/regionha/world_test.go b/internal/sim/regionha/world_test.go
index 3ccd911d1..13d793a3c 100644
--- a/internal/sim/regionha/world_test.go
+++ b/internal/sim/regionha/world_test.go
@@ -724,6 +724,7 @@ func runSeed(seed int64, verbose bool) *world {
dutyLegacySidecarWitness(w, seed)
}
runGroupScenario(w, seed)
+ runHandoverScenario(w, seed)
return w
}