package hostedctl import ( "context" "database/sql" "encoding/json" "errors" "fmt" "maps" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" ) // This file holds what the lifecycle simulation (sim_test.go) checks: the // provider wrapper that sees every call the controller makes, the snapshot // of the store and the fake, and the seven invariants of spec ยง14. // simVM is what the simulation knows about one VM the fake holds. type simVM struct { attempt string // the spec's attempt ID (the client token), or the planted name launchID string // from the bootstrap; empty for a planted VM planted bool claimed T // when a Launch reply first carried its Ref; 0 if none yet created T // model controller time when the VM appeared pass int // reaper passes begun when it appeared } // simGen names the Suspend call the simulation is making: its attempt and // the generation it asked for. type simGen struct { attempt string gen int64 } // simRunner wraps the fake provider. It queues the simulation's faults and // hands each one to the fake (Inject) just before the call it is meant for, // so the fake's own queue is empty between calls and the checks can read the // fake directly. It records every VM the fake creates, whatever the reply // said, and checks the call-time invariants (I3, I5, I6, I7) against the // store as the call is made; no transaction is open across a provider call, // so the store can be read here. type simRunner struct { fake *isolatedjob.Fake w *simWorld mu sync.Mutex pending map[isolatedjob.Op][]isolatedjob.Fault incomplete int // reaper passes left whose List calls all come back incomplete listBad bool // the pass running now is one of them inPass bool // a reaper pass is running vms map[isolatedjob.Ref]*simVM suspendOp *simGen bad []string // call-time violations, reported by the next check // For I4 (ruling R24): passes begun; per VM, the current unbroken run // of passes with a throttled Stop (reset by any Stop that is not // throttled) and the first Stop that took effect, or the provider's own // end, with the run credited when it was issued. passNo int listFail []int // passes in which a List failed, so orphans were not handled getFail map[isolatedjob.Ref][]int // passes in which a Get of the VM failed openPass int // passNo at the latest open stopRun map[isolatedjob.Ref]int runPass map[isolatedjob.Ref]int stoppedB map[isolatedjob.Ref]simStopAt // For I7: per VM, the pending operation its latest provider Resume was // for, and the operation whose resume a later Get saw running. Any // observed change of phase (a Get reading another state, a Suspend or a // Stop) drops the running evidence. resumeOp map[isolatedjob.Ref]string runningFor map[isolatedjob.Ref]string } // simStopAt is when a Stop for a VM first took effect, and the throttle // credit (in reaper intervals) its I4 bound had then. type simStopAt struct { at T credit int } func newSimRunner(fake *isolatedjob.Fake, w *simWorld) *simRunner { return &simRunner{fake: fake, w: w, pending: map[isolatedjob.Op][]isolatedjob.Fault{}, vms: map[isolatedjob.Ref]*simVM{}, getFail: map[isolatedjob.Ref][]int{}, stopRun: map[isolatedjob.Ref]int{}, runPass: map[isolatedjob.Ref]int{}, stoppedB: map[isolatedjob.Ref]simStopAt{}, resumeOp: map[isolatedjob.Ref]string{}, runningFor: map[isolatedjob.Ref]string{}} } func (r *simRunner) queue(op isolatedjob.Op, f isolatedjob.Fault) { r.mu.Lock() defer r.mu.Unlock() r.pending[op] = append(r.pending[op], f) } // inject hands the fault for this call of op to the fake. The caller holds // r.mu. func (r *simRunner) inject(op isolatedjob.Op) isolatedjob.Fault { var f isolatedjob.Fault if q := r.pending[op]; len(q) > 0 { f, r.pending[op] = q[0], q[1:] } if op == isolatedjob.OpList && r.listBad { f = isolatedjob.FaultIncompleteList } if f != "" { r.fake.Inject(op, f) } return f } func (r *simRunner) violate(format string, args ...any) { r.bad = append(r.bad, fmt.Sprintf(format, args...)) } // visibleLocked returns the Refs the fake shows now. func (r *simRunner) visibleLocked() map[isolatedjob.Ref]bool { vms, _ := r.fake.List(context.Background()) out := make(map[isolatedjob.Ref]bool, len(vms)) for _, vm := range vms { out[vm.Ref] = true } return out } func (r *simRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { r.mu.Lock() defer r.mu.Unlock() r.checkReplacementLocked(s) before := r.visibleLocked() var f isolatedjob.Fault if s.Validate(r.fake.Limits()) == nil { // a spec the fake refuses uses up no fault f = r.inject(isolatedjob.OpLaunch) } ref, err := r.fake.Launch(ctx, s) for now := range r.visibleLocked() { if !before[now] { r.vms[now] = &simVM{attempt: s.AttemptID, launchID: bootLaunchID(s.Bootstrap), created: r.w.now(), pass: r.passNo} } } if v := r.vms[ref]; err == nil && v != nil && v.claimed == 0 { v.claimed = r.w.now() } r.w.logf(" provider launch %s%s -> %s %s", s.AttemptID, faultNote(f), ref, errText(err)) return ref, err } func (r *simRunner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { r.mu.Lock() defer r.mu.Unlock() f := r.inject(isolatedjob.OpGet) j, err := r.fake.Get(ctx, ref) switch { case err == nil && j.State == isolatedjob.StateRunning: if op := r.resumeOp[ref]; op != "" { r.runningFor[ref] = op } case err == nil || errors.Is(err, isolatedjob.ErrNotFound): delete(r.runningFor, ref) // another phase: earlier running evidence is stale case !slices.Contains(r.getFail[ref], r.passNo): r.getFail[ref] = append(r.getFail[ref], r.passNo) } if f != "" || err != nil { r.w.logf(" provider get %s%s -> %s %s", ref, faultNote(f), j.State, errText(err)) } return j, err } func (r *simRunner) Suspend(ctx context.Context, ref isolatedjob.Ref) error { r.mu.Lock() defer r.mu.Unlock() r.checkSuspendLocked(ref) f := r.inject(isolatedjob.OpSuspend) err := r.fake.Suspend(ctx, ref) r.phaseLocked(ref, err) r.w.logf(" provider suspend %s%s -> %s", ref, faultNote(f), errText(err)) return err } func (r *simRunner) Resume(ctx context.Context, ref isolatedjob.Ref) error { r.mu.Lock() defer r.mu.Unlock() r.resumeOp[ref] = r.checkResumeLocked(ref) delete(r.runningFor, ref) f := r.inject(isolatedjob.OpResume) err := r.fake.Resume(ctx, ref) r.w.logf(" provider resume %s%s -> %s", ref, faultNote(f), errText(err)) return err } func (r *simRunner) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error { r.mu.Lock() defer r.mu.Unlock() if reason == reasonOrphan { r.checkOrphanStopLocked(ref) } f := r.inject(isolatedjob.OpStop) err := r.fake.Stop(ctx, ref, reason) r.phaseLocked(ref, err) r.noteStopLocked(ref, errors.Is(err, isolatedjob.ErrThrottled)) r.w.logf(" provider stop %s (%s)%s -> %s", ref, reason, faultNote(f), errText(err)) return err } func (r *simRunner) List(ctx context.Context) ([]isolatedjob.Job, error) { r.mu.Lock() defer r.mu.Unlock() f := r.inject(isolatedjob.OpList) vms, err := r.fake.List(ctx) if err != nil && !slices.Contains(r.listFail, r.passNo) { r.listFail = append(r.listFail, r.passNo) } if f != "" { r.w.logf(" provider list%s -> %d VMs %s", faultNote(f), len(vms), errText(err)) } return vms, err } func (r *simRunner) Limits() isolatedjob.Limits { return r.fake.Limits() } // phaseLocked drops a VM's running evidence after a Suspend or Stop that // was not throttled: its phase may have changed. func (r *simRunner) phaseLocked(ref isolatedjob.Ref, err error) { if !errors.Is(err, isolatedjob.ErrThrottled) { delete(r.runningFor, ref) } } // creditLocked is ref's throttle credit (R24 b): the length of its current // run of consecutive reaper passes that each sent it a throttled Stop. A // pass with none ends the run, so between passes the run is current only // if the last pass threw one, and during a pass also if the one before did. func (r *simRunner) creditLocked(ref isolatedjob.Ref) int { last := r.passNo if r.inPass { last-- } if r.runPass[ref] < last { return 0 } return r.stopRun[ref] } // noteStopLocked records a Stop of ref. A throttled one in a pass extends // the current run, or starts a new one; a Stop that took effect is // recorded once (stoppedLocked). func (r *simRunner) noteStopLocked(ref isolatedjob.Ref, throttled bool) { switch { case !throttled: r.stoppedLocked(ref) case r.inPass: if r.creditLocked(ref) == 0 { r.stopRun[ref] = 0 // an interrupted run ends with its credit } if r.stopRun[ref] == 0 || r.runPass[ref] != r.passNo { r.stopRun[ref]++ } r.runPass[ref] = r.passNo } } // stoppedLocked records the first Stop of ref that took effect (or the // provider's own end) with the throttle credit in force, and ends the run // of throttled Stops. func (r *simRunner) stoppedLocked(ref isolatedjob.Ref) { if _, ok := r.stoppedB[ref]; !ok { r.stoppedB[ref] = simStopAt{at: r.w.now(), credit: r.creditLocked(ref)} } r.stopRun[ref] = 0 } // simDeferral follows R22 deferral for one VM with no saved Ref (R24a c): // I4 does not apply while it does; once it ends, the bound runs from one // interval after the first check that found it ended, plus one interval // per later pass whose List failed (R24a d). type simDeferral struct { on, ended bool at T pass int } func (d *simDeferral) observe(applies bool, now T, pass int) { switch { case applies: d.on, d.ended = true, false case d.on: d.on, d.ended, d.at, d.pass = false, true, now, pass } } func (d *simDeferral) bound(listFail []int) (T, bool) { if !d.ended { return 0, false } b := d.at + T(ReapInterval) for _, p := range listFail { if p > d.pass { b += T(ReapInterval) } } return b, true } // end is the provider stopping a VM on its own, with no controller call. func (r *simRunner) end(ref isolatedjob.Ref) { r.mu.Lock() defer r.mu.Unlock() _ = r.fake.Stop(context.Background(), ref, "ended") delete(r.runningFor, ref) r.stoppedLocked(ref) } // plant adds an orphan VM no Launch asked for. func (r *simRunner) plant(name string) isolatedjob.Ref { r.mu.Lock() defer r.mu.Unlock() ref := r.fake.Plant(isolatedjob.LaunchSpec{AttemptID: name}) r.vms[ref] = &simVM{attempt: name, planted: true, created: r.w.now()} return ref } // beginPass applies the next incomplete-List window, if any, to the pass // about to run. func (r *simRunner) beginPass() { r.mu.Lock() defer r.mu.Unlock() r.passNo++ r.inPass = true r.listBad = r.incomplete > 0 if r.listBad { r.incomplete-- } } func (r *simRunner) endPass() { r.mu.Lock() defer r.mu.Unlock() r.listBad, r.inPass = false, false } // ownerLocked is the attempt a VM belongs to: the job whose launch ID its // bootstrap carries, or else the attempt ID it was launched (or planted) // under. The caller holds r.mu. func (r *simRunner) ownerLocked(s *simSnap, ref isolatedjob.Ref) string { v := r.vms[ref] if v == nil { return "" } if j := s.byLaunch[v.launchID]; v.launchID != "" && j != nil { return j.attempt } return v.attempt } func bootLaunchID(b []byte) string { var boot hostedwire.Bootstrap if json.Unmarshal(b, &boot) != nil { return "" } return boot.LaunchID } // simJob is one jobs row as the checks read it. type simJob struct { attempt, launchID, state, replaces string ref isolatedjob.Ref // empty when none is saved launchedT, stopT, drainT T epoch, gen int64 pauseStarted sql.NullInt64 quiescent, cancelled bool stopRequested, dispatched bool proof string // stop_proof_json; empty when none } // simResumeOp is one resume_ops row. type simResumeOp struct { attempt, id, status string prepared int64 result sql.NullInt64 } // simSnap is the store and the fake at one moment. type simSnap struct { jobs map[string]*simJob order []string // attempt IDs, sorted byRef map[isolatedjob.Ref]*simJob byLaunch map[string]*simJob ops []simResumeOp unmatched map[isolatedjob.Ref]T vms []isolatedjob.Job // every VM the fake shows, read directly vm map[isolatedjob.Ref]isolatedjob.Job } // errSimRead rolls back the simulation's read transaction, so reading // writes no checkpoint and costs no disk sync. var errSimRead = errors.New("simulation read only") // read takes a snapshot: the jobs, resume operations and unmatched VMs in // one rolled-back transaction, then the fake's VMs. func (w *simWorld) read() (*simSnap, error) { s := &simSnap{jobs: map[string]*simJob{}, byRef: map[isolatedjob.Ref]*simJob{}, byLaunch: map[string]*simJob{}, unmatched: map[isolatedjob.Ref]T{}, vm: map[isolatedjob.Ref]isolatedjob.Job{}} err := w.store.Tx(w.ctx, func(tx *sql.Tx) error { rows, err := tx.QueryContext(w.ctx, `SELECT attempt_id, launch_id, state, coalesce(replaces_attempt, ''), coalesce(vm_ref, ''), launched_t, stop_t, drain_t, epoch, pause_generation, pause_started_t, pause_quiescent, pause_cancelled, stop_requested_t IS NOT NULL, last_dispatch_t IS NOT NULL, coalesce(stop_proof_json, '') FROM jobs ORDER BY attempt_id`) if err != nil { return err } for rows.Next() { j := &simJob{} if err := rows.Scan(&j.attempt, &j.launchID, &j.state, &j.replaces, &j.ref, &j.launchedT, &j.stopT, &j.drainT, &j.epoch, &j.gen, &j.pauseStarted, &j.quiescent, &j.cancelled, &j.stopRequested, &j.dispatched, &j.proof); err != nil { _ = rows.Close() return err } s.jobs[j.attempt], s.byLaunch[j.launchID] = j, j s.order = append(s.order, j.attempt) if j.ref != "" { s.byRef[j.ref] = j } } if err := errors.Join(rows.Err(), rows.Close()); err != nil { return err } rows, err = tx.QueryContext(w.ctx, `SELECT attempt_id, operation_id, status, prepared_epoch, result_epoch FROM resume_ops ORDER BY attempt_id, operation_id`) if err != nil { return err } for rows.Next() { var o simResumeOp if err := rows.Scan(&o.attempt, &o.id, &o.status, &o.prepared, &o.result); err != nil { _ = rows.Close() return err } s.ops = append(s.ops, o) } if err := errors.Join(rows.Err(), rows.Close()); err != nil { return err } um, err := unmatchedVMs(w.ctx, tx) s.unmatched = um if err != nil { return err } return errSimRead }) if !errors.Is(err, errSimRead) { return nil, fmt.Errorf("read the store: %w", err) } if s.vms, err = w.fake.List(context.Background()); err != nil { return nil, fmt.Errorf("read the fake: %w", err) } for _, vm := range s.vms { s.vm[vm.Ref] = vm } return s, nil } // quiet reports whether no reaper pass can change anything: no VM that is // not terminal, no intent, orphan, open stop, pause or pending resume. func (s *simSnap) quiet() bool { for _, vm := range s.vms { if !vm.State.Terminal() { return false } } if len(s.unmatched) > 0 { return false } for _, j := range s.jobs { if j.state == JobWaiting || (j.proof == "" && (j.ref != "" || j.stopRequested)) || pauseState(j.state) { return false } } for _, o := range s.ops { if o.status == opPending { return false } } return true } // nextEvent is the earliest recorded drain or stop time after now. func (s *simSnap) nextEvent(now T) (T, bool) { var next T found := false for _, j := range s.jobs { for _, at := range []T{j.drainT, j.stopT} { if at > now && (!found || at < next) { next, found = at, true } } } return next, found } // liveOwnedLocked lists the live VMs that belong to attempt. The caller // holds r.mu. func (r *simRunner) liveOwnedLocked(s *simSnap, attempt string) []string { var out []string for _, vm := range s.vms { if vm.State.Live() && r.ownerLocked(s, vm.Ref) == attempt { out = append(out, fmt.Sprintf("%s %s", vm.Ref, vm.State)) } } return out } // checkOrphanStopLocked is I3, as the orphan stop is sent: the VM is no // job's saved Ref and no waiting intent's VM, was recorded unmatched, and // has had OrphanGrace of controller time since (by the store's record and // by the simulation's own record of when the VM appeared), unless it was // recorded before this process opened the store after a restart. func (r *simRunner) checkOrphanStopLocked(ref isolatedjob.Ref) { s, err := r.w.read() if err != nil { r.violate("I3: %v", err) return } now := r.w.now() if j := s.byRef[ref]; j != nil { r.violate("I3: orphan stop of %s, the saved Ref of %s", ref, j.attempt) } if j := s.jobs[r.ownerLocked(s, ref)]; j != nil && j.state == JobWaiting { r.violate("I3: orphan stop of %s, the VM of waiting intent %s", ref, j.attempt) } first, ok := s.unmatched[ref] early := r.w.store.Restarted() && first < r.w.store.OpenedAt() switch { case !ok: r.violate("I3: orphan stop of %s, which unmatched_vms does not hold", ref) case now-first < T(OrphanGrace) && !early: r.violate("I3: orphan stop of %s at %v, first seen at %v: grace not over", ref, simDur(now), simDur(first)) } if v := r.vms[ref]; v != nil && now-v.created < T(OrphanGrace) && !(r.w.restarted && v.created < r.w.openedAt) { r.violate("I3: orphan stop of %s at %v; the VM appeared at %v", ref, simDur(now), simDur(v.created)) } } // checkSuspendLocked is I5, as the provider Suspend is sent. The store // must hold the job suspending in its current generation, acknowledged // (pause_quiescent), not cancelled, its pause open; a Suspend call the // simulation made must have named that stored generation; and the // simulation's own history must agree: that generation is the last drain // it saw accepted, at the stored pause start, and it saw it acknowledged in // time. func (r *simRunner) checkSuspendLocked(ref isolatedjob.Ref) { s, err := r.w.read() if err != nil { r.violate("I5: %v", err) return } j := s.byRef[ref] if j == nil { r.violate("I5: provider suspend of %s, which no job holds", ref) return } if j.state != JobSuspending || !j.quiescent || j.cancelled || !j.pauseStarted.Valid { r.violate("I5: provider suspend of %s (%s): stored state %s, generation %d, quiescent %v, cancelled %v, pause started %v", ref, j.attempt, j.state, j.gen, j.quiescent, j.cancelled, j.pauseStarted) } if op := r.suspendOp; op != nil && op.attempt == j.attempt && op.gen != j.gen { r.violate("I5: provider suspend of %s for named generation %d; the stored one is %d", ref, op.gen, j.gen) } if p := r.w.m.pause[j.attempt]; p == nil || !p.open || !p.acked || p.gen != j.gen || int64(p.drainedAt) != j.pauseStarted.Int64 { r.violate("I5: provider suspend of %s (%s) at stored generation %d; the simulation's history is %+v", ref, j.attempt, j.gen, p) } } // checkReplacementLocked is I6's launch half: a replacement's provider // Launch needs the replaced attempt to hold stop proof and have no live VM. func (r *simRunner) checkReplacementLocked(spec isolatedjob.LaunchSpec) { s, err := r.w.read() if err != nil { r.violate("I6: %v", err) return } j := s.byLaunch[bootLaunchID(spec.Bootstrap)] if j == nil { j = s.jobs[spec.AttemptID] } if j == nil || j.replaces == "" { return } if old := s.jobs[j.replaces]; old == nil || old.proof == "" { r.violate("I6: replacement %s launched before %s holds stop proof", j.attempt, j.replaces) } if live := r.liveOwnedLocked(s, j.replaces); len(live) > 0 { r.violate("I6: replacement %s launched while %s still has %v", j.attempt, j.replaces, live) } } // checkResumeLocked is I7's call half: a provider Resume needs a pending // operation prepared at one above the job's epoch, which is not yet raised. // It returns that operation's ID, the one later running evidence is for. func (r *simRunner) checkResumeLocked(ref isolatedjob.Ref) string { s, err := r.w.read() if err != nil { r.violate("I7: %v", err) return "" } j := s.byRef[ref] if j == nil { r.violate("I7: provider resume of %s, which no job holds", ref) return "" } var pending []simResumeOp for _, o := range s.ops { if o.attempt == j.attempt && o.status == opPending { pending = append(pending, o) } } switch { case len(pending) != 1: r.violate("I7: provider resume of %s (%s) with %d prepared operations", ref, j.attempt, len(pending)) case pending[0].prepared != j.epoch+1: r.violate("I7: provider resume of %s for operation %s prepared at epoch %d while the job's epoch is %d", ref, pending[0].id, pending[0].prepared, j.epoch) } if len(pending) == 0 { return "" } return pending[0].id } // check runs every invariant on snapshot s and returns the violations, // those the provider calls found first. M0 lines are the model's own // consistency (the simulation's clock and deadlines agree with the store). func (w *simWorld) check(s *simSnap) []string { r := w.run r.mu.Lock() defer r.mu.Unlock() bad := r.bad r.bad = nil add := func(format string, args ...any) { bad = append(bad, fmt.Sprintf(format, args...)) } now := w.now() if st := w.store.Clock().Now(); st != now { add("M0: store clock reads %v, the model %v", simDur(st), simDur(now)) } for _, id := range s.order { if _, ok := w.m.stopAt[id]; !ok { w.m.stopAt[id] = w.opT + T(w.m.req[id].MaxLifetime-StopBefore) if got := s.jobs[id].stopT; got != w.m.stopAt[id] { add("M0: %s saved with stop time %v, the model expects %v", id, simDur(got), simDur(w.m.stopAt[id])) } } } // I1: at most one live VM per attempt. live := map[string][]string{} for _, vm := range s.vms { if vm.State.Live() { o := r.ownerLocked(s, vm.Ref) live[o] = append(live[o], string(vm.Ref)) } } for _, o := range sortedKeys(live) { if len(live[o]) > 1 { add("I1: attempt %s has %d live VMs: %v", o, len(live[o]), live[o]) } } // I2: every VM is a saved Ref, matches a stored intent's attempt, or // was planted. for _, vm := range s.vms { v := r.vms[vm.Ref] switch { case s.byRef[vm.Ref] != nil: case v == nil: add("I2: VM %s appeared without a Launch or a Plant", vm.Ref) case v.planted, s.jobs[v.attempt] != nil: default: add("I2: VM %s (attempt %s, %s) is no saved Ref, matches no stored intent and was not planted", vm.Ref, v.attempt, vm.State) } } // I4, as ruling R24 words it: every live VM (stopping included) tied // to a recorded attempt, by a saved Ref or by the fake's spec attempt // ID, is live no later than max(stop_t, OpenedAt) + ReapInterval, plus // one interval per pass of its current run of throttled Stops // (creditLocked); a // stopping VM also passes when its first effective Stop came within // the bound in force then; a VM with no saved Ref gets OrphanGrace + // ReapInterval more, and is exempt while R22 deferral applies, then // bounded from one interval after it ends (simDeferral). R24a (d): a VM // with no saved Ref also gets one interval for each pass since it // appeared in which a List failed, as the reaper handles orphans only on // complete Lists. And (e), after R20: after a restart, a job launched // before the open gets one interval for each pass since the open in // which a Get of its VM failed (at most RestartGetTries), as its stop // time is re-based only on a Get that answers. And (f), carrying (c) // over: a VM claimed late (a replay's Launch reply first carried its // Ref, perhaps in the orphan recheck after the deadline step) is // bounded no earlier than one interval after that reply. deferral := false for _, j := range s.jobs { deferral = deferral || (j.state == JobWaiting && j.ref == "" && j.dispatched) } for _, vm := range s.vms { j, v := s.byRef[vm.Ref], r.vms[vm.Ref] noRef := j == nil if noRef && v != nil { j = s.jobs[v.attempt] } if j == nil || !vm.State.Live() { continue } d := w.m.deferral[vm.Ref] if noRef { if d == nil { d = &simDeferral{} w.m.deferral[vm.Ref] = d } if d.observe(deferral, now, r.passNo); d.on { continue } } base := max(min(j.stopT, w.m.stopAt[j.attempt]), w.store.OpenedAt()) + T(ReapInterval) if noRef { base += T(OrphanGrace + ReapInterval) for _, p := range r.listFail { if v != nil && p >= v.pass { base += T(ReapInterval) } } } if w.store.Restarted() && j.launchedT <= w.store.OpenedAt() { n := 0 for _, p := range r.getFail[vm.Ref] { if p > r.openPass { n++ } } base += T(ReapInterval) * T(min(n, RestartGetTries)) } if v != nil && v.claimed > 0 { base = max(base, v.claimed+T(ReapInterval)) } if d != nil { if b, ok := d.bound(r.listFail); ok { base = max(base, b) } } credit := r.creditLocked(vm.Ref) if now <= base+T(ReapInterval)*T(credit) { continue } if st, ok := r.stoppedB[vm.Ref]; ok && vm.State == isolatedjob.StateStopping && st.at <= base+T(ReapInterval)*T(st.credit) { continue } add("I4: VM %s of %s is %s at %v, its stop time %v (bound %v, throttle run %d, saved Ref %v)", vm.Ref, j.attempt, vm.State, simDur(now), simDur(j.stopT), simDur(base), credit, !noRef) } // I5, the store against the simulation's history: a job's stored // generation is the last drain the simulation saw accepted, started // when it drained, and is acknowledged only if the simulation saw an // acknowledgement of it in time. for _, id := range s.order { j, p := s.jobs[id], w.m.pause[id] switch { case p == nil && j.gen != 0: add("I5: %s holds generation %d with no drain accepted", id, j.gen) case p == nil: case j.gen != p.gen: add("I5: %s holds generation %d; the last drain accepted gave %d", id, j.gen, p.gen) case j.pauseStarted.Valid && j.pauseStarted.Int64 != int64(p.drainedAt): add("I5: %s pause started at %v; generation %d drained at %v", id, simDur(T(j.pauseStarted.Int64)), p.gen, simDur(p.drainedAt)) case j.quiescent && !p.acked: add("I5: %s generation %d is stored acknowledged; no acknowledgement of it came in time", id, j.gen) } } // I6: proof only from a terminal state, and never while a VM of the // attempt is live. for _, id := range s.order { j := s.jobs[id] if j.proof == "" { continue } var p hostedwire.StopProof if err := json.Unmarshal([]byte(j.proof), &p); err != nil || !p.State.Terminal() { add("I6: %s holds proof from state %q (%v)", id, p.State, err) } if l := r.liveOwnedLocked(s, id); len(l) > 0 { add("I6: %s holds stop proof while %v", id, l) } } // I7: the epoch is the number of done operations, each raised it by // exactly one, a newly done one followed a running read after its last // resume call, and done operations stay done with their epoch. ops := map[string][]simResumeOp{} done := map[[2]string]int64{} for _, o := range s.ops { ops[o.attempt] = append(ops[o.attempt], o) if o.status == opDone { done[[2]string{o.attempt, o.id}] = o.result.Int64 } } for _, id := range s.order { j := s.jobs[id] n := int64(0) for _, o := range ops[id] { if o.status == opDone { n++ } } seen := map[int64]bool{} for _, o := range ops[id] { if o.status != opDone { continue } // n done operations with distinct epochs in 1..n: each raised // the epoch by one, once. if !o.result.Valid || o.result.Int64 != o.prepared || o.prepared < 1 || o.prepared > n || seen[o.prepared] { add("I7: %s operation %s done with epoch %v, prepared %d, of %d done", id, o.id, o.result, o.prepared, n) } seen[o.prepared] = true key := [2]string{id, o.id} if _, known := w.m.done[key]; !known { if r.runningFor[j.ref] != o.id { add("I7: %s operation %s committed with no running read of %s after a provider resume for it (evidence for %q)", id, o.id, j.ref, r.runningFor[j.ref]) } delete(r.runningFor, j.ref) w.m.done[key] = o.result.Int64 w.closePause(id) } } if j.epoch != n { add("I7: %s has epoch %d after %d done resume operations", id, j.epoch, n) } } for _, key := range sortedKeys(w.m.done) { if e, ok := done[key]; !ok || e != w.m.done[key] { add("I7: %s operation %s was done at epoch %d; now %v", key[0], key[1], w.m.done[key], e) } } for _, x := range w.m.returned { if e, ok := done[[2]string{x.attempt, x.op}]; !ok || e != x.epoch { add("I7: Resume(%s, %s) returned epoch %d; the store holds %d (done %v)", x.attempt, x.op, x.epoch, e, ok) } } w.m.returned = w.m.returned[:0] return bad } // sortedKeys returns m's keys in a fixed order, so reports are stable. func sortedKeys[K comparable, V any](m map[K]V) []K { out := slices.Collect(maps.Keys(m)) slices.SortFunc(out, func(a, b K) int { return strings.Compare(fmt.Sprint(a), fmt.Sprint(b)) }) return out } // TestSimDeadlineCredits checks I4's two time credits directly, on the // review's examples: a throttle run broken by a pass with no Stop gives no // credit, and the bound after R22 deferral runs from the deferral's end. func TestSimDeadlineCredits(t *testing.T) { min := func(m int) T { return T(time.Duration(m) * time.Minute) } // stop_t 10m, so the unextended bound is 11m. for _, c := range []struct { name string throttled []int // minutes whose pass throttles the Stop stopAt int // minute whose pass stops the VM accepted bool }{ {"throttled at 10m, no Stop at 11m, stopped at 12m", []int{10}, 12, false}, {"throttled at 10m and 11m, stopped at 12m", []int{10, 11}, 12, true}, {"throttled at 10m, stopped at 11m", []int{10}, 11, true}, } { clk := isolatedjobtest.NewFakeClock(testWall) r := newSimRunner(nil, &simWorld{clk: clk}) for m := 10; m <= c.stopAt; m++ { clk.AdvanceMono(time.Duration(min(m)) - clk.Mono()) r.beginPass() if slices.Contains(c.throttled, m) || m == c.stopAt { r.noteStopLocked("vm-1", m != c.stopAt) } r.endPass() } st := r.stoppedB["vm-1"] if got := st.at <= min(11)+T(ReapInterval)*T(st.credit); got != c.accepted { t.Errorf("%s: stop at %v with credit %d accepted %v, want %v", c.name, simDur(st.at), st.credit, got, c.accepted) } } // Deferred at 30m; the last waiting intent resolves in the 31m pass. for _, c := range []struct { name string listFail []int // passes (numbered by minute) whose List failed liveAt int ok bool }{ {"incomplete List at 31m, stopped by the 32m pass", []int{31}, 32, true}, {"complete Lists, still live at 33m", nil, 33, false}, {"incomplete Lists at 31m and 32m, live at 33m", []int{31, 32}, 33, true}, } { d := &simDeferral{} d.observe(true, min(30), 30) d.observe(false, min(31), 31) b, _ := d.bound(c.listFail) if got := min(c.liveAt) <= b; got != c.ok { t.Errorf("%s: live at %v within bound %v is %v, want %v", c.name, simDur(min(c.liveAt)), simDur(b), got, c.ok) } } }