package hostedctl import ( "context" "database/sql" "errors" "fmt" "math/rand" "os" "path/filepath" "runtime" "runtime/debug" "slices" "strconv" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" ) // TestLifecycleSimulation drives the real controller, over the real store // and the fake provider, through random launches, crashes, provider faults, // pauses, resumes, orphans, stops, wall-clock jumps and time advances, and // checks the invariants of spec ยง14 (I1 to I7, sim_model_test.go) after // every step and every reaper pass. The directed scenarios (simScenarios) // run first. Each seed fixes the random choices, though not the order in // which the two goroutines of a concurrent duplicate launch run; // EQUIPO_SIM_SEEDS=n runs seeds 1 to n (default 200) and EQUIPO_SIM_SEED=s // runs seed s alone. A failure prints its seed and step log. func TestLifecycleSimulation(t *testing.T) { seeds := []int64{} n := 200 if v := os.Getenv("EQUIPO_SIM_SEEDS"); v != "" { var err error if n, err = strconv.Atoi(v); err != nil || n < 1 { t.Fatalf("EQUIPO_SIM_SEEDS=%q: want a positive count", v) } } for s := 1; s <= n; s++ { seeds = append(seeds, int64(s)) } if v := os.Getenv("EQUIPO_SIM_SEED"); v != "" { s, err := strconv.ParseInt(v, 10, 64) if err != nil { t.Fatalf("EQUIPO_SIM_SEED=%q: want a seed", v) } seeds = []int64{s} } dir := t.TempDir() template := simTemplate(t, dir) var mu sync.Mutex var fails []*simFailure for i, sc := range simScenarios { if f := runSim(dir, -int64(i+1), template, sc.name, sc.run); f != nil { fails = append(fails, f) } } next := make(chan int64) var wg sync.WaitGroup for range min(runtime.GOMAXPROCS(0), 8, len(seeds)) { wg.Add(1) go func() { defer wg.Done() for seed := range next { if f := runSim(dir, seed, template, "", (*simWorld).randomSteps); f != nil { mu.Lock() fails = append(fails, f) mu.Unlock() } } }() } for _, seed := range seeds { mu.Lock() stop := len(fails) >= 3 // enough to show; the rest would only repeat it mu.Unlock() if stop { break } next <- seed } close(next) wg.Wait() slices.SortFunc(fails, func(a, b *simFailure) int { return int(a.seed - b.seed) }) for _, f := range fails { what := fmt.Sprintf("seed %d", f.seed) if f.name != "" { what = "scenario " + f.name } t.Errorf("%s failed at step %d:\n %s", what, f.step, strings.Join(f.bad, "\n ")) } if len(fails) > 0 { log := fails[0].log if lines := strings.Split(log, "\n"); len(lines) > simLogLines { log = fmt.Sprintf("(%d earlier lines left out)\n%s", len(lines)-simLogLines, strings.Join(lines[len(lines)-simLogLines:], "\n")) } what := fmt.Sprintf("seed %d (EQUIPO_SIM_SEED=%d replays it)", fails[0].seed, fails[0].seed) if fails[0].name != "" { what = "scenario " + fails[0].name } t.Logf("step log of %s:\n%s", what, log) } } // simTemplate migrates one store and returns its file with the clock // checkpoint removed, so each seed starts from a copy that Open still // treats as fresh (T at 0, not restarted). Creating a store from nothing // costs tens of milliseconds of disk syncs; a copy costs almost none. func simTemplate(t *testing.T, dir string) []byte { t.Helper() path := filepath.Join(dir, "template.db") s, err := Open(context.Background(), path, isolatedjobtest.NewFakeClock(testWall)) if err != nil { t.Fatalf("open the template store: %v", err) } if err := s.Close(); err != nil { t.Fatalf("close the template store: %v", err) } db, err := sql.Open("sqlite", path) if err != nil { t.Fatalf("open the template file: %v", err) } if _, err := db.Exec(`DELETE FROM clock`); err != nil { t.Fatalf("template: remove the clock checkpoint: %v", err) } if err := db.Close(); err != nil { t.Fatalf("close the template file: %v", err) } b, err := os.ReadFile(path) if err != nil { t.Fatalf("read the template: %v", err) } return b } // simSteps is how many operations one seed runs; simLogLines is how much // of a failing seed's step log is printed. const ( simSteps = 40 simLogLines = 400 ) const simActor hostedwire.KeyID = "inst-1" type simFailure struct { name string // a directed scenario's; empty for a random seed seed int64 step int bad []string log string } // simPause is the model of one attempt's pause barrier. type simPause struct { gen int64 drainedAt T open bool // drained and not reopened or resumed since acked bool // the current generation was acknowledged in time } // simReturned is an epoch a Resume call returned, checked against the store. type simReturned struct { attempt, op string epoch int64 } // simModel is what the simulation itself expects, kept only as far as the // invariants need it. type simModel struct { next, nextOp, nextOrphan int req map[string]LaunchRequest stopAt map[string]T // stop time from the launch step's time and the lifetime pause map[string]*simPause ops map[string][]string // resume operation IDs used, per attempt done map[[2]string]int64 // (attempt, operation) -> epoch, once seen done returned []simReturned deferral map[isolatedjob.Ref]*simDeferral // R22 deferral of VMs with no saved Ref } // simWorld is one seed's controller, store, fake and model clock. type simWorld struct { seed int64 rng *rand.Rand ctx context.Context path string clk *isolatedjobtest.FakeClock fake *isolatedjob.Fake run *simRunner cfg Config store *Store c *Controller // The model's controller clock: restored at open as the store should, // from the checkpoint written at close. opened bool restarted bool base, openedAt T monoAtOpen time.Duration cpT T cpWall time.Time opT T // controller time when the current step began auditBad int step int snap *simSnap m simModel bad []string logMu sync.Mutex lines []string off []bool // simOps kinds this seed leaves out (swarm testing) follow string // the step the runner's protocol takes next, if any short bool // the next time advance is a short one } func newSimWorld(dir string, seed int64) *simWorld { clk := isolatedjobtest.NewFakeClock(testWall) fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits()) fake.SetBackstop(false) w := &simWorld{ seed: seed, rng: rand.New(rand.NewSource(seed)), ctx: context.Background(), path: filepath.Join(dir, fmt.Sprintf("sim-%d.db", seed)), clk: clk, fake: fake, cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true}, ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint}, m: simModel{req: map[string]LaunchRequest{}, stopAt: map[string]T{}, pause: map[string]*simPause{}, ops: map[string][]string{}, done: map[[2]string]int64{}, deferral: map[isolatedjob.Ref]*simDeferral{}}, } w.run = newSimRunner(fake, w) // Swarm testing: each seed leaves out some kinds of step, so some // seeds run long pause and resume sequences that a stop would cut // short, and others pile up faults. Launches and time always run. w.off = make([]bool, len(simOps)) for i, o := range simOps { w.off[i] = !o.always && w.rng.Intn(5) < 2 } return w } func (w *simWorld) now() T { return w.base + T(w.clk.Mono()-w.monoAtOpen) } func (w *simWorld) logf(format string, args ...any) { w.logMu.Lock() defer w.logMu.Unlock() w.lines = append(w.lines, fmt.Sprintf(format, args...)) } // runSim runs one seed's random steps, or one directed scenario, in a world // of its own, and returns its failure, if any. func runSim(dir string, seed int64, template []byte, name string, body func(*simWorld)) (f *simFailure) { w := newSimWorld(dir, seed) defer w.cleanup() if err := os.WriteFile(w.path, template, 0o600); err != nil { return &simFailure{name: name, seed: seed, bad: []string{err.Error()}} } fail := func(bad ...string) *simFailure { return &simFailure{name: name, seed: seed, step: w.step, bad: bad, log: strings.Join(w.lines, "\n")} } defer func() { if p := recover(); p != nil { f = fail(fmt.Sprintf("panic: %v\n%s", p, debug.Stack())) } }() if err := w.open(); err != nil { return fail(err.Error()) } if w.pass() { body(w) } if w.bad != nil { return fail(w.bad...) } return nil } func (w *simWorld) randomSteps() { for range simSteps { op := w.pickOp() if !w.do(op.name, func() string { return op.run(w) }) { return } } } // do runs one step: it logs it, runs it, then the invariants. It reports // whether everything still holds. func (w *simWorld) do(what string, run func() string) bool { w.step++ w.opT = w.now() w.logf("step %d at %v: %s", w.step, simDur(w.opT), what) w.logf(" %s", run()) if w.bad == nil { w.verify() } return w.bad == nil } // want is a directed scenario's own expectation, checked after the // invariants: a scenario that does not reach the state it means to test // fails rather than passing vacuously. func (w *simWorld) want(ok bool, format string, args ...any) bool { if !ok && w.bad == nil { w.bad = []string{"scenario: " + fmt.Sprintf(format, args...)} } return w.bad == nil } func (w *simWorld) cleanup() { if w.opened { _ = w.store.Close() } for _, suffix := range []string{"", "-wal", "-shm"} { _ = os.Remove(w.path + suffix) } } // open opens the store and builds a controller, as the process starting. // The model restores controller time the way the store must: the // checkpoint's time plus the wall time since it, never less. func (w *simWorld) open() error { s, err := Open(w.ctx, w.path, w.clk) if err != nil { return fmt.Errorf("open: %w", err) } // A crash here is Close and Open, never a power cut, so the store's // disk syncs buy the simulation nothing and cost most of its time. // Only this test connection changes; it must run outside a transaction. if _, err := s.conn.ExecContext(w.ctx, `PRAGMA synchronous = OFF`); err != nil { _ = s.Close() return fmt.Errorf("open: turn off disk syncs: %w", err) } w.base = 0 if w.cpWall != (time.Time{}) { w.restarted = true w.base = w.cpT if wall := w.clk.Wall(); wall.After(w.cpWall) { w.base += T(wall.Sub(w.cpWall)) } } w.monoAtOpen, w.openedAt = w.clk.Mono(), w.base c, err := New(w.cfg, Deps{Store: s, Runner: w.run, Auditor: w.fake, Alerter: &recordingAlerter{}}) if err != nil { _ = s.Close() return fmt.Errorf("new: %w", err) } w.store, w.c, w.opened = s, c, true w.run.mu.Lock() w.run.openPass = w.run.passNo w.run.mu.Unlock() return nil } // close closes the store, as the process exiting; Close checkpoints. func (w *simWorld) close() error { w.cpT, w.cpWall = w.now(), w.clk.Wall() w.opened = false return w.store.Close() } // verify reads a snapshot and runs every invariant; it records the first // violations in w.bad. func (w *simWorld) verify() bool { s, err := w.read() if err != nil { w.bad = []string{err.Error()} return false } w.snap = s if bad := w.check(s); len(bad) > 0 { w.bad = bad return false } return true } // pass runs one reaper pass, as Loop would, then the invariants. func (w *simWorld) pass() bool { a := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true} if w.auditBad > 0 { w.auditBad-- a.ResolverDisabled = false } w.fake.SetAudit(a, nil) w.run.beginPass() rep, err := w.c.Reap(w.ctx) w.run.endPass() w.logf(" pass at %v: %+v %s", simDur(w.now()), rep, errText(err)) return w.verify() } // advance moves time forward by d in steps of at most ReapInterval, with // the provider's progress (Tick) and a reaper pass at each step. While // nothing can change it skips ahead, but never past a recorded drain or stop // time, where a pass runs, and never while a fault window (failing audits, // incomplete Lists) or a queued List fault would have played out in the // passes left out: a quiet pass calls only List and the audit. func (w *simWorld) advance(d time.Duration) string { passes := 0 for d > 0 && w.bad == nil { step := min(d, ReapInterval) if step > time.Second && w.rng.Intn(4) == 0 { step = time.Duration(1+w.rng.Int63n(int64(step/time.Second))) * time.Second } if d > ReapInterval && w.snap.quiet() && w.faultFree() { skip := d if at, ok := w.snap.nextEvent(w.now()); ok && time.Duration(at-w.now()) < skip { skip = time.Duration(at - w.now()) } if skip > step { step = skip w.logf(" quiet: skip %v", skip) } } w.clk.AdvanceMono(step) w.clk.SetWall(w.clk.Wall().Add(step)) d -= step w.fake.Tick() w.pass() passes++ } return fmt.Sprintf("%d passes", passes) } // simOp is one kind of step. Its weight is multiplied by simBoost while // some job without proof is ready for it (boost), so the runner's side of // the pause protocol (drain, acknowledge, suspend, resume) is followed // often enough to reach its later steps; the step itself still picks any // job, and the generation or operation it names, at random. // faultFree reports whether no failing audit, incomplete-List window or // queued List fault is waiting for a pass. func (w *simWorld) faultFree() bool { w.run.mu.Lock() defer w.run.mu.Unlock() return w.auditBad == 0 && w.run.incomplete == 0 && len(w.run.pending[isolatedjob.OpList]) == 0 } type simOp struct { name string weight int boost func(w *simWorld, j *simJob) bool run func(w *simWorld) string always bool // never left out of a seed } // The pause protocol's next step for job j, by the model. func simToDrain(_ *simWorld, j *simJob) bool { return j.state == JobRunning } func simToAck(w *simWorld, j *simJob) bool { p := w.m.pause[j.attempt] return j.state == JobDraining && p != nil && p.open && !p.acked } func simToSuspend(w *simWorld, j *simJob) bool { p := w.m.pause[j.attempt] return j.state == JobDraining && p != nil && p.acked } func simToResume(_ *simWorld, j *simJob) bool { return j.state == JobSuspended || j.state == JobResuming } const simBoost = 4 var simOps = []simOp{ {"launch", 10, nil, (*simWorld).opLaunch, true}, {"launch a replacement", 5, nil, (*simWorld).opReplace, false}, {"launch a concurrent duplicate", 3, nil, (*simWorld).opDuplicate, false}, {"crash and reopen", 4, nil, (*simWorld).opCrash, false}, {"fault: lost reply", 4, nil, (*simWorld).opLostReply, false}, {"fault: throttle", 3, nil, (*simWorld).opThrottle, false}, {"fault: incomplete lists", 3, nil, (*simWorld).opIncomplete, false}, {"fault: unknown state", 3, nil, (*simWorld).opUnknownState, false}, {"fault: unknown age", 2, nil, (*simWorld).opUnknownAge, false}, {"fault: failing network audit", 3, nil, (*simWorld).opAuditFails, false}, {"drain", 4, simToDrain, (*simWorld).opDrain, false}, {"acknowledge quiescent", 3, simToAck, (*simWorld).opAck, false}, {"suspend", 3, simToSuspend, (*simWorld).opSuspend, false}, {"reopen", 1, nil, (*simWorld).opReopen, false}, {"resume", 3, simToResume, (*simWorld).opResume, false}, {"plant an orphan", 3, nil, (*simWorld).opPlant, false}, {"stop", 5, nil, (*simWorld).opStop, false}, {"a VM ends by itself", 1, nil, (*simWorld).opEnd, false}, {"the provider forgets a stopped VM", 1, nil, (*simWorld).opVanish, false}, {"wall-clock jump", 3, nil, (*simWorld).opWall, false}, {"time advance", 16, nil, (*simWorld).opAdvance, true}, } func (w *simWorld) pickOp() simOp { // A runner follows the pause protocol promptly: after a drain it // usually acknowledges, then suspends, then waits for the VM, then // resumes. Any other step may still come in between. if next := w.follow; next != "" { w.follow = "" for i, o := range simOps { if o.name == next && !w.off[i] && w.rng.Intn(10) < 7 { return o } } } weights := make([]int, len(simOps)) total := 0 for i, o := range simOps { if w.off[i] { continue } weights[i] = o.weight if o.boost != nil && w.anyJob(o.boost) { weights[i] *= simBoost } total += weights[i] } n := w.rng.Intn(total) for i, o := range simOps { if n -= weights[i]; n < 0 { return o } } return simOps[len(simOps)-1] } // simLives are the lifetimes launches ask for, short ones often so stop // times come within a few passes. var simLives = []struct { d time.Duration weight int }{{11 * time.Minute, 3}, {12 * time.Minute, 2}, {15 * time.Minute, 3}, {20 * time.Minute, 3}, {30 * time.Minute, 4}, {45 * time.Minute, 4}, {time.Hour, 4}, {2 * time.Hour, 2}, {8 * time.Hour, 1}} func (w *simWorld) newRequest(replaces string) LaunchRequest { w.m.next++ id := fmt.Sprintf("a%d", w.m.next) total := 0 for _, l := range simLives { total += l.weight } n, life := w.rng.Intn(total), simLives[0].d for _, l := range simLives { if n -= l.weight; n < 0 { life = l.d break } } q := LaunchRequest{AttemptID: id, TaskID: "task-" + id, Account: "acct-1", Replaces: replaces, Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: life, InstanceCode: testCode} w.m.req[id] = q return q } // anyJob reports whether some job without proof satisfies ok. func (w *simWorld) anyJob(ok func(*simWorld, *simJob) bool) bool { for _, id := range w.snap.order { if j := w.snap.jobs[id]; j.proof == "" && ok(w, j) { return true } } return false } // pickReady returns, four times in five, a random job without proof that // satisfies ready; otherwise, or when there is none, pickJob(states...). func (w *simWorld) pickReady(ready func(*simWorld, *simJob) bool, states ...string) string { var ids []string for _, id := range w.snap.order { if j := w.snap.jobs[id]; j.proof == "" && ready(w, j) { ids = append(ids, id) } } if len(ids) > 0 && w.rng.Intn(5) != 0 { return ids[w.rng.Intn(len(ids))] } return w.pickJob(states...) } // pickJob returns a random attempt in one of states (any state when none // is given) that holds no proof, or "" when there is none. func (w *simWorld) pickJob(states ...string) string { var ids []string for _, id := range w.snap.order { j := w.snap.jobs[id] if j.proof == "" && (len(states) == 0 || slices.Contains(states, j.state)) { ids = append(ids, id) } } if len(ids) == 0 { if len(states) > 0 && len(w.snap.order) > 0 && w.rng.Intn(6) == 0 { return w.snap.order[w.rng.Intn(len(w.snap.order))] // a job in the wrong state is refused } return "" } return ids[w.rng.Intn(len(ids))] } func (w *simWorld) maybeLost(op isolatedjob.Op, oneIn int) string { if w.rng.Intn(oneIn) != 0 { return "" } w.run.queue(op, isolatedjob.FaultLostReply) return " (reply lost)" } func (w *simWorld) opLaunch() string { q := w.newRequest("") lost := w.maybeLost(isolatedjob.OpLaunch, 4) v, err := w.c.Launch(w.ctx, simActor, instKey, q) return fmt.Sprintf("launch %s life %v%s -> %s", q.AttemptID, q.MaxLifetime, lost, viewText(v, err)) } func (w *simWorld) opReplace() string { var proven, all []string for _, id := range w.snap.order { all = append(all, id) if w.snap.jobs[id].proof != "" { proven = append(proven, id) } } if len(all) == 0 { return w.opLaunch() } old := all[w.rng.Intn(len(all))] if len(proven) > 0 && w.rng.Intn(4) != 0 { old = proven[w.rng.Intn(len(proven))] } q := w.newRequest(old) lost := w.maybeLost(isolatedjob.OpLaunch, 4) v, err := w.c.Launch(w.ctx, simActor, instKey, q) return fmt.Sprintf("launch %s replacing %s%s -> %s", q.AttemptID, old, lost, viewText(v, err)) } func (w *simWorld) opDuplicate() string { var q LaunchRequest if len(w.snap.order) > 0 && w.rng.Intn(3) == 0 { q = w.m.req[w.snap.order[w.rng.Intn(len(w.snap.order))]] } else { q = w.newRequest("") } lost := w.maybeLost(isolatedjob.OpLaunch, 3) // The two goroutines run in whatever order the scheduler picks, so a // seed fixes which requests race but not which one wins, or which // one meets a queued fault: replaying a seed can differ here. out := make([]string, 2) var wg sync.WaitGroup for i := range out { wg.Add(1) go func() { defer wg.Done() v, err := w.c.Launch(w.ctx, simActor, instKey, q) out[i] = viewText(v, err) }() } wg.Wait() return fmt.Sprintf("launch %s twice at once%s -> %s; %s", q.AttemptID, lost, out[0], out[1]) } func (w *simWorld) opCrash() string { var down, extra time.Duration if w.rng.Intn(2) == 0 { down = time.Duration(1+w.rng.Intn(1200)) * time.Second } if w.rng.Intn(3) == 0 { extra = time.Duration(w.rng.Intn(7200)-3600) * time.Second } switch { case w.cfg.Enabled && w.rng.Intn(8) == 0: w.cfg.Enabled = false case !w.cfg.Enabled && w.rng.Intn(2) == 0: w.cfg.Enabled = true } return w.crash(down, extra, w.rng.Intn(10) < 7) } // crash closes the store, lets down pass (the wall clock moves down plus // extra), opens it again and builds a new controller; with pass, the first // reaper pass runs at once, as Loop's does. func (w *simWorld) crash(down, extra time.Duration, pass bool) string { if err := w.close(); err != nil { w.bad = []string{"close: " + err.Error()} return "close failed" } wall := w.clk.Wall().Add(down + extra) w.clk.AdvanceMono(down) w.clk.SetWall(wall) if down > 0 { w.fake.Tick() } if err := w.open(); err != nil { w.bad = []string{err.Error()} return "reopen failed" } out := fmt.Sprintf("down %v, wall moved %v, launches enabled %v", down, wall.Sub(w.cpWall), w.cfg.Enabled) if pass { w.pass() out += ", first pass run" } return out } func (w *simWorld) opLostReply() string { op := []isolatedjob.Op{isolatedjob.OpLaunch, isolatedjob.OpStop, isolatedjob.OpResume}[w.rng.Intn(3)] w.run.queue(op, isolatedjob.FaultLostReply) return fmt.Sprintf("the next %s reply is lost", op) } func (w *simWorld) opThrottle() string { ops := []isolatedjob.Op{isolatedjob.OpLaunch, isolatedjob.OpGet, isolatedjob.OpSuspend, isolatedjob.OpResume, isolatedjob.OpStop, isolatedjob.OpList} op := ops[w.rng.Intn(len(ops))] w.run.queue(op, isolatedjob.FaultThrottle) return fmt.Sprintf("the next %s is throttled", op) } func (w *simWorld) opIncomplete() string { k := 1 + w.rng.Intn(6) w.run.mu.Lock() w.run.incomplete += k w.run.mu.Unlock() return fmt.Sprintf("every List is incomplete for %d more passes", k) } func (w *simWorld) opUnknownState() string { w.run.queue(isolatedjob.OpGet, isolatedjob.FaultUnknownState) return "the next Get reads unknown" } func (w *simWorld) opUnknownAge() string { w.run.queue(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) return "the next Get gives no age" } func (w *simWorld) opAuditFails() string { k := 5 + w.rng.Intn(16) w.auditBad += k return fmt.Sprintf("the network audit fails for %d more passes", k) } // genChoice picks a generation to name: the current one mostly, else the // one before or the one after. func (w *simWorld) genChoice(id string) (int64, string) { cur := int64(0) if p := w.m.pause[id]; p != nil { cur = p.gen } switch n := w.rng.Intn(20); { case n < 14: return cur, "current" case n < 17: return cur - 1, "stale" } return cur + 1, "next" } func (w *simWorld) opDrain() string { id := w.pickReady(simToDrain, JobRunning, JobDraining) if id == "" { return "no job to drain" } gen, err := w.drain(id) if err == nil { w.follow = "acknowledge quiescent" } return fmt.Sprintf("drain %s -> generation %d %s", id, gen, errText(err)) } func (w *simWorld) drain(id string) (int64, error) { gen, err := w.c.Drain(w.ctx, simActor, instKey, id) if err == nil { w.m.pause[id] = &simPause{gen: gen, drainedAt: w.now(), open: true} } return gen, err } // ack sends Quiescent for gen and records an in-time acknowledgement of // the current generation in the model's history. A generation drained // before the last restart is never in time: the downtime is unknown. func (w *simWorld) ack(id string, gen int64) error { err := w.c.Quiescent(w.ctx, simActor, instKey, id, gen) if p := w.m.pause[id]; err == nil && p != nil && p.open && gen == p.gen && w.now()-p.drainedAt <= T(PauseAckTimeout) && !(w.restarted && p.drainedAt <= w.openedAt) { p.acked = true } return err } func (w *simWorld) suspend(id string, gen int64) error { w.run.mu.Lock() w.run.suspendOp = &simGen{attempt: id, gen: gen} w.run.mu.Unlock() err := w.c.Suspend(w.ctx, simActor, instKey, id, gen) w.run.mu.Lock() w.run.suspendOp = nil w.run.mu.Unlock() return err } func (w *simWorld) resume(id, op string) (int64, error) { epoch, err := w.c.Resume(w.ctx, simActor, instKey, id, op) if err == nil { // a commit, if this call made one, closes the pause in check w.m.returned = append(w.m.returned, simReturned{attempt: id, op: op, epoch: epoch}) } return epoch, err } func (w *simWorld) opAck() string { id := w.pickReady(simToAck, JobDraining) if id == "" { return "no job to acknowledge" } gen, kind := w.genChoice(id) p := w.m.pause[id] if kind == "current" && p != nil && w.now()-p.drainedAt > T(PauseAckTimeout) { kind = "late" } err := w.ack(id, gen) if err == nil && p != nil && p.acked && gen == p.gen { w.follow = "suspend" } return fmt.Sprintf("quiescent %s generation %d (%s) -> %s", id, gen, kind, errText(err)) } func (w *simWorld) opSuspend() string { id := w.pickReady(simToSuspend, JobDraining, JobSuspending) if id == "" { return "no job to suspend" } gen, kind := w.genChoice(id) fault := "" if w.rng.Intn(5) == 0 { w.run.queue(isolatedjob.OpSuspend, isolatedjob.FaultThrottle) fault = " (throttled)" } err := w.suspend(id, gen) if err == nil { w.follow, w.short = "time advance", true } return fmt.Sprintf("suspend %s generation %d (%s)%s -> %s", id, gen, kind, fault, errText(err)) } func (w *simWorld) opReopen() string { id := w.pickJob(JobDraining) if id == "" { return "no job to reopen" } gen, kind := w.genChoice(id) err := w.c.Reopen(w.ctx, simActor, instKey, id, gen) if p := w.m.pause[id]; err == nil && p != nil && gen == p.gen { p.open, p.acked = false, false } return fmt.Sprintf("reopen %s generation %d (%s) -> %s", id, gen, kind, errText(err)) } func (w *simWorld) opResume() string { id := w.pickReady(simToResume, JobSuspended, JobResuming) if id == "" { return "no job to resume" } op, kind := "", "new" if used := w.m.ops[id]; len(used) > 0 && w.rng.Intn(5) < 2 { op, kind = used[w.rng.Intn(len(used))], "repeated" } else { w.m.nextOp++ op = fmt.Sprintf("op-%d", w.m.nextOp) w.m.ops[id] = append(w.m.ops[id], op) } lost := w.maybeLost(isolatedjob.OpResume, 3) epoch, err := w.resume(id, op) if err != nil { w.follow, w.short = "time advance", true } return fmt.Sprintf("resume %s operation %s (%s)%s -> epoch %d %s", id, op, kind, lost, epoch, errText(err)) } // closePause records that the pause of attempt ended in a newly committed // resume. func (w *simWorld) closePause(id string) { if p := w.m.pause[id]; p != nil { p.open, p.acked = false, false } } func (w *simWorld) opPlant() string { w.m.nextOrphan++ ref := w.run.plant(fmt.Sprintf("orphan-%d", w.m.nextOrphan)) return fmt.Sprintf("planted orphan %s", ref) } func (w *simWorld) opStop() string { id := w.pickJob() if id == "" { return "no job to stop" } lost := w.maybeLost(isolatedjob.OpStop, 5) p, err := w.c.Stop(w.ctx, simActor, instKey, id, "simulation stop") return fmt.Sprintf("stop %s%s -> proof %+v %s", id, lost, p, errText(err)) } // vmsIn returns the fake's VMs whose state passes keep, in launch order. func (w *simWorld) vmsIn(keep func(isolatedjob.State) bool) []isolatedjob.Ref { var out []isolatedjob.Ref for _, vm := range w.snap.vms { if keep(vm.State) { out = append(out, vm.Ref) } } return out } func (w *simWorld) opEnd() string { refs := w.vmsIn(func(s isolatedjob.State) bool { return s.Live() && s != isolatedjob.StateStopping }) if len(refs) == 0 { return "no live VM" } ref := refs[w.rng.Intn(len(refs))] w.run.end(ref) // the provider's own doing: no controller call return fmt.Sprintf("%s ends by itself", ref) } func (w *simWorld) opVanish() string { refs := w.vmsIn(isolatedjob.State.Terminal) if len(refs) == 0 { return "no stopped VM" } ref := refs[w.rng.Intn(len(refs))] w.fake.Vanish(ref) return fmt.Sprintf("the provider forgets %s", ref) } func (w *simWorld) opWall() string { d := time.Duration(w.rng.Int63n(int64(6*time.Hour))) - 3*time.Hour w.clk.SetWall(w.clk.Wall().Add(d)) return fmt.Sprintf("wall clock moves %v", d) } func (w *simWorld) opAdvance() string { var d time.Duration short := w.short // waiting for the VM to settle after a suspend or resume w.short = false switch n := w.rng.Intn(20); { case n < 10 || short: d = time.Duration(1+w.rng.Intn(60)) * time.Second case n < 19: d = time.Duration(61+w.rng.Intn(540)) * time.Second default: d = time.Duration(901+w.rng.Intn(9*3600-900)) * time.Second } out := fmt.Sprintf("advance %v: %s", d, w.advance(d)) if short && w.bad == nil && w.anyJob(simToResume) { w.follow = "resume" } return out } // simScenarios are directed sequences with fixed choices, run before the // random seeds under the same invariants. Each crash after a lost reply // first confirms the provider's effect and the unresolved store state, then // reopens before anything reconciles; the others reach, every run, the // states the thinnest random coverage depends on. var simScenarios = []struct { name string run func(*simWorld) }{ {"lost launch reply, crash, reconcile", (*simWorld).scLostLaunch}, {"lost stop reply, crash, reconcile", (*simWorld).scLostStop}, {"lost resume reply, crash, reconcile", (*simWorld).scLostResume}, {"throttled resume while the VM stays suspended", (*simWorld).scThrottledResume}, {"a waiting intent's VM outlives its orphan grace", (*simWorld).scOrphanRecheck}, {"future generations are refused", (*simWorld).scFutureGen}, } // launchFor launches a new attempt with lifetime life, its reply lost when // lost, and returns its ID and Launch's error. func (w *simWorld) launchFor(life time.Duration, lost bool) (string, error) { q := w.newRequest("") q.MaxLifetime = life w.m.req[q.AttemptID] = q if lost { w.run.queue(isolatedjob.OpLaunch, isolatedjob.FaultLostReply) } _, err := w.c.Launch(w.ctx, simActor, instKey, q) return q.AttemptID, err } // vmsOf returns the VMs of attempt id in the latest snapshot. func (w *simWorld) vmsOf(id string) []isolatedjob.Job { w.run.mu.Lock() defer w.run.mu.Unlock() var out []isolatedjob.Job for _, vm := range w.snap.vms { if w.run.ownerLocked(w.snap, vm.Ref) == id { out = append(out, vm) } } return out } // oneVM reports whether attempt id has exactly one VM, in state st. func (w *simWorld) oneVM(id string, st isolatedjob.State) bool { vms := w.vmsOf(id) return w.want(len(vms) == 1 && vms[0].State == st, "%s has VMs %+v, want one %s", id, vms, st) } func (w *simWorld) try(what string, run func() error, ok func(error) bool) bool { var err error return w.do(what, func() string { err = run(); return errText(err) }) && w.want(ok(err), "%s: unexpected result %v", what, err) } func (w *simWorld) wait(d time.Duration) bool { return w.do(fmt.Sprintf("advance %v", d), func() string { return w.advance(d) }) } func simOK(err error) bool { return err == nil } // running launches an attempt with lifetime life and waits for it to run. func (w *simWorld) running(life time.Duration) (string, bool) { var id string ok := w.try("launch", func() (err error) { id, err = w.launchFor(life, false); return err }, simOK) && w.wait(ReapInterval) && w.want(w.snap.jobs[id].state == JobRunning, "%s is %s, want running", id, w.snap.jobs[id].state) return id, ok } // suspended runs an attempt through drain, acknowledgement and suspend // until the store holds it suspended. func (w *simWorld) suspended() (string, bool) { id, ok := w.running(time.Hour) var gen int64 ok = ok && w.try("drain", func() (err error) { gen, err = w.drain(id); return err }, simOK) && w.try("acknowledge", func() error { return w.ack(id, gen) }, simOK) && w.try("suspend", func() error { return w.suspend(id, gen) }, simOK) && w.wait(ReapInterval) && w.want(w.snap.jobs[id].state == JobSuspended, "%s is %s, want suspended", id, w.snap.jobs[id].state) return id, ok } func (w *simWorld) scLostLaunch() { var id string _ = w.try("launch with its reply lost", func() (err error) { id, err = w.launchFor(time.Hour, true); return err }, func(err error) bool { return errors.Is(err, ErrProviderLaunch) }) && w.oneVM(id, isolatedjob.StateStarting) && w.want(w.snap.jobs[id].state == JobWaiting && w.snap.jobs[id].ref == "" && w.snap.jobs[id].dispatched, "%s after the lost reply: %+v, want a dispatched waiting intent with no Ref", id, w.snap.jobs[id]) && w.do("crash before any reconciliation", func() string { return w.crash(0, 0, false) }) && w.wait(2*ReapInterval) && w.oneVM(id, isolatedjob.StateRunning) && w.want(w.snap.jobs[id].ref == w.vmsOf(id)[0].Ref, "%s holds Ref %q after the replays", id, w.snap.jobs[id].ref) && w.wait(time.Hour) && w.want(w.snap.jobs[id].proof != "", "%s has no proof after its stop time", id) } func (w *simWorld) scLostStop() { id, ok := w.running(time.Hour) _ = ok && w.try("stop with its reply lost", func() error { w.run.queue(isolatedjob.OpStop, isolatedjob.FaultLostReply) _, err := w.c.Stop(w.ctx, simActor, instKey, id, "scenario stop") return err }, func(err error) bool { return errors.Is(err, isolatedjob.ErrLostReply) }) && w.oneVM(id, isolatedjob.StateStopping) && w.want(w.snap.jobs[id].stopRequested && w.snap.jobs[id].proof == "", "%s after the lost stop: %+v", id, w.snap.jobs[id]) && w.do("crash before any reconciliation", func() string { return w.crash(0, 0, false) }) && w.wait(2*ReapInterval) && w.want(w.snap.jobs[id].proof != "", "%s has no proof after the reopen", id) } func (w *simWorld) scLostResume() { id, ok := w.suspended() var epoch int64 _ = ok && w.try("resume op-1 with its reply lost", func() (err error) { w.run.queue(isolatedjob.OpResume, isolatedjob.FaultLostReply) _, err = w.resume(id, "op-1") return err }, func(err error) bool { return errors.Is(err, ErrResumePending) }) && w.do("the provider finishes the resume", func() string { w.fake.Tick(); return "tick" }) && w.oneVM(id, isolatedjob.StateRunning) && w.want(w.snap.jobs[id].state == JobResuming && w.snap.jobs[id].epoch == 0 && len(w.snap.ops) == 1 && w.snap.ops[0].status == opPending, "%s after the lost resume: %+v, operations %+v", id, w.snap.jobs[id], w.snap.ops) && w.do("crash before any reconciliation", func() string { return w.crash(0, 0, false) }) && w.wait(2*ReapInterval) && w.want(w.snap.jobs[id].epoch == 1, "%s epoch %d after recovery, want 1", id, w.snap.jobs[id].epoch) && w.try("resume op-1 again", func() (err error) { epoch, err = w.resume(id, "op-1"); return err }, simOK) && w.want(epoch == 1, "the repeated op-1 returned epoch %d, want 1", epoch) } func (w *simWorld) scThrottledResume() { id, ok := w.suspended() _ = ok && w.try("resume op-1, the provider call throttled", func() (err error) { w.run.queue(isolatedjob.OpResume, isolatedjob.FaultThrottle) _, err = w.resume(id, "op-1") return err }, func(err error) bool { return errors.Is(err, ErrResumePending) }) && w.oneVM(id, isolatedjob.StateSuspended) && w.want(w.snap.jobs[id].epoch == 0, "%s committed epoch %d with no provider resume", id, w.snap.jobs[id].epoch) && w.wait(3*ReapInterval) && w.want(w.snap.jobs[id].epoch == 1, "%s epoch %d once Refresh resumed it, want 1", id, w.snap.jobs[id].epoch) } func (w *simWorld) scOrphanRecheck() { var id string _ = w.try("launch with its reply lost", func() (err error) { id, err = w.launchFor(2*time.Hour, true); return err }, func(err error) bool { return errors.Is(err, ErrProviderLaunch) }) && w.do("the network audit fails from now, for 15 passes", func() string { w.auditBad = 15 w.fake.SetAudit(isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true}, nil) return errText(w.c.RunAudit(w.ctx)) // recorded now, so no replay can claim the VM }) && w.wait(12*time.Minute) && w.oneVM(id, isolatedjob.StateRunning) && w.want(w.snap.jobs[id].state == JobWaiting, "%s is %s, want still waiting", id, w.snap.jobs[id].state) && w.wait(6*time.Minute) && w.want(w.snap.jobs[id].ref == w.vmsOf(id)[0].Ref, "%s did not claim its VM once audits passed", id) } func (w *simWorld) scFutureGen() { id, ok := w.running(time.Hour) var gen int64 refused := func(err error) bool { return errors.Is(err, ErrGenerationCancelled) } _ = ok && w.try("drain", func() (err error) { gen, err = w.drain(id); return err }, simOK) && w.try("acknowledge the next generation", func() error { return w.ack(id, gen+1) }, refused) && w.try("acknowledge the current generation", func() error { return w.ack(id, gen) }, simOK) && w.try("suspend the next generation", func() error { return w.suspend(id, gen+1) }, refused) && w.try("suspend the current generation", func() error { return w.suspend(id, gen) }, simOK) } func viewText(v JobView, err error) string { if err != nil { return errText(err) } return fmt.Sprintf("%s %s", v.State, v.VMRef) } func faultNote(f isolatedjob.Fault) string { if f == "" { return "" } return " [" + string(f) + "]" } func errText(err error) string { if err == nil { return "ok" } s := strings.ReplaceAll(err.Error(), "\n", " | ") if len(s) > 200 { s = s[:200] + "..." } return "error: " + s } func simDur(t T) time.Duration { return time.Duration(t) }