region HA P1a Task 14: seeded N-box simulation of single writer and no stale serving for born-HA hosts, with mutation checks
internal/sim/regionha drives the real hafresh decisions (DecideAcquire, DecideKeep, OwnerFor, MarkerBody, DecodeLock) over 2 to 5 boxes and one S3 with conditional writes, replica chains and a files manifest, in the release order of Tasks 6, 7, 10 and 12. Invariants I1 (one running unit per host; every replica and manifest write from the lease holder; no TXID reused), I2 (serve only S3's state) and I5 (no host stranded by a deleted lock or an owed marker never written). 13 mutation rules, each with a witness; mutate.sh takes the test binary path (S14).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+2,538
−0
internal/sim/regionha/actions_test.go+918 −0internal/sim/regionha/expected-outcomes.txt+10 −0internal/sim/regionha/invariants_test.go+121 −0internal/sim/regionha/mutate.sh+179 −0internal/sim/regionha/rules_test.go+60 −0internal/sim/regionha/sim_test.go+223 −0internal/sim/regionha/witness_test.go+469 −0internal/sim/regionha/world_test.go+558 −0
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| new file mode 100644 |
| index 000000000..9359781e5 |
| --- /dev/null |
| +++ b/internal/sim/regionha/actions_test.go |
| @@ -0,0 +1,918 @@ |
| +package regionha |
| + |
| +import ( |
| + "fmt" |
| + "strconv" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// ---- the acquire (lease.AcquireHA, classifyAndTake; Tasks 6 and 9) ---- |
| + |
| +// sameBoxEmpty is the same-box emptiness proof (activator, Task 12): the |
| +// row is contained (every box here is nested), this agent's startup sweep |
| +// proved every unit stopped, this agent process never took the host, and |
| +// the host's slice reads empty. No S3 request. |
| +func (w *world) sameBoxEmpty(b *box, h string) bool { |
| + return (b.Swept || !on("recover-without-sweep")) && !b.AcquiredHere[h] && w.sliceEmpty(b, h) |
| +} |
| + |
| +// sliceEmpty reads the host slice's cgroup.events on b: populated while |
| +// any unit of the host runs there. |
| +func (w *world) sliceEmpty(b *box, h string) bool { |
| + for _, u := range b.Units[h] { |
| + if u.Running { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// decideAcquire is hafresh.DecideAcquire with this box's proofs. |
| +func (w *world) decideAcquire(b *box, h string, v hafresh.View) hafresh.Decision { |
| + proof := func() (bool, error) { return w.sameBoxEmpty(b, h), nil } |
| + if !on("same-box-no-proof") { |
| + proof = func() (bool, error) { return true, nil } |
| + } |
| + d := hafresh.DecideAcquire(v, b.Self, w.now(), hafresh.Proofs{SameBoxEmpty: proof}) |
| + if !on("expiry-authorizes") && d.Action == hafresh.ActRefuse && d.Reason == hafresh.ReasonOtherExpired { |
| + d = hafresh.Decision{Action: hafresh.ActTake, Reason: "expired"} |
| + } |
| + return d |
| +} |
| + |
| +// classify is one round's decision on v (AcquireHA's decide func): "" |
| +// takes; anything else is the refusal, and nothing is written. |
| +func (w *world) classify(b *box, h string, v hafresh.View) string { |
| + d := w.decideAcquire(b, h, v) |
| + switch d.Action { |
| + case hafresh.ActCreate: |
| + if on("first-wake-ignores-leftovers") && !w.s3[h].empty() { |
| + return "leftover data" |
| + } |
| + return "" |
| + case hafresh.ActTake: |
| + return "" |
| + case hafresh.ActHeld: |
| + return "held by " + d.Reason |
| + } |
| + return d.Reason |
| +} |
| + |
| +// take writes the next lease over v, conditional on it, owned by b's agent |
| +// process: generation 1 over an absent lock, v's plus one otherwise. |
| +func (w *world) take(b *box, h string, v hafresh.View, ha bool) *entry { |
| + gen := int64(1) |
| + if !v.Absent { |
| + gen = v.Lock.Generation + 1 |
| + } |
| + expires := w.now().Add(ttlTicks * tick) |
| + if !w.putLock(h, w.leaseBody(gen, hafresh.OwnerFor(b.Self, b.PID, ha), expires), v) { |
| + return nil |
| + } |
| + return &entry{Host: h, HA: ha, ETag: w.s3[h].ETag, Gen: gen, Expires: expires, View: v} |
| +} |
| + |
| +// acquireHA is the classify-and-take loop, at most three rounds. pre is a |
| +// round 0 already read and classified (an acquire whose PUT comes a step |
| +// after its GET); nil reads now. |
| +func (w *world) acquireHA(b *box, h string, pre *pending) (*entry, string) { |
| + for round := 0; round < 3; round++ { |
| + var v hafresh.View |
| + if round == 0 && pre != nil { |
| + v = pre.View |
| + } else { |
| + if round > 0 && !on("legacy-fallback-on-ha") { |
| + return w.acquireLeaseLitestream(b, h) |
| + } |
| + v = w.view(h) |
| + if why := w.classify(b, h, v); why != "" { |
| + return nil, why |
| + } |
| + } |
| + if e := w.take(b, h, v, true); e != nil { |
| + return e, "" |
| + } |
| + w.event("reclassified") |
| + w.logf("box%d: %s: the lock changed since it was read; read and classify again", b.ID, h) |
| + } |
| + return nil, "contended" |
| +} |
| + |
| +// acquireLeaseLitestream is litestream's AcquireLease, which the HA |
| +// acquire must never fall back to (r2.6): any lock that is absent or |
| +// expired is free. |
| +func (w *world) acquireLeaseLitestream(b *box, h string) (*entry, string) { |
| + v := w.view(h) |
| + if !v.Absent && !w.now().After(v.Lock.ExpiresAt) { |
| + return nil, "held by " + v.Lock.Owner |
| + } |
| + if e := w.take(b, h, v, true); e != nil { |
| + return e, "" |
| + } |
| + return nil, "contended" |
| +} |
| + |
| +// ---- the wake (activator.acquireClassified, restoreHA; Task 9) ---- |
| + |
| +// wakeOpts are a wake's faults. |
| +type wakeOpts struct { |
| + LateAck bool // the take is acknowledged after its safe deadline |
| + RestoreFails bool // the restore fails after the copy was set aside |
| + FailAfterRepl bool // the wake fails after replication has started |
| + SettleFails bool // the owed marker's retry before the acquire fails |
| + MarkerFails bool // the unclean release's marker PUT fails |
| +} |
| + |
| +// wake is a request's wake of h at b, which has no entry for it. pre is a |
| +// round 0 the box already read (wake-begin). It reports what happened. |
| +func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string { |
| + if pre == nil && b.StaleNeg[h] && w.s3[h].ETag != "" { |
| + // The box's index says legacy: the legacy acquire (takeLegacy) |
| + // classifies the lock first. |
| + w.event("legacy-path") |
| + v := w.view(h) |
| + if v.HAOn() && on("legacy-takes-ha-lock") { |
| + w.event("ha-lock-on-legacy-path") |
| + b.StaleNeg[h] = false // MarkHA: the host is HA on this box from now on |
| + w.logf("box%d: %s: the lock is HA-format; the host is HA from now on", b.ID, h) |
| + } else { |
| + if !v.Absent && !w.now().After(v.Lock.ExpiresAt) { |
| + w.event("refused-held") |
| + return "legacy: held" |
| + } |
| + e := w.take(b, h, v, false) |
| + if e == nil { |
| + return "legacy: lost" |
| + } |
| + return w.legacyWake(b, h, e) |
| + } |
| + } |
| + if pre == nil { |
| + if ob := b.Owed[h]; ob != nil && !w.retryObligation(b, ob, o.SettleFails) { |
| + w.event("refused-settle") |
| + return "refused: the owed marker could not be settled" |
| + } |
| + } |
| + e, why := w.acquireHA(b, h, pre) |
| + if e == nil { |
| + switch { |
| + case strings.HasPrefix(why, "held"): |
| + w.event("refused-held") |
| + case why == hafresh.ReasonOtherExpired: |
| + w.event("refused-other-expired") |
| + case strings.HasPrefix(why, hafresh.ReasonSameBoxUnsure): |
| + w.event("refused-same-box") |
| + case why == "leftover data": |
| + w.event("refused-leftover-data") |
| + default: |
| + w.event("refused-other") |
| + } |
| + w.logf("box%d: %s: wake refused: %s (lock %s)", b.ID, h, why, w.lockString(h)) |
| + return "refused: " + why |
| + } |
| + b.AcquiredHere[h] = true |
| + if !e.View.Absent && e.View.Lock.Release == nil { |
| + w.event("same-box-retake") |
| + } |
| + w.logf("box%d: %s: acquired over %s", b.ID, h, viewWord(e.View)) |
| + if o.LateAck { |
| + // The acquire's own cleanup: the lock is ours, the deadline is not. |
| + w.event("late-ack") |
| + w.releaseUnclean(b, h, e, 0, o.MarkerFails) |
| + return "late ack" |
| + } |
| + l := w.local(b, h) |
| + if e.View.Absent { |
| + // A first wake: the prefix was proven empty, so boot fresh. |
| + w.setAside(l) |
| + w.fresh(l) |
| + w.event("fresh") |
| + } else { |
| + keep, reason := w.decideKeep(b, h, e.View, l.now()) |
| + if keep { |
| + w.event("kept") |
| + } else { |
| + w.setAside(l) |
| + if o.RestoreFails { |
| + w.event("failed-restore") |
| + w.releaseUnclean(b, h, e, 0, o.MarkerFails) |
| + return "failed restore" |
| + } |
| + w.restore(l, h) |
| + w.event("restored") |
| + } |
| + w.logf("box%d: %s: keep=%v (%s)", b.ID, h, keep, reason) |
| + } |
| + w.startWake(b, h, e, l) |
| + if o.FailAfterRepl { |
| + w.event("failed-after-replication") |
| + w.tenantWrite(b, h, false) |
| + w.sync(b, h, false) |
| + w.closeHA(b, h, o.MarkerFails) |
| + return "failed after replication" |
| + } |
| + return "served" |
| +} |
| + |
| +func viewWord(v hafresh.View) string { |
| + switch { |
| + case v.Absent: |
| + return "an absent lock" |
| + case v.Lock.Release != nil && v.Lock.Release.Clean: |
| + return "a clean marker of " + v.Lock.Release.Box |
| + case v.Lock.Release != nil: |
| + return "an unclean marker of " + v.Lock.Release.Box |
| + } |
| + return "an expired lease of " + v.Lock.Owner |
| +} |
| + |
| +// decideKeep is hafresh.DecideKeep over the view the acquire classified. |
| +func (w *world) decideKeep(b *box, h string, v hafresh.View, now hafresh.LocalNow) (bool, string) { |
| + if !on("keep-without-marker") && now.HaveRecord { |
| + // The box's own release record stands in for the lock's marker. |
| + m := now.Record.Marker |
| + v = hafresh.View{Lock: hafresh.Lock{Owner: hafresh.MarkerOwner(m), Release: &m}} |
| + } |
| + if !on("keep-unclean") && !v.Absent && v.Lock.Release != nil { |
| + m := *v.Lock.Release |
| + m.Clean = true |
| + v.Lock.Release = &m |
| + } |
| + return hafresh.DecideKeep(v, b.Self, w.lifetime(h), now) |
| +} |
| + |
| +// startWake starts the host's main unit and its entry: the replicator from |
| +// the local position, the publisher from the manifest the copy matches. |
| +// The box serves from here on, so I2 is checked now. |
| +func (w *world) startWake(b *box, h string, e *entry, l *localCopy) { |
| + p := w.s3[h] |
| + b.Units[h] = append(b.Units[h], &unit{Running: true}) |
| + e.Uploaded = l.TXID |
| + pub := &publisher{Box: b.ID, PID: b.PID, Host: h, Gen: p.Gen, Last: p.Files} |
| + if l.Record != nil { |
| + // A keep: a restore or a fresh boot removed the record. The |
| + // publisher continues from the manifest the record names. |
| + pub.Gen, pub.Last = genSeq(l.Record.Marker.FilesGen), l.Files |
| + } |
| + e.Pub = pub |
| + b.Entries[h] = e |
| + w.event("served") |
| + w.checkServe(b, h) |
| +} |
| + |
| +func genSeq(gen string) int { |
| + seq, _, _ := strings.Cut(gen, ":") |
| + n, _ := strconv.Atoi(seq) |
| + return n |
| +} |
| + |
| +func (w *world) local(b *box, h string) *localCopy { |
| + l := b.Local[h] |
| + if l == nil { |
| + l = &localCopy{WALEmpty: true} |
| + b.Local[h] = l |
| + } |
| + return l |
| +} |
| + |
| +// setAside moves the database and files aside and removes the release |
| +// record and litestream's local state. |
| +func (w *world) setAside(l *localCopy) { |
| + *l = localCopy{WALEmpty: true} |
| +} |
| + |
| +// restore restores the database from the replica chain's head and the |
| +// files from the manifest, into a clean tree. |
| +func (w *world) restore(l *localCopy, h string) { |
| + p := w.s3[h] |
| + t := w.newClock() |
| + *l = localCopy{ |
| + DBExists: true, DB: hafresh.FileID{Inode: w.newInode(), Size: 4096, MtimeNs: t, CtimeNs: t}, WALEmpty: true, |
| + TXID: p.MaxTXID, Ver: p.HeadVer, Tree: true, Files: p.Files, TreeMeta: w.newClock(), |
| + } |
| +} |
| + |
| +// fresh is a first wake's empty database and empty files tree. |
| +func (w *world) fresh(l *localCopy) { |
| + t := w.newClock() |
| + *l = localCopy{ |
| + DBExists: true, DB: hafresh.FileID{Inode: w.newInode(), Size: 4096, MtimeNs: t, CtimeNs: t}, WALEmpty: true, |
| + Tree: true, TreeMeta: w.newClock(), |
| + } |
| +} |
| + |
| +// legacyWake is the legacy path's wake (restorePlain): it keeps any local |
| +// database file, and restores only when there is none. Only a mutation |
| +// reaches it for a born-HA host. |
| +func (w *world) legacyWake(b *box, h string, e *entry) string { |
| + w.event("legacy-wake") |
| + l := w.local(b, h) |
| + if !l.DBExists { |
| + w.restore(l, h) |
| + } |
| + b.Units[h] = append(b.Units[h], &unit{Running: true}) |
| + e.Uploaded = l.TXID |
| + b.Entries[h] = e |
| + w.logf("box%d: %s: woken by the legacy path over %s", b.ID, h, viewWord(e.View)) |
| + w.event("served") |
| + w.checkServe(b, h) |
| + return "legacy served" |
| +} |
| + |
| +// ---- tenant writes, replication, files ---- |
| + |
| +// tenantWrite is a request's write: one transaction into the WAL, and |
| +// maybe a change to the files tree. |
| +func (w *world) tenantWrite(b *box, h string, filesToo bool) { |
| + l := b.Local[h] |
| + l.TXID++ |
| + l.Ver = w.newVer() |
| + l.WALEmpty = false |
| + if filesToo { |
| + l.Files = files{Ver: w.newVer()} |
| + l.TreeMeta = w.newClock() |
| + } |
| +} |
| + |
| +// checkpoint copies the WAL into the database file: the file changes. |
| +func (w *world) checkpoint(l *localCopy) { |
| + t := w.newClock() |
| + l.WALEmpty = true |
| + l.DB.MtimeNs, l.DB.CtimeNs = t, t |
| + l.DB.Size += 4096 |
| +} |
| + |
| +// sync is one replicator sync: an upload of everything past the uploaded |
| +// position, then maybe a checkpoint. |
| +func (w *world) sync(b *box, h string, ckpt bool) { |
| + e, l := b.Entries[h], b.Local[h] |
| + if l.TXID > e.Uploaded { |
| + w.replicaWrite(b, b.PID, h, l.TXID, l.Ver) |
| + e.Uploaded = l.TXID |
| + } |
| + if ckpt && !l.WALEmpty { |
| + w.checkpoint(l) |
| + } |
| +} |
| + |
| +// replicaWrite is one LTX upload. I1: from the lock's holder, at a TXID |
| +// the chain does not hold. |
| +func (w *world) replicaWrite(b *box, pid int, h string, txid uint64, ver int) { |
| + p := w.s3[h] |
| + w.checkHolder(b, pid, h, fmt.Sprintf("replica write txid %d", txid)) |
| + if txid <= p.MaxTXID { |
| + w.fail("I1", "box%d (pid %d) uploaded txid %d for %s, which the replica already holds (head %d)", b.ID, pid, txid, h, p.MaxTXID) |
| + } |
| + p.Chain = append(p.Chain, ltx{TXID: txid, Ver: ver, Box: b.ID, PID: pid}) |
| + if txid > p.MaxTXID { |
| + p.MaxTXID = txid |
| + } |
| + p.HeadVer = ver |
| + w.logf("box%d: %s: uploaded txid %d", b.ID, h, txid) |
| +} |
| + |
| +// manifestWrite is a files manifest commit, conditional on the |
| +// publisher's generation. I1: from the lock's holder. |
| +func (w *world) manifestWrite(b *box, pub *publisher, f files) bool { |
| + p := w.s3[pub.Host] |
| + if p.Gen != pub.Gen { |
| + pub.Broken = true |
| + w.logf("box%d: %s: the manifest was superseded; the publisher stops", b.ID, pub.Host) |
| + return false |
| + } |
| + w.checkHolder(b, pub.PID, pub.Host, fmt.Sprintf("manifest commit gen %d", p.Gen+1)) |
| + p.Gen++ |
| + p.Files = f |
| + pub.Gen, pub.Last = p.Gen, f |
| + w.event("manifest-committed") |
| + w.logf("box%d: %s: committed manifest gen %d", b.ID, pub.Host, p.Gen) |
| + return true |
| +} |
| + |
| +// publishTick is the publisher's cadence: an in-flight snapshot commits |
| +// when it is done; a changed tree starts one. |
| +func (w *world) publishTick(b *box, h string, e *entry) { |
| + pub := e.Pub |
| + if pub.Broken { |
| + return |
| + } |
| + if s := pub.Inflight; s != nil { |
| + if w.step >= s.DoneAt { |
| + pub.Inflight = nil |
| + w.manifestWrite(b, pub, s.Files) |
| + } |
| + return |
| + } |
| + if !w.scripted && b.Local[h].Files != pub.Last && w.pct(30) { |
| + w.startSnapshot(b, h, 1+w.rng.Intn(3)) |
| + } |
| +} |
| + |
| +// startSnapshot starts a snapshot of the tree as it is now, done in d ticks. |
| +func (w *world) startSnapshot(b *box, h string, d int) { |
| + pub := b.Entries[h].Pub |
| + pub.Inflight = &snapshot{Files: b.Local[h].Files, DoneAt: w.step + d} |
| + w.logf("box%d: %s: a snapshot starts", b.ID, h) |
| +} |
| + |
| +// strayTick runs publishers that outlived their release (a mutation only). |
| +func (w *world) strayTick(b *box) { |
| + var keep []*publisher |
| + for _, pub := range b.Strays { |
| + s := pub.Inflight |
| + if s == nil || pub.Broken { |
| + continue |
| + } |
| + if w.step < s.DoneAt { |
| + keep = append(keep, pub) |
| + continue |
| + } |
| + pub.Inflight = nil |
| + w.logf("box%d: %s: a publisher that outlived its release commits", b.ID, pub.Host) |
| + w.manifestWrite(b, pub, s.Files) |
| + } |
| + b.Strays = keep |
| +} |
| + |
| +// renew is the renewer: once fewer than renewWithin ticks remain, a |
| +// conditional PUT of the same lease with a new expiry. A lock that changed |
| +// under it means the lease is lost: the host is stopped. |
| +func (w *world) renew(b *box, h string) { |
| + e := b.Entries[h] |
| + if e.Expires.Sub(w.now()) > renewWithin*tick { |
| + return |
| + } |
| + expires := w.now().Add(ttlTicks * tick) |
| + if !w.putLock(h, w.leaseBody(e.Gen, hafresh.OwnerFor(b.Self, b.PID, e.HA), expires), hafresh.View{ETag: e.ETag}) { |
| + w.event("lease-lost") |
| + w.logf("box%d: %s: the renewal lost its condition; the lease is lost and the host stops", b.ID, h) |
| + w.stopMain(b, h) |
| + delete(b.Entries, h) |
| + return |
| + } |
| + e.ETag, e.Expires = w.s3[h].ETag, expires |
| +} |
| + |
| +func (w *world) stopMain(b *box, h string) { |
| + us := b.Units[h][:0] |
| + for _, u := range b.Units[h] { |
| + if u.Straggler || u.Orphan { |
| + us = append(us, u) |
| + } |
| + } |
| + b.Units[h] = us |
| +} |
| + |
| +// ---- releases (lease.releaseWithMarker, activator.releaseHAClean) ---- |
| + |
| +// sleepOpts are a graceful sleep's faults. |
| +type sleepOpts struct { |
| + Straggler int // a unit of the host the stop missed, exiting in this many ticks |
| + FinalIncomplete bool // the final files publish skips an entry |
| + SyncFails bool // the final database sync fails |
| + MarkerFails bool // the marker PUT fails |
| +} |
| + |
| +// sleep is the graceful sleep: the stop (proven for the main unit), then |
| +// the release, which waits while the host's slice is populated. |
| +func (w *world) sleep(b *box, h string, o sleepOpts) { |
| + e := b.Entries[h] |
| + if !e.HA { |
| + w.legacySleep(b, h) |
| + return |
| + } |
| + w.stopMain(b, h) |
| + if o.Straggler > 0 { |
| + b.Units[h] = append(b.Units[h], &unit{Running: true, Straggler: true, ExitAt: w.step + o.Straggler}) |
| + } |
| + e.Releasing = &o |
| + w.tryRelease(b, h) |
| +} |
| + |
| +// tryRelease is releaseHAClean once the stop has been proven: the host's |
| +// slice read empty, stopFiles and Final, Finish, the local release record, |
| +// then the marker; nothing after it. |
| +func (w *world) tryRelease(b *box, h string) { |
| + e := b.Entries[h] |
| + o := *e.Releasing |
| + if on("marker-before-slice-empty") && !w.sliceEmpty(b, h) { |
| + w.event("release-held") |
| + w.logf("box%d: %s: the host's slice is not proven empty; the release waits", b.ID, h) |
| + return |
| + } |
| + l := b.Local[h] |
| + base := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), At: w.now()} |
| + if !on("marker-before-final") { |
| + m := base |
| + m.TXID, m.FilesGen, m.Clean = e.Uploaded, w.gen(e.Pub.Gen), true |
| + w.putMarker(b, h, e, m, o.MarkerFails) |
| + w.stopAndFinal(b, h, e, o.FinalIncomplete) |
| + w.finish(b, h, e, o.SyncFails) |
| + w.writeRecord(l, m) |
| + delete(b.Entries, h) |
| + return |
| + } |
| + gen, complete := w.stopAndFinal(b, h, e, o.FinalIncomplete) |
| + txid, synced := w.finish(b, h, e, o.SyncFails) |
| + m := base |
| + m.TXID, m.FilesGen, m.Clean = txid, gen, complete && synced |
| + w.writeRecord(l, m) |
| + w.putMarker(b, h, e, m, o.MarkerFails) |
| + delete(b.Entries, h) |
| +} |
| + |
| +// stopAndFinal is stopFiles (joining the publisher: its in-flight snapshot |
| +// commits or fails) and then Final: one last full publish. complete is |
| +// SyncStats.Complete and a landed commit. |
| +func (w *world) stopAndFinal(b *box, h string, e *entry, incomplete bool) (string, bool) { |
| + pub := e.Pub |
| + if pub.Inflight != nil { |
| + if on("publisher-outlives-release") { |
| + s := pub.Inflight |
| + pub.Inflight = nil |
| + w.manifestWrite(b, pub, s.Files) |
| + } else { |
| + b.Strays = append(b.Strays, pub) |
| + } |
| + } |
| + if pub.Broken { |
| + return w.gen(pub.Gen), false |
| + } |
| + f := b.Local[h].Files |
| + if incomplete { |
| + f.Partial = true |
| + } |
| + if f != pub.Last && !w.manifestWrite(b, pub, f) { |
| + return w.gen(pub.Gen), false |
| + } |
| + return w.gen(pub.Gen), !incomplete |
| +} |
| + |
| +// finish is the replicator's finalization: the final sync. txid is the |
| +// replica's position after it. |
| +func (w *world) finish(b *box, h string, e *entry, fails bool) (uint64, bool) { |
| + if fails { |
| + w.logf("box%d: %s: the final sync fails", b.ID, h) |
| + return e.Uploaded, false |
| + } |
| + w.sync(b, h, false) |
| + return e.Uploaded, true |
| +} |
| + |
| +// writeRecord is writeHARecord: a clean release truncates the WAL first, |
| +// then the record captures the marker, the database's identity, the WAL |
| +// and the tree digest. |
| +func (w *world) writeRecord(l *localCopy, m hafresh.Marker) { |
| + if m.Clean && !l.WALEmpty { |
| + w.checkpoint(l) |
| + } |
| + l.Record = &hafresh.LocalRecord{Marker: m, DB: l.DB, WALEmpty: l.WALEmpty, TreeDigest: l.digest()} |
| +} |
| + |
| +// putMarker is releaseWithMarker: MarkerBody at the lease's generation, |
| +// If-Match its ETag. A failure is an obligation, persisted before the |
| +// error returns; a 412 means the lease is no longer ours. |
| +func (w *world) putMarker(b *box, h string, e *entry, m hafresh.Marker, fails bool) { |
| + body, err := hafresh.MarkerBody(e.Gen, m) |
| + if err != nil { |
| + w.fail("MODEL", "MarkerBody: %v", err) |
| + return |
| + } |
| + if fails { |
| + ob := &obligation{Host: h, ETag: e.ETag, Body: body} |
| + b.Owed[h] = ob |
| + if on("obligation-in-memory-only") { |
| + b.Disk[h] = ob |
| + } |
| + w.owed[h][e.ETag] = true |
| + w.event("marker-owed") |
| + w.logf("box%d: %s: the marker PUT fails; owed (If-Match %s)", b.ID, h, e.ETag) |
| + return |
| + } |
| + if !w.putLock(h, body, hafresh.View{ETag: e.ETag}) { |
| + w.event("marker-void") |
| + return |
| + } |
| + if m.Clean { |
| + w.event("marker-clean") |
| + } else { |
| + w.event("marker-unclean") |
| + } |
| + w.logf("box%d: %s: released with a marker (clean %v, txid %d, files %s)", b.ID, h, m.Clean, m.TXID, m.FilesGen) |
| +} |
| + |
| +// releaseUnclean is every release but the clean one: the acquire's cleanup |
| +// after a late acknowledgement, a failed restore, and Close. The marker is |
| +// unclean, at txid. |
| +func (w *world) releaseUnclean(b *box, h string, e *entry, txid uint64, markerFails bool) { |
| + delete(b.Entries, h) |
| + if !on("cleanup-deletes-lock") { |
| + w.deleteLock(h, e.ETag) |
| + w.logf("box%d: %s: released by deleting the lock", b.ID, h) |
| + return |
| + } |
| + m := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), TXID: txid, At: w.now()} |
| + w.putMarker(b, h, e, m, markerFails) |
| +} |
| + |
| +// closeHA is a failed wake's Close after replication started: the unit is |
| +// stopped, the replicator finalizes (its final sync), then the unclean |
| +// marker at the replica's position. |
| +func (w *world) closeHA(b *box, h string, markerFails bool) { |
| + e := b.Entries[h] |
| + w.stopMain(b, h) |
| + w.sync(b, h, false) |
| + w.releaseUnclean(b, h, e, e.Uploaded, markerFails) |
| +} |
| + |
| +// legacySleep is the legacy Close: the final sync, then a DELETE of the |
| +// lock, If-Match. |
| +func (w *world) legacySleep(b *box, h string) { |
| + e := b.Entries[h] |
| + w.stopMain(b, h) |
| + w.sync(b, h, false) |
| + delete(b.Entries, h) |
| + w.deleteLock(h, e.ETag) |
| + w.logf("box%d: %s: legacy release deleted the lock", b.ID, h) |
| +} |
| + |
| +// retryObligation is one retry of an owed marker: one PUT, If-Match the |
| +// owed ETag. Success or a 412 ends it; anything else keeps it. false only |
| +// when the PUT failed. |
| +func (w *world) retryObligation(b *box, ob *obligation, fails bool) bool { |
| + if fails { |
| + w.logf("box%d: %s: the owed marker's retry fails", b.ID, ob.Host) |
| + return false |
| + } |
| + delete(b.Owed, ob.Host) |
| + delete(b.Disk, ob.Host) |
| + if w.putLock(ob.Host, ob.Body, hafresh.View{ETag: ob.ETag}) { |
| + w.event("obligation-discharged") |
| + w.logf("box%d: %s: the owed marker is written", b.ID, ob.Host) |
| + } else { |
| + w.event("obligation-void") |
| + } |
| + return true |
| +} |
| + |
| +// ---- agents ---- |
| + |
| +// crash kills b's agent: its memory goes (entries, pending acquires, owed |
| +// markers not on disk, publishers); the host units outlive it as orphans. |
| +func (w *world) crash(b *box) { |
| + b.Agent = agentDown |
| + for _, h := range w.hosts { |
| + for _, u := range b.Units[h] { |
| + if !u.Straggler { |
| + u.Orphan = true |
| + } |
| + } |
| + } |
| + b.Entries = map[string]*entry{} |
| + b.Pending = map[string]*pending{} |
| + b.Owed = map[string]*obligation{} |
| + b.Strays = nil |
| + b.AcquiredHere = map[string]bool{} |
| + b.Swept = false |
| + w.event("crash") |
| + w.logf("box%d: the agent crashes", b.ID) |
| +} |
| + |
| +// restart starts a new agent process: its startup sweep (which, when it |
| +// succeeds, proves every unit on the box stopped) and the obligations on |
| +// disk. |
| +func (w *world) restart(b *box, sweepOK bool) { |
| + b.Agent = agentUp |
| + b.PID = w.newPID() |
| + b.Swept = sweepOK |
| + if sweepOK { |
| + b.Units = map[string][]*unit{} |
| + } |
| + for h, ob := range b.Disk { |
| + b.Owed[h] = ob |
| + } |
| + w.event("restart") |
| + w.logf("box%d: the agent restarts as pid %d (sweep ok %v)", b.ID, b.PID, sweepOK) |
| +} |
| + |
| +func (w *world) hang(b *box, d int) { |
| + b.Agent = agentHung |
| + b.HungTill = w.step + d |
| + w.event("hang") |
| + w.logf("box%d: the agent hangs for %d ticks", b.ID, d) |
| +} |
| + |
| +// plant writes objects under a host's prefix whose lock is absent: what an |
| +// earlier life of the name, or a hand, left behind. |
| +func (w *world) plant(h string) { |
| + p := w.s3[h] |
| + ver := w.newVer() |
| + for i := uint64(1); i <= 3; i++ { |
| + p.Chain = append(p.Chain, ltx{TXID: i, Ver: ver, Box: -1}) |
| + } |
| + p.MaxTXID, p.HeadVer = 3, ver |
| + p.Gen, p.Files = 1, files{Ver: w.newVer()} |
| + p.Planted = true |
| + w.event("leftovers-planted") |
| + w.logf("%s: leftover objects planted under an absent lock", h) |
| +} |
| + |
| +// ---- the random walk ---- |
| + |
| +func (w *world) randomBox() *box { return w.boxes[w.rng.Intn(len(w.boxes))] } |
| +func (w *world) randomHost() string { return w.hosts[w.rng.Intn(len(w.hosts))] } |
| + |
| +func (w *world) randomWakeOpts() wakeOpts { |
| + var o wakeOpts |
| + n := w.rng.Intn(100) |
| + if !w.calm() { |
| + o.LateAck = n < 5 |
| + o.RestoreFails = n >= 5 && n < 10 |
| + o.FailAfterRepl = n >= 10 && n < 15 |
| + } |
| + o.SettleFails = w.fault(30) |
| + o.MarkerFails = w.fault(15) |
| + return o |
| +} |
| + |
| +func (w *world) randomSleepOpts() sleepOpts { |
| + var o sleepOpts |
| + if w.fault(20) { |
| + o.Straggler = 1 + w.rng.Intn(3) |
| + } |
| + o.FinalIncomplete = w.fault(10) |
| + o.SyncFails = w.fault(10) |
| + o.MarkerFails = w.fault(15) |
| + return o |
| +} |
| + |
| +// idle reports whether b's agent has nothing in flight for h. |
| +func idle(b *box, h string) bool { return b.Entries[h] == nil && b.Pending[h] == nil } |
| + |
| +func init() { |
| + actions = append(actions, |
| + // A request at a random box: a write where the host is awake there, |
| + // else a wake. |
| + action{"request", 30, func(w *world) bool { |
| + b, h := w.randomBox(), w.randomHost() |
| + o := w.randomWakeOpts() |
| + if b.Agent != agentUp || b.Pending[h] != nil { |
| + return false |
| + } |
| + if e := b.Entries[h]; e != nil { |
| + if e.Releasing != nil { |
| + return false |
| + } |
| + w.tenantWrite(b, h, w.pct(40)) |
| + return true |
| + } |
| + w.logf("box%d: %s: wake: %s", b.ID, h, w.wake(b, h, o, nil)) |
| + return true |
| + }}, |
| + // A wake's GET and classification, whose PUT comes later |
| + // (wake-finish): concurrent cold wakes, a lock changing between |
| + // GET and PUT. |
| + action{"wake-begin", 5, func(w *world) bool { |
| + b, h := w.randomBox(), w.randomHost() |
| + settle := w.fault(30) |
| + if b.Agent != agentUp || !idle(b, h) || (b.StaleNeg[h] && w.s3[h].ETag != "") { |
| + return false |
| + } |
| + if ob := b.Owed[h]; ob != nil && !w.retryObligation(b, ob, settle) { |
| + w.event("refused-settle") |
| + return true |
| + } |
| + v := w.view(h) |
| + if why := w.classify(b, h, v); why != "" { |
| + w.logf("box%d: %s: wake refused at its read: %s", b.ID, h, why) |
| + return true |
| + } |
| + b.Pending[h] = &pending{View: v, At: w.step} |
| + w.logf("box%d: %s: read %s and classified it; the PUT is pending", b.ID, h, viewWord(v)) |
| + return true |
| + }}, |
| + action{"wake-finish", 5, func(w *world) bool { |
| + type bh struct { |
| + b *box |
| + h string |
| + } |
| + var ps []bh |
| + for _, b := range w.boxes { |
| + for _, h := range w.hosts { |
| + if b.Agent == agentUp && b.Pending[h] != nil { |
| + ps = append(ps, bh{b, h}) |
| + } |
| + } |
| + } |
| + if len(ps) == 0 { |
| + return false |
| + } |
| + x := ps[w.rng.Intn(len(ps))] |
| + pd := x.b.Pending[x.h] |
| + delete(x.b.Pending, x.h) |
| + w.logf("box%d: %s: the pending PUT (read at step %d): %s", x.b.ID, x.h, pd.At, w.wake(x.b, x.h, wakeOpts{MarkerFails: w.fault(15)}, pd)) |
| + return true |
| + }}, |
| + action{"sleep", 10, func(w *world) bool { |
| + b, h := w.randomBox(), w.randomHost() |
| + o := w.randomSleepOpts() |
| + e := b.Entries[h] |
| + if b.Agent != agentUp || e == nil || e.Releasing != nil { |
| + return false |
| + } |
| + w.sleep(b, h, o) |
| + return true |
| + }}, |
| + // A write to a box's local copy while the host sleeps there: the |
| + // database (into the WAL, maybe checkpointed) or the files tree. |
| + action{"tenant-write-asleep", 3, func(w *world) bool { |
| + b, h := w.randomBox(), w.randomHost() |
| + dbWrite, ckpt := w.pct(50), w.pct(50) |
| + l := b.Local[h] |
| + if w.calm() || l == nil || !l.DBExists || b.Entries[h] != nil || len(b.Units[h]) > 0 { |
| + return false |
| + } |
| + if dbWrite { |
| + l.TXID++ |
| + l.Ver = w.newVer() |
| + l.WALEmpty = false |
| + if ckpt { |
| + w.checkpoint(l) |
| + } |
| + } else { |
| + l.Files = files{Ver: w.newVer()} |
| + l.TreeMeta = w.newClock() |
| + } |
| + w.logf("box%d: %s: the local copy changes while the host sleeps (db %v)", b.ID, h, dbWrite) |
| + return true |
| + }}, |
| + action{"agent-crash", 2, func(w *world) bool { |
| + b := w.randomBox() |
| + if w.calm() || b.Agent == agentDown { |
| + return false |
| + } |
| + w.crash(b) |
| + return true |
| + }}, |
| + action{"agent-restart", 6, func(w *world) bool { |
| + b := w.randomBox() |
| + sweepOK := !w.fault(30) |
| + if b.Agent != agentDown { |
| + return false |
| + } |
| + w.restart(b, sweepOK) |
| + return true |
| + }}, |
| + // A hang, mostly past the TTL, then the agent resumes by itself. |
| + action{"agent-hang", 2, func(w *world) bool { |
| + b := w.randomBox() |
| + d := 1 + w.rng.Intn(ttlTicks) |
| + if w.pct(70) { |
| + d = ttlTicks + 1 + w.rng.Intn(6) |
| + } |
| + if w.calm() || b.Agent != agentUp { |
| + return false |
| + } |
| + w.hang(b, d) |
| + return true |
| + }}, |
| + action{"plant-leftovers", 1, func(w *world) bool { |
| + h := w.randomHost() |
| + p := w.s3[h] |
| + if w.calm() || p.ETag != "" || !p.empty() { |
| + return false |
| + } |
| + for _, b := range w.boxes { |
| + if b.Pending[h] != nil { |
| + return false |
| + } |
| + } |
| + w.plant(h) |
| + return true |
| + }}, |
| + // A request at a box whose lifetime index holds a stale negative |
| + // entry for the host: the legacy acquire classifies the lock first. |
| + action{"legacy-wake", 3, func(w *world) bool { |
| + type bh struct { |
| + b *box |
| + h string |
| + } |
| + var ps []bh |
| + for _, b := range w.boxes { |
| + for _, h := range w.hosts { |
| + if b.Agent == agentUp && b.StaleNeg[h] && idle(b, h) && w.s3[h].ETag != "" { |
| + ps = append(ps, bh{b, h}) |
| + } |
| + } |
| + } |
| + if len(ps) == 0 { |
| + return false |
| + } |
| + x := ps[w.rng.Intn(len(ps))] |
| + w.logf("box%d: %s: wake by a stale index: %s", x.b.ID, x.h, w.wake(x.b, x.h, wakeOpts{}, nil)) |
| + return true |
| + }}, |
| + ) |
| +} |
diff --git a/internal/sim/regionha/expected-outcomes.txt b/internal/sim/regionha/expected-outcomes.txt| new file mode 100644 |
| index 000000000..8a7573cd7 |
| --- /dev/null |
| +++ b/internal/sim/regionha/expected-outcomes.txt |
| @@ -0,0 +1,10 @@ |
| +# rule outcome reason. Read by mutate.sh: a rule listed `missed` is not |
| +# expected to be caught alone, by the random sweep or by its witness |
| +# (witness_test.go), and is reported EXPECTED-MISS; the sweep fails if it |
| +# is caught (the expectation is stale). A rule listed `rare N` is reached |
| +# by the random sweep only at N seeds or more; below N its miss is |
| +# expected. |
| +# |
| +# No rule is listed: every rule in rules_test.go is caught alone, by the |
| +# random sweep and by its own witness (TestWitnessRulesKnown requires one |
| +# witness per rule). |
diff --git a/internal/sim/regionha/invariants_test.go b/internal/sim/regionha/invariants_test.go| new file mode 100644 |
| index 000000000..bb0a771a2 |
| --- /dev/null |
| +++ b/internal/sim/regionha/invariants_test.go |
| @@ -0,0 +1,121 @@ |
| +package regionha |
| + |
| +import ( |
| + "fmt" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// The invariants (plan Task 14; spec §21.1): |
| +// |
| +// - I1, single writer. At every step at most one unit of a host runs, |
| +// fleet-wide (so at most one box runs it: a second unit on the same box, |
| +// an orphan beside a new wake, is a second writer too). Every replica |
| +// write and every manifest write came from the lease holder of that |
| +// moment: lock.json's owner parses (hafresh.ParseOwner) to the writing |
| +// box's reference, instance id and agent pid. No two replica writes for |
| +// a host share a TXID. |
| +// - I2, no stale serving. When a box starts serving a host, its database |
| +// (position and content) and its files are S3's: the replica chain's |
| +// head and the manifest. A copy kept on a clean marker is S3's state by |
| +// construction; anything else that is kept is not. |
| +// - I5, liveness of the release (spec §21.1 I5, the part P1a owns), |
| +// checked once every fault has cleared: a host asleep is never stranded, |
| +// with no lock over data an HA lease wrote, or behind a lease whose |
| +// marker was owed and never written. The designed exceptions hold: a |
| +// host whose agent crashed waits behind its own expired lease for its |
| +// box's recovery (§9.6), and leftover objects under an absent lock |
| +// refuse the first wake (the leftover action's, not a lease's). |
| +// |
| +// MODEL is the model's own consistency: a lock that does not decode. |
| + |
| +// fail records a violation of invariant inv, once per invariant id. |
| +func (w *world) fail(inv, format string, args ...any) { |
| + msg := fmt.Sprintf(format, args...) |
| + w.logf("VIOLATION %s: %s", inv, msg) |
| + for _, v := range w.violations { |
| + if invariantOf(v) == inv { |
| + return |
| + } |
| + } |
| + w.violations = append(w.violations, inv+": "+msg) |
| +} |
| + |
| +// invariantOf is the invariant id a violation string was recorded under. |
| +func invariantOf(violation string) string { |
| + if i := strings.Index(violation, ": "); i >= 0 { |
| + return violation[:i] |
| + } |
| + return violation |
| +} |
| + |
| +// check is I1's state half, at every step boundary: at most one running |
| +// unit of each host. |
| +func (w *world) check() { |
| + for _, h := range w.hosts { |
| + var where []string |
| + for _, b := range w.boxes { |
| + for _, u := range b.Units[h] { |
| + if u.Running { |
| + kind := "main" |
| + switch { |
| + case u.Straggler: |
| + kind = "straggler" |
| + case u.Orphan: |
| + kind = "orphan" |
| + } |
| + where = append(where, fmt.Sprintf("box%d(%s, agent %s)", b.ID, kind, b.Agent)) |
| + } |
| + } |
| + } |
| + if len(where) > 1 { |
| + w.fail("I1", "%s runs %d units at once: %s (lock %s)", h, len(where), strings.Join(where, ", "), w.lockString(h)) |
| + } |
| + } |
| +} |
| + |
| +// checkHolder is I1's write half: what is about to be written to h's |
| +// prefix comes from the lock's holder, b's agent pid. |
| +func (w *world) checkHolder(b *box, pid int, h, what string) { |
| + v := w.view(h) |
| + if !v.Absent && v.Lock.Release == nil { |
| + if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && o.Ref == b.Self.Ref && o.IID == b.Self.IID && o.PID == pid { |
| + return |
| + } |
| + } |
| + w.fail("I1", "%s: %s by box%d (pid %d), which does not hold the lease (lock %s)", h, what, b.ID, pid, w.lockString(h)) |
| +} |
| + |
| +// checkServe is I2, as b starts serving h. |
| +func (w *world) checkServe(b *box, h string) { |
| + l, p := b.Local[h], w.s3[h] |
| + if l.TXID != p.MaxTXID || l.Ver != p.HeadVer || l.Files != p.Files { |
| + w.fail("I2", "box%d serves %s from txid %d (content %d, files %+v), but S3 holds txid %d (content %d, files %+v) (lock %s)", |
| + b.ID, h, l.TXID, l.Ver, l.Files, p.MaxTXID, p.HeadVer, p.Files, w.lockString(h)) |
| + } |
| +} |
| + |
| +// checkLiveness is I5, after final() has cleared every fault. |
| +func (w *world) checkLiveness() { |
| + for _, h := range w.hosts { |
| + awake := false |
| + for _, b := range w.boxes { |
| + awake = awake || b.Entries[h] != nil |
| + } |
| + if awake { |
| + continue |
| + } |
| + p := w.s3[h] |
| + if p.ETag == "" { |
| + if !p.empty() && !p.Planted { |
| + w.fail("I5", "%s is stranded: no lock.json over a prefix an HA lease wrote (txid %d, manifest gen %d)", h, p.MaxTXID, p.Gen) |
| + } |
| + continue |
| + } |
| + v := w.view(h) |
| + if v.Lock.Release == nil && w.owed[h][p.ETag] { |
| + w.fail("I5", "%s is stranded: the release marker owed for %s was never written (lock %s)", h, p.ETag, w.lockString(h)) |
| + } |
| + } |
| +} |
diff --git a/internal/sim/regionha/mutate.sh b/internal/sim/regionha/mutate.sh| new file mode 100755 |
| index 000000000..e7001fd3e |
| --- /dev/null |
| +++ b/internal/sim/regionha/mutate.sh |
| @@ -0,0 +1,179 @@ |
| +#!/bin/bash |
| +# Mutation checks for the region HA model (plan Task 14), in the engines |
| +# model's shape (internal/sim/engines/mutate.sh): build the test binary |
| +# once, then run it once per rule with RHASIM_MUTATE set. The sweep never |
| +# copies or edits the source. |
| +# |
| +# The first argument is the test binary (pre-flight ruling S14); its |
| +# directory holds the scratch. Build it, run the sweep, remove the one |
| +# directory: |
| +# |
| +# D=$(mktemp -d -p "$TMPDIR" rhasim.XXXXXX) |
| +# go test -c -o "$D/regionha.test" ./internal/sim/regionha/ |
| +# RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh "$D/regionha.test" 3000 |
| +# rm -r "$D" |
| +# |
| +# mutate.sh BIN 3000 # every rule |
| +# mutate.sh BIN 3000 rule-a rule-b # named rules |
| +# mutate.sh BIN 3000 rule-a,rule-b # a combination, dropped together |
| +# RHASIM_LIST=1 mutate.sh BIN 0 # print the rules a run would check, and run nothing |
| +# |
| +# Each rule gets two runs under its mutation: the random sweep |
| +# (TestRegionHA over the seeds) and the rule's deterministic witnesses |
| +# (TestWitnesses, witness_test.go). The verdict line reports both: |
| +# |
| +# CAUGHT rule: sweep N of S (first seed n); witness violated|held|none |
| +# |
| +# CAUGHT the sweep reported at least one violating seed (replay it with |
| +# RHASIM_SEED), OR a witness of the rule violated its invariant; |
| +# MISSED every seed passed and every witness held (or there is none); |
| +# ERROR anything else: an unknown rule, a stale binary, a panic, a |
| +# timeout, output the harness cannot parse, or a witness run |
| +# that failed. An error is never a detection. |
| +# |
| +# expected-outcomes.txt beside this script may list a rule as `missed` (its |
| +# catch needs a stated combination) or `rare N` (the sweep reaches it only |
| +# at N seeds or more); see that file. The sweep exits nonzero on any ERROR, |
| +# any unexpected MISSED, and any `missed` rule that is CAUGHT (STALE). |
| +# |
| +# The machine is shared: run the sweep once per revision, under nice -n 19. |
| +# RHASIM_PAR (default 1) runs that many rules at once. |
| +set -u |
| +BIN=${1:?usage: mutate.sh TEST-BINARY SEEDS [RULE...]} |
| +SEEDS=${2:?usage: mutate.sh TEST-BINARY SEEDS [RULE...]} |
| +shift 2 |
| +PKG=$(cd "$(dirname "$0")" && pwd) |
| +SCRATCH=${RHASIM_SCRATCH:-$(dirname "$BIN")/rhasim} |
| +if [ ! -x "$BIN" ]; then |
| + echo "no test binary at $BIN; build it with: go test -c -o $BIN ./internal/sim/regionha/" >&2 |
| + exit 2 |
| +fi |
| +if [ -n "$(find "$PKG" -name '*.go' -newer "$BIN")" ]; then |
| + echo "the test binary $BIN is older than the source; rebuild it" >&2 |
| + exit 2 |
| +fi |
| +ALL=$(RHASIM_LIST=1 "$BIN") || { echo "$BIN cannot list its rules" >&2; exit 2; } |
| +RULES="$*" |
| +if [ -z "$RULES" ] || [ "$RULES" = "@all" ]; then |
| + RULES=$ALL |
| +fi |
| +if [ -n "${RHASIM_LIST:-}" ]; then |
| + printf '%s\n' $RULES |
| + exit 0 |
| +fi |
| +mkdir -p "$SCRATCH/logs" "$SCRATCH/verdicts" || { echo "cannot create $SCRATCH" >&2; exit 2; } |
| +EXPECT="$PKG/expected-outcomes.txt" |
| +# the rules that have witnesses (the witnesses table): a run of one of them |
| +# with no witness output is an ERROR, never "none" |
| +WRULES=$(sed -n '/^var witnesses/,/^}/p' "$PKG/witness_test.go" | grep -o '^\s*{"[a-z0-9-]*",' | tr -d ' \t{",' | sort -u) |
| +# the verdicts of this run only: remove the files inside, by exact name |
| +for f in "$SCRATCH"/verdicts/*; do |
| + [ -e "$f" ] && { rm -f -- "$f" || exit 2; } |
| +done |
| + |
| +# the unmutated sweep first, at the same seed count: if the model violates |
| +# with every rule in place, no catch below means anything |
| +blog="$SCRATCH/logs/unmutated.log" |
| +RHASIM_MUTATE= RHASIM_SEEDS=$SEEDS "$BIN" -test.run '^TestRegionHA$' -test.count=1 -test.v -test.timeout 180m >"$blog" 2>&1 |
| +brc=$? |
| +if [ $brc -ne 0 ] || [ "$(grep -c "^ sim_test.go:[0-9]*: $SEEDS seeds, 0 failed; mutated=\"\"" "$blog")" -ne 1 ]; then |
| + echo "BASELINE unmutated: FAILED (rc=$brc); see $blog" >&2 |
| + exit 1 |
| +fi |
| +echo "BASELINE unmutated: sweep 0 of $SEEDS" |
| + |
| +one() { |
| + r=$1 |
| + tag=$(echo "$r" | tr ',' '+') |
| + log="$SCRATCH/logs/$tag.log" |
| + verdict="$SCRATCH/verdicts/$tag" |
| + for x in $(echo "$r" | tr ',' ' '); do |
| + if ! echo "$ALL" | grep -qx "$x"; then |
| + echo "ERROR $r: no rule named $x" | tee "$verdict" |
| + return |
| + fi |
| + done |
| + RHASIM_MUTATE=$r RHASIM_SEEDS=$SEEDS "$BIN" -test.run '^TestRegionHA$' -test.count=1 -test.v -test.timeout 180m >"$log" 2>&1 |
| + rc=$? |
| + expect=$(awk -v r="$r" '$1==r {print $2}' "$EXPECT" 2>/dev/null) |
| + depth=$(awk -v r="$r" '$1==r {print $3}' "$EXPECT" 2>/dev/null) |
| + nviol=$(grep -o "[0-9]* of $SEEDS seeds violated an invariant" "$log" | head -1 | awk '{print $1}') |
| + seed=$(grep -o "first seed [0-9]*" "$log" | head -1 | awk '{print $3}') |
| + clean=$(grep -c "^ sim_test.go:[0-9]*: $SEEDS seeds, 0 failed; mutated=\"$r\"" "$log") |
| + sweep="" |
| + if [ $rc -ne 0 ] && [ -n "$nviol" ] && [ -n "$seed" ] && ! grep -q "^panic:\|test timed out" "$log"; then |
| + sweep="sweep $nviol of $SEEDS (first seed $seed)" |
| + elif [ $rc -eq 0 ] && [ "$clean" -eq 1 ]; then |
| + sweep="sweep 0 of $SEEDS" |
| + fi |
| + wlog="$SCRATCH/logs/$tag.witness.log" |
| + RHASIM_MUTATE=$r "$BIN" -test.run '^TestWitnesses$' -test.count=1 -test.v -test.timeout 10m >"$wlog" 2>&1 |
| + wrc=$? |
| + wit=none |
| + if grep -q "^ witness_test.go:[0-9]*: witness .*: violated" "$wlog"; then |
| + wit=violated |
| + elif grep -q "^ witness_test.go:[0-9]*: witness .*: held" "$wlog"; then |
| + wit=held |
| + fi |
| + if [ $wrc -ne 0 ] || grep -q "^panic:\|test timed out" "$wlog"; then |
| + echo "ERROR $r: witness run rc=$wrc; see $wlog" | tee "$verdict" |
| + return |
| + fi |
| + if [ "$wit" = none ]; then |
| + for x in $(echo "$r" | tr ',' ' '); do |
| + if echo "$WRULES" | grep -qx "$x"; then |
| + echo "ERROR $r: $x has witnesses but the run produced no witness output; see $wlog" | tee "$verdict" |
| + return |
| + fi |
| + done |
| + fi |
| + if [ -z "$sweep" ]; then |
| + echo "ERROR $r: rc=$rc, no parsable sweep verdict; see $log" | tee "$verdict" |
| + return |
| + fi |
| + caught=0 |
| + if [ "$sweep" != "sweep 0 of $SEEDS" ] || [ "$wit" = violated ]; then |
| + caught=1 |
| + fi |
| + if [ $caught -eq 1 ]; then |
| + if [ "$expect" = "missed" ]; then |
| + echo "STALE $r: $sweep; witness $wit; but expected-outcomes.txt says missed" | tee "$verdict" |
| + else |
| + echo "CAUGHT $r: $sweep; witness $wit" | tee "$verdict" |
| + fi |
| + elif [ "$expect" = "missed" ]; then |
| + echo "EXPECTED-MISS $r: $sweep; witness $wit" | tee "$verdict" |
| + elif [ "$expect" = "rare" ] && [ -n "$depth" ] && [ "$SEEDS" -lt "$depth" ]; then |
| + echo "EXPECTED-MISS $r: $sweep; witness $wit (rare: caught at $depth seeds)" | tee "$verdict" |
| + else |
| + echo "MISSED $r: $sweep; witness $wit" | tee "$verdict" |
| + fi |
| +} |
| +export -f one |
| +export SEEDS BIN SCRATCH WRULES EXPECT ALL |
| +printf '%s\n' $RULES | xargs -P "${RHASIM_PAR:-1}" -I{} bash -c 'one "$@"' _ {} |
| +xrc=$? |
| +if [ $xrc -ne 0 ]; then |
| + echo "sweep: orchestration failed (xargs rc=$xrc)" >&2 |
| + exit 2 |
| +fi |
| +# exactly one well-formed verdict per requested mutation |
| +want=$(printf '%s\n' $RULES | wc -l) |
| +have=$(find "$SCRATCH/verdicts" -type f | wc -l) |
| +if [ "$have" -ne "$want" ]; then |
| + echo "sweep: $want mutation(s) requested, $have verdict(s) written" >&2 |
| + exit 2 |
| +fi |
| +for r in $RULES; do |
| + v="$SCRATCH/verdicts/$(echo "$r" | tr ',' '+')" |
| + if ! grep -qE '^(CAUGHT|MISSED|EXPECTED-MISS|STALE|ERROR) ' "$v" 2>/dev/null; then |
| + echo "sweep: no well-formed verdict for $r" >&2 |
| + exit 2 |
| + fi |
| +done |
| +bad=$(cat "$SCRATCH"/verdicts/* | grep -c "^ERROR\|^MISSED\|^STALE") |
| +if [ "$bad" -gt 0 ]; then |
| + echo "sweep: $bad rule(s) ERROR, MISSED or STALE" >&2 |
| + exit 1 |
| +fi |
| +echo "sweep: all $want rule(s) CAUGHT or expected" |
diff --git a/internal/sim/regionha/rules_test.go b/internal/sim/regionha/rules_test.go| new file mode 100644 |
| index 000000000..582def2de |
| --- /dev/null |
| +++ b/internal/sim/regionha/rules_test.go |
| @@ -0,0 +1,60 @@ |
| +package regionha |
| + |
| +import ( |
| + "os" |
| + "strings" |
| +) |
| + |
| +// Every protocol rule the model enforces has a name here. The mutation |
| +// harness runs one prebuilt test binary with RHASIM_MUTATE set to one rule |
| +// name (or a comma-separated combination) and requires the sweep or the |
| +// rule's witness to violate an invariant. A rule whose mutation nothing |
| +// catches is either redundant or untested, and the run says which. |
| +// |
| +// Never edit `mutated` in place; the harness sets RHASIM_MUTATE. |
| +var mutated = "" |
| + |
| +// RHASIM_MUTATE sets `mutated` for one run of a prebuilt test binary, so |
| +// the mutation harness never edits or copies the source (mutate.sh). |
| +func init() { |
| + if v := os.Getenv("RHASIM_MUTATE"); v != "" { |
| + mutated = v |
| + } |
| +} |
| + |
| +// on reports whether a rule is enforced: false only when the mutation set |
| +// names it. |
| +func on(rule string) bool { |
| + for _, m := range strings.Split(mutated, ",") { |
| + if m == rule { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// allRules is the mutation list, in the plan's order (Task 14), each with |
| +// the code it stands for. The model drives the real decisions |
| +// (hafresh.DecideAcquire, DecideKeep); a mutation changes only what the |
| +// model hands them or does with their answer, the way a regression in a |
| +// caller would. |
| +var allRules = []string{ |
| + // the acquire table and the keep decision (I1, I2; spec §9.4, §5.3) |
| + "expiry-authorizes", // DecideAcquire: another box's expired HA lease is refused, never taken |
| + "keep-without-marker", // DecideKeep reads the lock's marker, never the box's own release record |
| + "keep-unclean", // DecideKeep: an unclean marker never keeps |
| + "same-box-no-proof", // DecideAcquire: this box's own expired lease only with Proofs.SameBoxEmpty |
| + "marker-before-final", // releaseHAClean: Final and Finish, then the record, then the marker; no write after it |
| + |
| + // cleanup, the shared take loop, files and the first wake (r2.1, r2.6) |
| + "cleanup-deletes-lock", // every unclean release writes a marker; lease never deletes an HA lock (r2.1) |
| + "legacy-fallback-on-ha", // a lost condition re-reads and reclassifies; never litestream's AcquireLease (r2.6) |
| + "publisher-outlives-release", // stopFiles joins the publisher (its in-flight snapshot) before Final |
| + "first-wake-ignores-leftovers", // an absent lock is created only over an empty prefix |
| + |
| + // the legacy path, obligations and containment (r3.1, r3.2, r3.3) |
| + "legacy-takes-ha-lock", // takeLegacy answers HALockError for an HA-format lock and writes nothing (r3.1) |
| + "obligation-in-memory-only", // a failed marker PUT is persisted before its error returns (r3.3) |
| + "recover-without-sweep", // sameBoxEmpty needs this agent's startup sweep to have proven every unit stopped (r3.2) |
| + "marker-before-slice-empty", // releaseHAClean holds the release until the host's slice reads empty (r3.2) |
| +} |
diff --git a/internal/sim/regionha/sim_test.go b/internal/sim/regionha/sim_test.go| new file mode 100644 |
| index 000000000..c4d9f1f5b |
| --- /dev/null |
| +++ b/internal/sim/regionha/sim_test.go |
| @@ -0,0 +1,223 @@ |
| +package regionha |
| + |
| +import ( |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "reflect" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// seedsFromEnv is the sweep size: RHASIM_SEEDS, else def. |
| +func seedsFromEnv(def int) int { |
| + if s := os.Getenv("RHASIM_SEEDS"); s != "" { |
| + if n, err := strconv.Atoi(s); err == nil && n > 0 { |
| + return n |
| + } |
| + } |
| + return def |
| +} |
| + |
| +// TestRegionHA is the sweep. RHASIM_SEEDS sets the seed count (default |
| +// 200); RHASIM_SEED=n runs one seed and prints its trace. |
| +func TestRegionHA(t *testing.T) { |
| + if s := os.Getenv("RHASIM_SEED"); s != "" { |
| + seed, err := strconv.ParseInt(s, 10, 64) |
| + if err != nil { |
| + t.Fatalf("RHASIM_SEED=%q: %v", s, err) |
| + } |
| + w := runSeed(seed, true) |
| + for _, line := range w.trace { |
| + t.Log(line) |
| + } |
| + for _, v := range w.violations { |
| + t.Errorf("seed %d: %s", seed, v) |
| + } |
| + return |
| + } |
| + n := seedsFromEnv(200) |
| + failed := 0 |
| + count := map[string]int{} |
| + firstSeed := map[string]int64{} |
| + stats, done, events := map[string]int{}, map[string]int{}, map[string]int{} |
| + for seed := int64(1); seed <= int64(n); seed++ { |
| + w := runSeed(seed, false) |
| + for k, v := range w.stats { |
| + stats[k] += v |
| + } |
| + for k, v := range w.done { |
| + done[k] += v |
| + } |
| + for k, v := range w.events { |
| + events[k] += v |
| + } |
| + if len(w.violations) == 0 { |
| + continue |
| + } |
| + failed++ |
| + for _, v := range w.violations { |
| + id := invariantOf(v) |
| + count[id]++ |
| + if _, ok := firstSeed[id]; !ok { |
| + firstSeed[id] = seed |
| + t.Logf("seed %d: %s", seed, v) |
| + } |
| + } |
| + } |
| + t.Logf("%d seeds, %d failed; mutated=%q", n, failed, mutated) |
| + t.Logf("actions chosen: %v", stats) |
| + t.Logf("actions completed: %v", done) |
| + t.Logf("events: %v", events) |
| + ids := make([]string, 0, len(count)) |
| + for id := range count { |
| + ids = append(ids, id) |
| + } |
| + sort.Strings(ids) |
| + for _, id := range ids { |
| + t.Logf(" %4d x %s (first seed %d)", count[id], id, firstSeed[id]) |
| + } |
| + if failed > 0 { |
| + t.Fatalf("%d of %d seeds violated an invariant", failed, n) |
| + } |
| +} |
| + |
| +// TestSeedDeterministic: one seed gives one trace, or no reported seed can |
| +// be replayed. |
| +func TestSeedDeterministic(t *testing.T) { |
| + a, b := runSeed(7, false), runSeed(7, false) |
| + if len(a.trace) == 0 { |
| + t.Fatal("the trace is empty, so equality proves nothing") |
| + } |
| + if !reflect.DeepEqual(a.trace, b.trace) || !reflect.DeepEqual(a.events, b.events) || !reflect.DeepEqual(a.violations, b.violations) { |
| + t.Fatal("two runs of seed 7 differ") |
| + } |
| + sizes := map[int]bool{} |
| + for s := int64(1); s <= 20; s++ { |
| + sizes[len(newWorld(s, false).boxes)] = true |
| + } |
| + for n := 2; n <= 5; n++ { |
| + if !sizes[n] { |
| + t.Errorf("no seed of 1 to 20 has %d boxes", n) |
| + } |
| + } |
| +} |
| + |
| +// TestMain handles RHASIM_LIST=1 before any test runs: it prints the rules |
| +// a run would check, one per line, and exits 0 without running a test (the |
| +// mutation harness reads this list). |
| +func TestMain(m *testing.M) { |
| + if os.Getenv("RHASIM_LIST") == "1" { |
| + for _, r := range allRules { |
| + fmt.Println(r) |
| + } |
| + os.Exit(0) |
| + } |
| + os.Exit(m.Run()) |
| +} |
| + |
| +// TestListPrintsRulesAndRunsNothing runs this test binary with |
| +// RHASIM_LIST=1 and requires exactly the rule list, and no test run. |
| +func TestListPrintsRulesAndRunsNothing(t *testing.T) { |
| + run := func(list bool) string { |
| + cmd := exec.Command(os.Args[0], "-test.v", "-test.run=TestOnMutation") |
| + for _, kv := range os.Environ() { |
| + if !strings.HasPrefix(kv, "RHASIM_LIST=") { |
| + cmd.Env = append(cmd.Env, kv) |
| + } |
| + } |
| + if list { |
| + cmd.Env = append(cmd.Env, "RHASIM_LIST=1") |
| + } |
| + out, err := cmd.Output() |
| + if err != nil { |
| + t.Fatalf("list=%v: %v", list, err) |
| + } |
| + return string(out) |
| + } |
| + if control := run(false); !strings.Contains(control, "=== RUN") { |
| + t.Fatalf("control run printed no test markers: %q", control) |
| + } |
| + want := "" |
| + for _, r := range allRules { |
| + want += r + "\n" |
| + } |
| + if got := run(true); got != want { |
| + t.Fatalf("RHASIM_LIST=1 output = %q, want exactly the rule list %q", got, want) |
| + } |
| +} |
| + |
| +// TestOnMutation: on is false only for a rule named in the mutation set. |
| +func TestOnMutation(t *testing.T) { |
| + saved := mutated |
| + defer func() { mutated = saved }() |
| + mutated = "" |
| + if !on("any-rule") { |
| + t.Fatal("no mutation: every rule is on") |
| + } |
| + mutated = "a-rule,b-rule" |
| + if on("a-rule") || on("b-rule") || !on("c-rule") { |
| + t.Fatal("only the named rules are off") |
| + } |
| +} |
| + |
| +// TestFailOncePerInvariant: fail keeps the first violation of each |
| +// invariant id. |
| +func TestFailOncePerInvariant(t *testing.T) { |
| + w := newWorld(1, false) |
| + w.fail("I1", "first %d", 1) |
| + w.fail("I1", "second %d", 2) |
| + w.fail("I2", "other") |
| + if len(w.violations) != 2 || w.violations[0] != "I1: first 1" || w.violations[1] != "I2: other" { |
| + t.Fatalf("violations = %v", w.violations) |
| + } |
| +} |
| + |
| +// TestEveryActionFires: over 200 seeds of the unmutated walk every action |
| +// completes a transition, and every protocol path a rule guards is |
| +// reached: a rule that guards a path no seed takes is untested however |
| +// green the sweep looks. |
| +func TestEveryActionFires(t *testing.T) { |
| + saved := mutated |
| + mutated = "" |
| + defer func() { mutated = saved }() |
| + names := map[string]bool{} |
| + for _, a := range actions { |
| + if names[a.name] { |
| + t.Errorf("action %q registered twice", a.name) |
| + } |
| + names[a.name] = true |
| + if a.weight <= 0 { |
| + t.Errorf("action %q has weight %d", a.name, a.weight) |
| + } |
| + } |
| + done, events := map[string]int{}, map[string]int{} |
| + for seed := int64(1); seed <= 200; seed++ { |
| + w := runSeed(seed, false) |
| + for k, v := range w.done { |
| + done[k] += v |
| + } |
| + for k, v := range w.events { |
| + events[k] += v |
| + } |
| + } |
| + for _, a := range actions { |
| + if done[a.name] == 0 { |
| + t.Errorf("action %q never completed a transition over 200 seeds", a.name) |
| + } |
| + } |
| + for _, e := range []string{ |
| + "served", "fresh", "kept", "restored", "same-box-retake", |
| + "refused-held", "refused-other-expired", "refused-same-box", "refused-leftover-data", |
| + "reclassified", "late-ack", "failed-restore", "failed-after-replication", |
| + "marker-clean", "marker-unclean", "marker-owed", "obligation-discharged", |
| + "release-held", "ha-lock-on-legacy-path", "hang-resumed", "manifest-committed", |
| + } { |
| + if events[e] == 0 { |
| + t.Errorf("no %s over 200 seeds", e) |
| + } |
| + } |
| + t.Logf("completed: %v; events: %v", done, events) |
| +} |
diff --git a/internal/sim/regionha/witness_test.go b/internal/sim/regionha/witness_test.go| new file mode 100644 |
| index 000000000..34c2c63d9 |
| --- /dev/null |
| +++ b/internal/sim/regionha/witness_test.go |
| @@ -0,0 +1,469 @@ |
| +package regionha |
| + |
| +import ( |
| + "fmt" |
| + "math/rand" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// Witness scenarios, in the engines model's shape |
| +// (internal/sim/engines/witness_test.go). |
| +// |
| +// The random sweep reaches some interleavings rarely. A witness is one |
| +// fixed, hand-scheduled scenario for one rule: it forces exactly the |
| +// interleaving the rule exists for, and draws nothing from the world's |
| +// RNG. It must hold (no invariant violated) with the rules in place, and |
| +// violate its named invariant when the rule's mutation is applied. Where |
| +// the plan names the witness (Task 14), the note says so. |
| +// |
| +// A witness calls w.check() at each step boundary, as doStep does in the |
| +// sweep; I5 is checked where the scenario ends (checkLiveness). |
| + |
| +type witness struct { |
| + rule string // the rule it is for |
| + needs string // the mutation set under which it must violate |
| + want string // the invariant the first violation names |
| + note string |
| + run func(t *testing.T, w *world) |
| +} |
| + |
| +var witnesses = []witness{ |
| + {"expiry-authorizes", "expiry-authorizes", "I1", |
| + "plan: a hang past the TTL, then another box's wake, is refused; taken on expiry, the new box runs beside the hung one", wHangPastTTL}, |
| + {"keep-without-marker", "keep-without-marker", "I2", |
| + "A releases clean, B wakes, writes and releases clean; A's own release record still matches its copy, so trusting it in place of the lock's marker (B's) serves A's old copy", wKeepWithoutMarker}, |
| + {"keep-unclean", "keep-unclean", "I2", |
| + "plan: a matching but unclean marker restores; the final files publish was incomplete, so keeping serves files S3 does not hold", wUncleanMarkerRestores}, |
| + {"same-box-no-proof", "same-box-no-proof", "I1", |
| + "the agent crashes, its unit outlives it and the restarted agent's sweep fails; re-taking the expired lease without the proof runs a second unit beside the orphan", wSameBoxNoProof}, |
| + {"marker-before-final", "marker-before-final", "I1", |
| + "a write not yet uploaded at sleep; a marker before the final sync lets that sync upload after the lease is released", wMarkerBeforeFinal}, |
| + {"cleanup-deletes-lock", "cleanup-deletes-lock", "I5", |
| + "plan: a late acknowledgement leaves an unclean marker; a delete there strands the host's data behind an absent lock", wLateAckUncleanMarker}, |
| + {"cleanup-deletes-lock", "cleanup-deletes-lock", "I5", |
| + "r2.1: a failure after replication starts releases through Close, with an unclean marker; a delete strands the replicated data", wFailAfterReplication}, |
| + {"legacy-fallback-on-ha", "legacy-fallback-on-ha", "I1", |
| + "plan: a lock rewritten between GET and PUT is reclassified; B takes the marker C read, crashes with its unit running, and expires; litestream's AcquireLease takes it", wRewrittenBetweenGetAndPut}, |
| + {"publisher-outlives-release", "publisher-outlives-release", "I1", |
| + "a snapshot is in flight at sleep; a publisher not joined commits it after the marker", wPublisherOutlivesRelease}, |
| + {"first-wake-ignores-leftovers", "first-wake-ignores-leftovers", "I2", |
| + "objects under an absent lock; a first wake over them boots fresh while S3 holds another history", wFirstWakeOverLeftovers}, |
| + {"legacy-takes-ha-lock", "legacy-takes-ha-lock", "I1", |
| + "r3.1: a box with a stale negative index entry wakes the host by the legacy path while its holder hangs past the TTL; the legacy acquire takes the expired HA lock", wLegacyTakesHALock}, |
| + {"obligation-in-memory-only", "obligation-in-memory-only", "I5", |
| + "plan: a failed marker PUT, then an agent restart, then a retry after expiry, then another box acquires; an obligation kept in memory only is gone after the restart", wFailedMarkerRetried}, |
| + {"recover-without-sweep", "recover-without-sweep", "I1", |
| + "the agent crashes and its sweep fails; the orphan is between restarts, so the slice reads empty; recovery without the sweep's proof runs beside it once systemd restarts it", wRecoverWithoutSweep}, |
| + {"marker-before-slice-empty", "marker-before-slice-empty", "I1", |
| + "r3.2: a unit of the host outlives the stop; the release waits for the slice, and a marker before it lets another box run beside the straggler", wStragglerHoldsRelease}, |
| +} |
| + |
| +// TestWitnesses is the deterministic half of the mutation evidence. |
| +// |
| +// With no mutation it proves every witness's claim in full: the scenario |
| +// holds with every rule in place, holds under every proper subset of its |
| +// mutation set, and under the whole set violates the invariant it names. |
| +// |
| +// Under RHASIM_MUTATE=m (the harness) it runs the witnesses of the rules in |
| +// m; a witness whose set is within m must violate with its named failure. |
| +// RHASIM_WITNESS=rule runs one rule's witnesses with their trace. |
| +func TestWitnesses(t *testing.T) { |
| + only := os.Getenv("RHASIM_WITNESS") |
| + if mutated == "" { |
| + ran := 0 |
| + for _, x := range witnesses { |
| + if only != "" && x.rule != only { |
| + continue |
| + } |
| + ran++ |
| + check(t, x, "", false, only != "") |
| + for _, s := range properSubsets(x.needs) { |
| + check(t, x, s, false, only != "") |
| + } |
| + check(t, x, x.needs, true, only != "") |
| + } |
| + if only != "" && ran == 0 { |
| + t.Fatalf("no witness for rule %q", only) |
| + } |
| + return |
| + } |
| + set := mutationSet(mutated) |
| + for _, x := range witnesses { |
| + if only != "" && x.rule != only { |
| + continue |
| + } |
| + if !set[x.rule] { |
| + continue |
| + } |
| + needs := true |
| + for _, m := range strings.Split(x.needs, ",") { |
| + needs = needs && set[m] |
| + } |
| + if needs { |
| + check(t, x, mutated, true, only != "") |
| + continue |
| + } |
| + report(t, x, mutated, only != "") |
| + } |
| +} |
| + |
| +// TestWitnessRulesKnown: every witness names a rule in allRules, and every |
| +// rule has a witness, so every mutation is caught deterministically, not |
| +// only by a seed the sweep happens to reach. |
| +func TestWitnessRulesKnown(t *testing.T) { |
| + known, has := map[string]bool{}, map[string]bool{} |
| + for _, r := range allRules { |
| + known[r] = true |
| + } |
| + for _, x := range witnesses { |
| + if !known[x.rule] { |
| + t.Errorf("witness for unknown rule %q", x.rule) |
| + } |
| + for _, m := range strings.Split(x.needs, ",") { |
| + if !known[m] { |
| + t.Errorf("witness %s needs unknown rule %q", x.rule, m) |
| + } |
| + } |
| + has[x.rule] = true |
| + } |
| + for _, r := range allRules { |
| + if !has[r] { |
| + t.Errorf("rule %q has no witness", r) |
| + } |
| + } |
| +} |
| + |
| +func report(t *testing.T, x witness, m string, trace bool) { |
| + saved := mutated |
| + mutated = m |
| + defer func() { mutated = saved }() |
| + w := newWitness() |
| + x.run(t, w) |
| + tag := "held" |
| + if len(w.violations) > 0 { |
| + tag = "violated: " + w.violations[0] |
| + } |
| + t.Logf("witness %s under %q (needs %q): %s", x.rule, m, x.needs, tag) |
| + if trace { |
| + dump(t, w) |
| + } |
| +} |
| + |
| +// check runs one witness under mutation m and fails the test unless the |
| +// outcome is the stated one: held when no violation is expected, the named |
| +// failure when one is. |
| +func check(t *testing.T, x witness, m string, expectViolation bool, trace bool) { |
| + saved := mutated |
| + mutated = m |
| + defer func() { mutated = saved }() |
| + w := newWitness() |
| + x.run(t, w) |
| + violated := len(w.violations) > 0 |
| + tag := "held" |
| + if violated { |
| + tag = "violated: " + w.violations[0] |
| + } |
| + t.Logf("witness %s under %q (needs %q): %s", x.rule, m, x.needs, tag) |
| + switch { |
| + case expectViolation && !violated: |
| + t.Errorf("witness %s held under %q, which it must violate", x.rule, m) |
| + dump(t, w) |
| + case expectViolation && invariantOf(w.violations[0]) != x.want: |
| + t.Errorf("witness %s under %q violated, but not its named failure %q", x.rule, m, x.want) |
| + dump(t, w) |
| + case !expectViolation && violated: |
| + t.Errorf("witness %s violated under %q, where it must hold", x.rule, m) |
| + dump(t, w) |
| + } |
| + if trace { |
| + dump(t, w) |
| + } |
| +} |
| + |
| +func mutationSet(m string) map[string]bool { |
| + set := map[string]bool{} |
| + for _, x := range strings.Split(m, ",") { |
| + if x != "" { |
| + set[x] = true |
| + } |
| + } |
| + return set |
| +} |
| + |
| +// properSubsets: every non-empty proper subset of a comma-separated set. |
| +func properSubsets(needs string) []string { |
| + xs := strings.Split(needs, ",") |
| + var out []string |
| + for mask := 1; mask < (1<<len(xs))-1; mask++ { |
| + var sub []string |
| + for i, x := range xs { |
| + if mask&(1<<i) != 0 { |
| + sub = append(sub, x) |
| + } |
| + } |
| + out = append(out, strings.Join(sub, ",")) |
| + } |
| + return out |
| +} |
| + |
| +func dump(t *testing.T, w *world) { |
| + for _, line := range w.trace { |
| + t.Log(line) |
| + } |
| + t.Logf("state: %s", w.boxesState()) |
| +} |
| + |
| +func (w *world) boxesState() string { |
| + var out []string |
| + for _, b := range w.boxes { |
| + var hs []string |
| + for _, h := range w.hosts { |
| + n := 0 |
| + for _, u := range b.Units[h] { |
| + if u.Running { |
| + n++ |
| + } |
| + } |
| + hs = append(hs, fmt.Sprintf("%s{awake %v units %d owed %v}", h, b.Entries[h] != nil, n, b.Owed[h] != nil)) |
| + } |
| + out = append(out, fmt.Sprintf("box%d(%s pid %d swept %v %s)", b.ID, b.Agent, b.PID, b.Swept, strings.Join(hs, " "))) |
| + } |
| + for _, h := range w.hosts { |
| + out = append(out, h+": "+w.lockString(h)) |
| + } |
| + return strings.Join(out, "; ") |
| +} |
| + |
| +// ---- the witness world ---- |
| + |
| +const sh = "shop" |
| + |
| +// newWitness is three nested boxes (A, B, C), one born-HA host, no stale |
| +// index entries, every lock absent and every prefix empty. It never draws |
| +// from its RNG. |
| +func newWitness() *world { |
| + w := newWorldN(1, rand.New(rand.NewSource(1)), 3, []string{sh}) |
| + w.scripted = true |
| + return w |
| +} |
| + |
| +func (w *world) abc() (*box, *box, *box) { return w.boxes[0], w.boxes[1], w.boxes[2] } |
| + |
| +// req is a request's wake of the host at b, then the step boundary. |
| +func (w *world) req(b *box, o wakeOpts) string { |
| + r := w.wake(b, sh, o, nil) |
| + w.logf("box%d: wake: %s", b.ID, r) |
| + w.check() |
| + return r |
| +} |
| + |
| +// serve is a wake that must serve: a witness's setup. |
| +func (w *world) serve(t *testing.T, b *box) { |
| + if r := w.req(b, wakeOpts{}); r != "served" { |
| + t.Errorf("setup: box%d's wake: %s", b.ID, r) |
| + } |
| +} |
| + |
| +func (w *world) write(b *box, filesToo bool) { w.tenantWrite(b, sh, filesToo); w.check() } |
| +func (w *world) syncNow(b *box, ckpt bool) { w.sync(b, sh, ckpt); w.check() } |
| +func (w *world) sleepNow(b *box, o sleepOpts) { w.sleep(b, sh, o); w.check() } |
| + |
| +// expect is an assertion about the rule's own behaviour: it applies only |
| +// while that rule is in place (under its mutation the witness is meant to |
| +// go wrong). |
| +func expect(t *testing.T, rule string, ok bool, format string, args ...any) { |
| + if on(rule) && !ok { |
| + t.Errorf(rule+": "+format, args...) |
| + } |
| +} |
| + |
| +func wHangPastTTL(t *testing.T, w *world) { |
| + A, B, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, false) |
| + w.syncNow(A, false) |
| + w.hang(A, ttlTicks+3) |
| + w.advance(ttlTicks + 1) |
| + r := w.req(B, wakeOpts{}) |
| + expect(t, "expiry-authorizes", r == "refused: "+hafresh.ReasonOtherExpired, "B's wake over A's expired lease: %s", r) |
| + w.advance(3) // A resumes: it syncs, and renews |
| +} |
| + |
| +func wKeepWithoutMarker(t *testing.T, w *world) { |
| + A, B, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, false) |
| + w.syncNow(A, true) |
| + w.sleepNow(A, sleepOpts{}) |
| + w.serve(t, B) |
| + w.write(B, false) |
| + w.syncNow(B, true) |
| + w.sleepNow(B, sleepOpts{}) |
| + restored := w.events["restored"] |
| + w.req(A, wakeOpts{}) |
| + expect(t, "keep-without-marker", w.events["restored"] == restored+1, "A, under B's marker, did not restore") |
| +} |
| + |
| +func wUncleanMarkerRestores(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, true) |
| + w.syncNow(A, true) |
| + w.sleepNow(A, sleepOpts{FinalIncomplete: true}) |
| + v := w.view(sh) |
| + expect(t, "keep-unclean", v.Lock.Release != nil && !v.Lock.Release.Clean, "the release left %s, not an unclean marker", w.lockString(sh)) |
| + restored := w.events["restored"] |
| + w.req(A, wakeOpts{}) |
| + expect(t, "keep-unclean", w.events["restored"] == restored+1, "A, under its own unclean marker, did not restore") |
| +} |
| + |
| +func wSameBoxNoProof(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + w.serve(t, A) |
| + w.crash(A) |
| + w.restart(A, false) |
| + w.check() |
| + w.advance(ttlTicks + 1) |
| + r := w.req(A, wakeOpts{}) |
| + expect(t, "same-box-no-proof", r == "refused: "+hafresh.ReasonSameBoxUnsure, "A's own expired lease, unproven: %s", r) |
| +} |
| + |
| +func wMarkerBeforeFinal(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, false) |
| + w.sleepNow(A, sleepOpts{}) |
| + v := w.view(sh) |
| + expect(t, "marker-before-final", v.Lock.Release != nil && v.Lock.Release.Clean && v.Lock.Release.TXID == w.s3[sh].MaxTXID, |
| + "the clean marker does not name the final position: %s, head %d", w.lockString(sh), w.s3[sh].MaxTXID) |
| +} |
| + |
| +func wLateAckUncleanMarker(t *testing.T, w *world) { |
| + A, B, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, true) |
| + w.syncNow(A, false) |
| + w.sleepNow(A, sleepOpts{}) |
| + w.req(B, wakeOpts{LateAck: true}) |
| + v := w.view(sh) |
| + expect(t, "cleanup-deletes-lock", v.Lock.Release != nil && !v.Lock.Release.Clean && v.Lock.Release.Box == B.Self.Ref, |
| + "a late acknowledgement left %s, not B's unclean marker", w.lockString(sh)) |
| + w.checkLiveness() |
| +} |
| + |
| +func wFailAfterReplication(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + r := w.req(A, wakeOpts{FailAfterRepl: true}) |
| + if r != "failed after replication" { |
| + t.Errorf("setup: %s", r) |
| + } |
| + v := w.view(sh) |
| + expect(t, "cleanup-deletes-lock", v.Lock.Release != nil && !v.Lock.Release.Clean, "Close left %s, not an unclean marker", w.lockString(sh)) |
| + w.checkLiveness() |
| +} |
| + |
| +func wRewrittenBetweenGetAndPut(t *testing.T, w *world) { |
| + A, B, C := w.abc() |
| + w.serve(t, A) |
| + w.sleepNow(A, sleepOpts{}) |
| + v := w.view(sh) |
| + if why := w.classify(C, sh, v); why != "" { |
| + t.Errorf("setup: C classifies the marker: %s", why) |
| + } |
| + C.Pending[sh] = &pending{View: v, At: w.step} |
| + w.serve(t, B) // the lock is rewritten under C's read |
| + w.crash(B) // B's unit outlives its agent |
| + w.check() |
| + w.advance(ttlTicks + 1) |
| + pd := C.Pending[sh] |
| + delete(C.Pending, sh) |
| + reclassified := w.events["reclassified"] |
| + r := w.wake(C, sh, wakeOpts{}, pd) |
| + w.check() |
| + expect(t, "legacy-fallback-on-ha", w.events["reclassified"] == reclassified+1 && r == "refused: "+hafresh.ReasonOtherExpired, |
| + "C's PUT over a lock rewritten since its GET: %s", r) |
| +} |
| + |
| +func wPublisherOutlivesRelease(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, true) |
| + w.startSnapshot(A, sh, 2) |
| + w.sleepNow(A, sleepOpts{}) |
| + w.advance(2) |
| + expect(t, "publisher-outlives-release", len(A.Strays) == 0 && w.s3[sh].Files == A.Local[sh].Files, |
| + "the manifest holds %+v, the released tree %+v", w.s3[sh].Files, A.Local[sh].Files) |
| +} |
| + |
| +func wFirstWakeOverLeftovers(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + w.plant(sh) |
| + r := w.req(A, wakeOpts{}) |
| + expect(t, "first-wake-ignores-leftovers", r == "refused: leftover data", "a first wake over leftovers: %s", r) |
| +} |
| + |
| +func wLegacyTakesHALock(t *testing.T, w *world) { |
| + A, B, _ := w.abc() |
| + B.StaleNeg[sh] = true |
| + w.serve(t, A) |
| + w.hang(A, ttlTicks+3) |
| + w.advance(ttlTicks + 1) |
| + r := w.req(B, wakeOpts{}) |
| + expect(t, "legacy-takes-ha-lock", !B.StaleNeg[sh] && r == "refused: "+hafresh.ReasonOtherExpired, |
| + "B's stale index over an HA lock: %s (still stale %v)", r, B.StaleNeg[sh]) |
| + w.advance(3) |
| +} |
| + |
| +func wFailedMarkerRetried(t *testing.T, w *world) { |
| + A, B, _ := w.abc() |
| + w.serve(t, A) |
| + w.write(A, false) |
| + w.syncNow(A, true) |
| + w.sleepNow(A, sleepOpts{MarkerFails: true}) |
| + w.crash(A) |
| + w.restart(A, true) |
| + w.check() |
| + w.advance(ttlTicks + 1) |
| + if ob := A.Owed[sh]; ob != nil { |
| + w.retryObligation(A, ob, false) // the sweep's retry, after expiry |
| + w.check() |
| + } |
| + r := w.req(B, wakeOpts{}) |
| + expect(t, "obligation-in-memory-only", r == "served", "B after the owed marker's retry: %s", r) |
| + w.checkLiveness() |
| +} |
| + |
| +func wRecoverWithoutSweep(t *testing.T, w *world) { |
| + A, _, _ := w.abc() |
| + w.serve(t, A) |
| + w.crash(A) |
| + for _, u := range A.Units[sh] { |
| + u.Running, u.BackAt = false, 1<<30 // between restarts: the slice reads empty |
| + } |
| + w.restart(A, false) |
| + w.check() |
| + w.advance(ttlTicks + 1) |
| + r := w.req(A, wakeOpts{}) |
| + expect(t, "recover-without-sweep", r == "refused: "+hafresh.ReasonSameBoxUnsure, "A's recovery without its sweep: %s", r) |
| + for _, u := range A.Units[sh] { |
| + if u.Orphan && !u.Running { |
| + u.Running = true // systemd restarts the orphan |
| + w.logf("box%d: %s: systemd restarts the orphan unit", A.ID, sh) |
| + } |
| + } |
| + w.check() |
| +} |
| + |
| +func wStragglerHoldsRelease(t *testing.T, w *world) { |
| + A, B, _ := w.abc() |
| + w.serve(t, A) |
| + w.sleepNow(A, sleepOpts{Straggler: 5}) |
| + r := w.req(B, wakeOpts{}) |
| + expect(t, "marker-before-slice-empty", strings.HasPrefix(r, "refused: held"), "B while A's straggler runs: %s", r) |
| + w.advance(6) |
| + expect(t, "marker-before-slice-empty", w.view(sh).Lock.Release != nil, "the held release never finished: %s", w.lockString(sh)) |
| +} |
diff --git a/internal/sim/regionha/world_test.go b/internal/sim/regionha/world_test.go| new file mode 100644 |
| index 000000000..697a50a4c |
| --- /dev/null |
| +++ b/internal/sim/regionha/world_test.go |
| @@ -0,0 +1,558 @@ |
| +package regionha |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "math/rand" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// The model of region HA P1a for born-HA hosts (spec |
| +// docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md §5, |
| +// §9.4, §9.6, §21.1; plan Task 14). Two to five boxes share one S3. Every |
| +// decision a box makes about a lock or a local copy is the real one |
| +// (hafresh.DecideAcquire, DecideKeep, read through DecodeLock, written |
| +// through OwnerFor and MarkerBody); the model supplies the I/O around them |
| +// and the release ordering of Tasks 6, 7 and 10 (lease.AcquireHA's |
| +// classify-and-take loop, releaseWithMarker and its obligations, and |
| +// activator.releaseHAClean). |
| +// |
| +// One step is one tick, a minute: lease.LeaseTTL is 15 minutes, so a lease |
| +// expires 15 ticks after its last renewal. Everything is decided from one |
| +// seeded source; nothing reads the clock, starts a goroutine or lets a |
| +// map's iteration order choose. |
| + |
| +const ( |
| + chaosSteps = 400 // faults and every action are eligible |
| + calmSteps = 200 // no new faults: the same walk lets the world settle |
| + settleTicks = 20 // final: ticks with every fault cleared, before the liveness oracle |
| + ttlTicks = 15 // lease.LeaseTTL, in ticks |
| + renewWithin = 5 // the renewer renews once fewer than this many ticks remain |
| +) |
| + |
| +const tick = time.Minute |
| + |
| +var epoch = time.Date(2026, 10, 26, 0, 0, 0, 0, time.UTC) |
| + |
| +// files is a files tree's content: a version, and whether a publish of it |
| +// skipped an entry (an incomplete Final commits what it could read). |
| +type files struct { |
| + Ver int |
| + Partial bool |
| +} |
| + |
| +// ltx is one LTX upload to a host's replica chain. |
| +type ltx struct { |
| + TXID uint64 |
| + Ver int |
| + Box, PID int |
| +} |
| + |
| +// prefix is one host's hibernate prefix in S3: lock.json (its body and |
| +// ETag; no ETag is no lock), the replica chain with its head, and the files |
| +// manifest (generation 0 is none). Planted marks objects the leftover |
| +// action wrote, not any box under a lease. |
| +type prefix struct { |
| + Lock []byte |
| + ETag string |
| + Chain []ltx |
| + MaxTXID uint64 |
| + HeadVer int |
| + Gen int |
| + Files files |
| + Planted bool |
| +} |
| + |
| +// empty is lease.PrefixEmpty: nothing at all stored under the prefix but |
| +// lock.json (one LIST, max-keys 1). |
| +func (p *prefix) empty() bool { return len(p.Chain) == 0 && p.Gen == 0 && !p.Planted } |
| + |
| +// localCopy is one box's local state of a host: the database file's |
| +// identity, its WAL, its position and content, the files tree, and the |
| +// release record <db>.release.json. |
| +type localCopy struct { |
| + DBExists bool |
| + DB hafresh.FileID |
| + WALEmpty bool |
| + TXID uint64 |
| + Ver int |
| + Tree bool |
| + Files files |
| + TreeMeta int64 |
| + Record *hafresh.LocalRecord |
| +} |
| + |
| +// digest is the files tree digest: metadata only, so any change to the |
| +// tree changes it. "" when there is no tree. |
| +func (l *localCopy) digest() string { |
| + if !l.Tree { |
| + return "" |
| + } |
| + return fmt.Sprintf("tree-%d", l.TreeMeta) |
| +} |
| + |
| +// now is readLocalNow over the copy. |
| +func (l *localCopy) now() hafresh.LocalNow { |
| + n := hafresh.LocalNow{DBExists: l.DBExists, DB: l.DB, WALEmpty: l.WALEmpty, TreeDigest: l.digest()} |
| + if l.Record != nil { |
| + n.HaveRecord, n.Record = true, *l.Record |
| + } |
| + return n |
| +} |
| + |
| +// unit is one systemd unit of a host on a box, under the host's slice. A |
| +// main unit is the wake's; a straggler is a unit of the host the stop did |
| +// not cover, which exits on its own at ExitAt; an orphan is a unit whose |
| +// agent died. An orphan that is not Running is between restarts: its slice |
| +// reads empty, and systemd starts it again at BackAt. |
| +type unit struct { |
| + Running bool |
| + Straggler bool |
| + ExitAt int |
| + Orphan bool |
| + BackAt int |
| +} |
| + |
| +type snapshot struct { |
| + Files files |
| + DoneAt int |
| +} |
| + |
| +// publisher is an awake HA host's files publisher (activator.hostFiles): |
| +// the manifest generation it last committed, what it committed, and the |
| +// snapshot it has in flight. Its commits are conditional on Gen; a commit |
| +// that finds another generation breaks it (superseded), and its Final then |
| +// fails. |
| +type publisher struct { |
| + Box, PID int |
| + Host string |
| + Gen int |
| + Last files |
| + Inflight *snapshot |
| + Broken bool |
| +} |
| + |
| +// entry is an awake host in an agent's memory: the lease it holds (ETag, |
| +// generation, expiry), the view its acquire classified, the replicator's |
| +// uploaded position and the files publisher. Releasing is set once the |
| +// sleep has stopped the main unit, while the release waits for the host's |
| +// slice to read empty. |
| +type entry struct { |
| + Host string |
| + HA bool |
| + ETag string |
| + Gen int64 |
| + Expires time.Time |
| + View hafresh.View |
| + Uploaded uint64 |
| + Pub *publisher |
| + Releasing *sleepOpts |
| +} |
| + |
| +// obligation is an owed marker write: Body to the host's lock.json, |
| +// If-Match ETag. |
| +type obligation struct { |
| + Host, ETag string |
| + Body []byte |
| +} |
| + |
| +// pending is an acquire between its GET and its PUT: the view it read and |
| +// classified. |
| +type pending struct { |
| + View hafresh.View |
| + At int |
| +} |
| + |
| +type agentState int |
| + |
| +const ( |
| + agentUp agentState = iota |
| + agentHung |
| + agentDown |
| +) |
| + |
| +func (a agentState) String() string { |
| + switch a { |
| + case agentHung: |
| + return "hung" |
| + case agentDown: |
| + return "down" |
| + } |
| + return "up" |
| +} |
| + |
| +// box is one box of the region. Self is its lease identity (reference and |
| +// instance id, both known); PID is its agent process's. Swept is this |
| +// agent's startup sweep, AcquiredHere the hosts this agent process took. |
| +// StaleNeg is a stale negative entry in its lifetime index: it believes the |
| +// host legacy. Owed is the obligation store in memory, Disk what of it is |
| +// on disk. |
| +type box struct { |
| + ID int |
| + Self hafresh.Self |
| + PID int |
| + Agent agentState |
| + HungTill int |
| + Swept bool |
| + AcquiredHere map[string]bool |
| + StaleNeg map[string]bool |
| + Local map[string]*localCopy |
| + Entries map[string]*entry |
| + Units map[string][]*unit |
| + Owed map[string]*obligation |
| + Disk map[string]*obligation |
| + Pending map[string]*pending |
| + Strays []*publisher |
| +} |
| + |
| +type world struct { |
| + seed int64 |
| + rng *rand.Rand |
| + boxes []*box |
| + hosts []string |
| + s3 map[string]*prefix |
| + step int |
| + trace []string |
| + violations []string |
| + stats map[string]int // actions selected, by name |
| + done map[string]int // actions whose transition completed, by name |
| + events map[string]int // protocol outcomes, by name |
| + |
| + // owed is the oracle's record of every marker whose PUT failed, by |
| + // host and the ETag it was conditioned on: if the lock still carries |
| + // that ETag at the end, the marker was never written (I5). |
| + owed map[string]map[string]bool |
| + |
| + clock, nextETag, nextPID, nextInode, nextVer int64 |
| + |
| + // scripted is a witness's world: the timers run (expiry, hang ends, |
| + // stragglers exiting, snapshots finishing, renewals, held releases), |
| + // but nothing random does. A witness calls every sync, snapshot start, |
| + // obligation retry and orphan restart itself. |
| + scripted bool |
| + verbose bool |
| +} |
| + |
| +// action is one thing the random walk can do. run reports whether the |
| +// transition completed: false when it found nothing to act on. A refusal |
| +// by the protocol is a completed transition. |
| +type action struct { |
| + name string |
| + weight int |
| + run func(*world) bool |
| +} |
| + |
| +var actions []action |
| + |
| +func newWorld(seed int64, verbose bool) *world { |
| + rng := rand.New(rand.NewSource(seed)) |
| + n := 2 + rng.Intn(4) |
| + w := newWorldN(seed, rng, n, []string{"blog", "docs", "shop"}) |
| + w.verbose = verbose |
| + // A stale negative index entry: the box indexed an older, legacy |
| + // incarnation of the host (r3.1). |
| + for _, b := range w.boxes { |
| + for _, h := range w.hosts { |
| + if w.rng.Intn(5) == 0 { |
| + b.StaleNeg[h] = true |
| + } |
| + } |
| + } |
| + w.logf("world seed %d: %d boxes, hosts %v, stale negative entries %s", seed, n, w.hosts, w.staleString()) |
| + return w |
| +} |
| + |
| +func newWorldN(seed int64, rng *rand.Rand, n int, hosts []string) *world { |
| + w := &world{ |
| + seed: seed, |
| + rng: rng, |
| + hosts: hosts, |
| + s3: map[string]*prefix{}, |
| + stats: map[string]int{}, |
| + done: map[string]int{}, |
| + events: map[string]int{}, |
| + owed: map[string]map[string]bool{}, |
| + nextPID: 100, |
| + } |
| + for _, h := range hosts { |
| + w.s3[h] = &prefix{} |
| + w.owed[h] = map[string]bool{} |
| + } |
| + for i := 0; i < n; i++ { |
| + w.boxes = append(w.boxes, &box{ |
| + ID: i, |
| + Self: hafresh.Self{Ref: fmt.Sprintf("box%d", i), IID: fmt.Sprintf("i-%04d", i)}, |
| + PID: w.newPID(), |
| + Swept: true, |
| + AcquiredHere: map[string]bool{}, |
| + StaleNeg: map[string]bool{}, |
| + Local: map[string]*localCopy{}, |
| + Entries: map[string]*entry{}, |
| + Units: map[string][]*unit{}, |
| + Owed: map[string]*obligation{}, |
| + Disk: map[string]*obligation{}, |
| + Pending: map[string]*pending{}, |
| + }) |
| + } |
| + return w |
| +} |
| + |
| +func (w *world) staleString() string { |
| + var out []string |
| + for _, b := range w.boxes { |
| + for _, h := range w.hosts { |
| + if b.StaleNeg[h] { |
| + out = append(out, fmt.Sprintf("box%d:%s", b.ID, h)) |
| + } |
| + } |
| + } |
| + return fmt.Sprint(out) |
| +} |
| + |
| +func (w *world) now() time.Time { return epoch.Add(time.Duration(w.step) * tick) } |
| + |
| +func (w *world) newPID() int { w.nextPID++; return int(w.nextPID) } |
| +func (w *world) newETag() string { w.nextETag++; return fmt.Sprintf("\"e%d\"", w.nextETag) } |
| +func (w *world) newInode() uint64 { w.nextInode++; return uint64(1000 + w.nextInode) } |
| +func (w *world) newVer() int { w.nextVer++; return int(w.nextVer) } |
| +func (w *world) newClock() int64 { w.clock++; return int64(1_000_000_000) * (w.clock + 1) } |
| +func (w *world) lifetime(h string) string { return "inc-" + h + "-1" } |
| +func (w *world) gen(n int) string { return fmt.Sprintf("%d:h%d", n, n) } |
| + |
| +// calm is true once the chaos steps are over: no new fault is injected. |
| +func (w *world) calm() bool { return w.step > chaosSteps } |
| + |
| +// pct is a seeded coin: true with probability p percent. A witness's world |
| +// never calls it. |
| +func (w *world) pct(p int) bool { |
| + if w.scripted { |
| + panic("a scripted world drew from the rng") |
| + } |
| + return w.rng.Intn(100) < p |
| +} |
| + |
| +// fault is pct, and false once the world is calm. |
| +func (w *world) fault(p int) bool { return !w.calm() && w.pct(p) } |
| + |
| +func (w *world) logf(format string, args ...any) { |
| + w.trace = append(w.trace, fmt.Sprintf("[%d] ", w.step)+fmt.Sprintf(format, args...)) |
| +} |
| + |
| +func (w *world) event(name string) { w.events[name]++ } |
| + |
| +// ---- S3 ---- |
| + |
| +// view is a GET of the host's lock.json, read through hafresh.DecodeLock. |
| +// Only an absent object is Absent. |
| +func (w *world) view(h string) hafresh.View { |
| + p := w.s3[h] |
| + if p.ETag == "" { |
| + return hafresh.View{Absent: true} |
| + } |
| + v, err := hafresh.DecodeLock(p.Lock, p.ETag) |
| + if err != nil { |
| + w.fail("MODEL", "%s: lock.json does not decode: %v", h, err) |
| + return hafresh.View{} |
| + } |
| + return v |
| +} |
| + |
| +// putLock is a conditional PUT of lock.json: If-None-Match: * when cond is |
| +// Absent, else If-Match cond's ETag. false is a lost condition (412). |
| +func (w *world) putLock(h string, body []byte, cond hafresh.View) bool { |
| + p := w.s3[h] |
| + if cond.Absent { |
| + if p.ETag != "" { |
| + return false |
| + } |
| + } else if p.ETag != cond.ETag { |
| + return false |
| + } |
| + p.Lock, p.ETag = body, w.newETag() |
| + return true |
| +} |
| + |
| +// deleteLock is litestream's ReleaseLease: a DELETE, If-Match etag. |
| +func (w *world) deleteLock(h, etag string) bool { |
| + p := w.s3[h] |
| + if p.ETag != etag { |
| + return false |
| + } |
| + p.Lock, p.ETag = nil, "" |
| + return true |
| +} |
| + |
| +// leaseBody is the lock.json a take or a renewal writes (litestream.Lease's |
| +// JSON: generation, expires_at, owner). |
| +func (w *world) leaseBody(gen int64, owner string, expires time.Time) []byte { |
| + b, err := json.Marshal(hafresh.Lock{Generation: gen, ExpiresAt: expires, Owner: owner}) |
| + if err != nil { |
| + panic(err) |
| + } |
| + return b |
| +} |
| + |
| +func (w *world) lockString(h string) string { |
| + v := w.view(h) |
| + switch { |
| + case v.Absent: |
| + return "absent" |
| + case v.Lock.Release != nil: |
| + return fmt.Sprintf("marker{box %s clean %v txid %d gen %d}", v.Lock.Release.Box, v.Lock.Release.Clean, v.Lock.Release.TXID, v.Lock.Generation) |
| + } |
| + return fmt.Sprintf("lease{%s gen %d expires %s %s}", v.Lock.Owner, v.Lock.Generation, v.Lock.ExpiresAt.Sub(epoch), v.ETag) |
| +} |
| + |
| +// ---- timers and background work ---- |
| + |
| +// tick advances the background of one step: an agent's hang ends; |
| +// stragglers exit; orphans restart by systemd; and every running agent's |
| +// held releases retry, its publishers and replicators run, its leases |
| +// renew and its owed markers retry. A scripted world runs only the timers |
| +// and what follows from them. |
| +func (w *world) tick() { |
| + for _, b := range w.boxes { |
| + if b.Agent == agentHung && w.step >= b.HungTill { |
| + b.Agent = agentUp |
| + w.event("hang-resumed") |
| + w.logf("box%d: the agent resumes", b.ID) |
| + } |
| + for _, h := range w.hosts { |
| + us := b.Units[h][:0] |
| + for _, u := range b.Units[h] { |
| + if u.Straggler && w.step >= u.ExitAt { |
| + w.logf("box%d: %s: a straggler unit exits", b.ID, h) |
| + continue |
| + } |
| + if u.Orphan { |
| + if !u.Running && w.step >= u.BackAt { |
| + u.Running = true |
| + w.logf("box%d: %s: systemd restarts the orphan unit", b.ID, h) |
| + } else if u.Running && !w.scripted && w.pct(20) { |
| + u.Running, u.BackAt = false, w.step+1+w.rng.Intn(2) |
| + w.logf("box%d: %s: the orphan unit exits; systemd will restart it", b.ID, h) |
| + } |
| + } |
| + us = append(us, u) |
| + } |
| + b.Units[h] = us |
| + } |
| + } |
| + for _, b := range w.boxes { |
| + if b.Agent != agentUp { |
| + continue |
| + } |
| + for _, h := range w.hosts { |
| + if e := b.Entries[h]; e != nil && e.Releasing != nil { |
| + w.tryRelease(b, h) |
| + } |
| + e := b.Entries[h] |
| + if e == nil { |
| + continue |
| + } |
| + if e.Pub != nil { |
| + w.publishTick(b, h, e) |
| + } |
| + if !w.scripted && w.pct(50) { |
| + w.sync(b, h, w.pct(50)) |
| + } |
| + w.renew(b, h) |
| + } |
| + w.strayTick(b) |
| + if !w.scripted { |
| + for _, h := range w.hosts { |
| + if ob := b.Owed[h]; ob != nil && w.pct(30) { |
| + w.retryObligation(b, ob, w.fault(40)) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// doStep advances one tick, runs one chosen action and checks the state |
| +// invariants. |
| +func (w *world) doStep() { |
| + w.step++ |
| + w.tick() |
| + a := w.pick() |
| + if a != nil { |
| + w.stats[a.name]++ |
| + w.logf("action %s", a.name) |
| + if a.run(w) { |
| + w.done[a.name]++ |
| + } |
| + } |
| + w.check() |
| +} |
| + |
| +// advance is doStep with no action: a witness's passage of time. |
| +func (w *world) advance(n int) { |
| + for i := 0; i < n; i++ { |
| + w.step++ |
| + w.tick() |
| + w.check() |
| + } |
| +} |
| + |
| +// pick chooses one registered action by weight, over the registry sorted |
| +// by name so the order files' init functions ran in never matters. |
| +func (w *world) pick() *action { |
| + sorted := make([]action, 0, len(actions)) |
| + total := 0 |
| + for _, a := range actions { |
| + if a.weight > 0 { |
| + sorted = append(sorted, a) |
| + total += a.weight |
| + } |
| + } |
| + if total == 0 { |
| + return nil |
| + } |
| + sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].name < sorted[j].name }) |
| + n := w.rng.Intn(total) |
| + for i := range sorted { |
| + if n < sorted[i].weight { |
| + return &sorted[i] |
| + } |
| + n -= sorted[i].weight |
| + } |
| + return nil |
| +} |
| + |
| +// final clears every fault and lets the world settle: hung agents resume, |
| +// dead agents restart (their startup sweep succeeds), stragglers exit, |
| +// held releases finish and owed markers are retried. Then the liveness |
| +// oracle (I5). |
| +func (w *world) final() { |
| + for _, b := range w.boxes { |
| + switch b.Agent { |
| + case agentHung: |
| + b.Agent = agentUp |
| + w.logf("final: box%d resumes", b.ID) |
| + case agentDown: |
| + w.restart(b, true) |
| + } |
| + } |
| + w.advance(settleTicks) |
| + for _, b := range w.boxes { |
| + for _, h := range w.hosts { |
| + if ob := b.Owed[h]; ob != nil { |
| + w.retryObligation(b, ob, false) |
| + } |
| + } |
| + } |
| + w.checkLiveness() |
| + w.logf("final: %d steps, %d violations", w.step, len(w.violations)) |
| +} |
| + |
| +func runSeed(seed int64, verbose bool) *world { |
| + w := newWorld(seed, verbose) |
| + for i := 0; i < chaosSteps+calmSteps; i++ { |
| + w.doStep() |
| + } |
| + w.final() |
| + return w |
| +} |