| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "maps" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 17 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 18 | "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" |
| 19 | ) |
| 20 | |
| 21 | // This file holds what the lifecycle simulation (sim_test.go) checks: the |
| 22 | // provider wrapper that sees every call the controller makes, the snapshot |
| 23 | // of the store and the fake, and the seven invariants of spec §14. |
| 24 | |
| 25 | // simVM is what the simulation knows about one VM the fake holds. |
| 26 | type simVM struct { |
| 27 | attempt string // the spec's attempt ID (the client token), or the planted name |
| 28 | launchID string // from the bootstrap; empty for a planted VM |
| 29 | planted bool |
| 30 | claimed T // when a Launch reply first carried its Ref; 0 if none yet |
| 31 | created T // model controller time when the VM appeared |
| 32 | pass int // reaper passes begun when it appeared |
| 33 | } |
| 34 | |
| 35 | // simGen names the Suspend call the simulation is making: its attempt and |
| 36 | // the generation it asked for. |
| 37 | type simGen struct { |
| 38 | attempt string |
| 39 | gen int64 |
| 40 | } |
| 41 | |
| 42 | // simRunner wraps the fake provider. It queues the simulation's faults and |
| 43 | // hands each one to the fake (Inject) just before the call it is meant for, |
| 44 | // so the fake's own queue is empty between calls and the checks can read the |
| 45 | // fake directly. It records every VM the fake creates, whatever the reply |
| 46 | // said, and checks the call-time invariants (I3, I5, I6, I7) against the |
| 47 | // store as the call is made; no transaction is open across a provider call, |
| 48 | // so the store can be read here. |
| 49 | type simRunner struct { |
| 50 | fake *isolatedjob.Fake |
| 51 | w *simWorld |
| 52 | |
| 53 | mu sync.Mutex |
| 54 | pending map[isolatedjob.Op][]isolatedjob.Fault |
| 55 | incomplete int // reaper passes left whose List calls all come back incomplete |
| 56 | listBad bool // the pass running now is one of them |
| 57 | inPass bool // a reaper pass is running |
| 58 | vms map[isolatedjob.Ref]*simVM |
| 59 | suspendOp *simGen |
| 60 | bad []string // call-time violations, reported by the next check |
| 61 | |
| 62 | // For I4 (ruling R24): passes begun; per VM, the current unbroken run |
| 63 | // of passes with a throttled Stop (reset by any Stop that is not |
| 64 | // throttled) and the first Stop that took effect, or the provider's own |
| 65 | // end, with the run credited when it was issued. |
| 66 | passNo int |
| 67 | listFail []int // passes in which a List failed, so orphans were not handled |
| 68 | getFail map[isolatedjob.Ref][]int // passes in which a Get of the VM failed |
| 69 | openPass int // passNo at the latest open |
| 70 | stopRun map[isolatedjob.Ref]int |
| 71 | runPass map[isolatedjob.Ref]int |
| 72 | stoppedB map[isolatedjob.Ref]simStopAt |
| 73 | |
| 74 | // For I7: per VM, the pending operation its latest provider Resume was |
| 75 | // for, and the operation whose resume a later Get saw running. Any |
| 76 | // observed change of phase (a Get reading another state, a Suspend or a |
| 77 | // Stop) drops the running evidence. |
| 78 | resumeOp map[isolatedjob.Ref]string |
| 79 | runningFor map[isolatedjob.Ref]string |
| 80 | } |
| 81 | |
| 82 | // simStopAt is when a Stop for a VM first took effect, and the throttle |
| 83 | // credit (in reaper intervals) its I4 bound had then. |
| 84 | type simStopAt struct { |
| 85 | at T |
| 86 | credit int |
| 87 | } |
| 88 | |
| 89 | func newSimRunner(fake *isolatedjob.Fake, w *simWorld) *simRunner { |
| 90 | return &simRunner{fake: fake, w: w, pending: map[isolatedjob.Op][]isolatedjob.Fault{}, |
| 91 | vms: map[isolatedjob.Ref]*simVM{}, getFail: map[isolatedjob.Ref][]int{}, stopRun: map[isolatedjob.Ref]int{}, runPass: map[isolatedjob.Ref]int{}, |
| 92 | stoppedB: map[isolatedjob.Ref]simStopAt{}, resumeOp: map[isolatedjob.Ref]string{}, runningFor: map[isolatedjob.Ref]string{}} |
| 93 | } |
| 94 | |
| 95 | func (r *simRunner) queue(op isolatedjob.Op, f isolatedjob.Fault) { |
| 96 | r.mu.Lock() |
| 97 | defer r.mu.Unlock() |
| 98 | r.pending[op] = append(r.pending[op], f) |
| 99 | } |
| 100 | |
| 101 | // inject hands the fault for this call of op to the fake. The caller holds |
| 102 | // r.mu. |
| 103 | func (r *simRunner) inject(op isolatedjob.Op) isolatedjob.Fault { |
| 104 | var f isolatedjob.Fault |
| 105 | if q := r.pending[op]; len(q) > 0 { |
| 106 | f, r.pending[op] = q[0], q[1:] |
| 107 | } |
| 108 | if op == isolatedjob.OpList && r.listBad { |
| 109 | f = isolatedjob.FaultIncompleteList |
| 110 | } |
| 111 | if f != "" { |
| 112 | r.fake.Inject(op, f) |
| 113 | } |
| 114 | return f |
| 115 | } |
| 116 | |
| 117 | func (r *simRunner) violate(format string, args ...any) { |
| 118 | r.bad = append(r.bad, fmt.Sprintf(format, args...)) |
| 119 | } |
| 120 | |
| 121 | // visibleLocked returns the Refs the fake shows now. |
| 122 | func (r *simRunner) visibleLocked() map[isolatedjob.Ref]bool { |
| 123 | vms, _ := r.fake.List(context.Background()) |
| 124 | out := make(map[isolatedjob.Ref]bool, len(vms)) |
| 125 | for _, vm := range vms { |
| 126 | out[vm.Ref] = true |
| 127 | } |
| 128 | return out |
| 129 | } |
| 130 | |
| 131 | func (r *simRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { |
| 132 | r.mu.Lock() |
| 133 | defer r.mu.Unlock() |
| 134 | r.checkReplacementLocked(s) |
| 135 | before := r.visibleLocked() |
| 136 | var f isolatedjob.Fault |
| 137 | if s.Validate(r.fake.Limits()) == nil { // a spec the fake refuses uses up no fault |
| 138 | f = r.inject(isolatedjob.OpLaunch) |
| 139 | } |
| 140 | ref, err := r.fake.Launch(ctx, s) |
| 141 | for now := range r.visibleLocked() { |
| 142 | if !before[now] { |
| 143 | r.vms[now] = &simVM{attempt: s.AttemptID, launchID: bootLaunchID(s.Bootstrap), created: r.w.now(), pass: r.passNo} |
| 144 | } |
| 145 | } |
| 146 | if v := r.vms[ref]; err == nil && v != nil && v.claimed == 0 { |
| 147 | v.claimed = r.w.now() |
| 148 | } |
| 149 | r.w.logf(" provider launch %s%s -> %s %s", s.AttemptID, faultNote(f), ref, errText(err)) |
| 150 | return ref, err |
| 151 | } |
| 152 | |
| 153 | func (r *simRunner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { |
| 154 | r.mu.Lock() |
| 155 | defer r.mu.Unlock() |
| 156 | f := r.inject(isolatedjob.OpGet) |
| 157 | j, err := r.fake.Get(ctx, ref) |
| 158 | switch { |
| 159 | case err == nil && j.State == isolatedjob.StateRunning: |
| 160 | if op := r.resumeOp[ref]; op != "" { |
| 161 | r.runningFor[ref] = op |
| 162 | } |
| 163 | case err == nil || errors.Is(err, isolatedjob.ErrNotFound): |
| 164 | delete(r.runningFor, ref) // another phase: earlier running evidence is stale |
| 165 | case !slices.Contains(r.getFail[ref], r.passNo): |
| 166 | r.getFail[ref] = append(r.getFail[ref], r.passNo) |
| 167 | } |
| 168 | if f != "" || err != nil { |
| 169 | r.w.logf(" provider get %s%s -> %s %s", ref, faultNote(f), j.State, errText(err)) |
| 170 | } |
| 171 | return j, err |
| 172 | } |
| 173 | |
| 174 | func (r *simRunner) Suspend(ctx context.Context, ref isolatedjob.Ref) error { |
| 175 | r.mu.Lock() |
| 176 | defer r.mu.Unlock() |
| 177 | r.checkSuspendLocked(ref) |
| 178 | f := r.inject(isolatedjob.OpSuspend) |
| 179 | err := r.fake.Suspend(ctx, ref) |
| 180 | r.phaseLocked(ref, err) |
| 181 | r.w.logf(" provider suspend %s%s -> %s", ref, faultNote(f), errText(err)) |
| 182 | return err |
| 183 | } |
| 184 | |
| 185 | func (r *simRunner) Resume(ctx context.Context, ref isolatedjob.Ref) error { |
| 186 | r.mu.Lock() |
| 187 | defer r.mu.Unlock() |
| 188 | r.resumeOp[ref] = r.checkResumeLocked(ref) |
| 189 | delete(r.runningFor, ref) |
| 190 | f := r.inject(isolatedjob.OpResume) |
| 191 | err := r.fake.Resume(ctx, ref) |
| 192 | r.w.logf(" provider resume %s%s -> %s", ref, faultNote(f), errText(err)) |
| 193 | return err |
| 194 | } |
| 195 | |
| 196 | func (r *simRunner) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error { |
| 197 | r.mu.Lock() |
| 198 | defer r.mu.Unlock() |
| 199 | if reason == reasonOrphan { |
| 200 | r.checkOrphanStopLocked(ref) |
| 201 | } |
| 202 | f := r.inject(isolatedjob.OpStop) |
| 203 | err := r.fake.Stop(ctx, ref, reason) |
| 204 | r.phaseLocked(ref, err) |
| 205 | r.noteStopLocked(ref, errors.Is(err, isolatedjob.ErrThrottled)) |
| 206 | r.w.logf(" provider stop %s (%s)%s -> %s", ref, reason, faultNote(f), errText(err)) |
| 207 | return err |
| 208 | } |
| 209 | |
| 210 | func (r *simRunner) List(ctx context.Context) ([]isolatedjob.Job, error) { |
| 211 | r.mu.Lock() |
| 212 | defer r.mu.Unlock() |
| 213 | f := r.inject(isolatedjob.OpList) |
| 214 | vms, err := r.fake.List(ctx) |
| 215 | if err != nil && !slices.Contains(r.listFail, r.passNo) { |
| 216 | r.listFail = append(r.listFail, r.passNo) |
| 217 | } |
| 218 | if f != "" { |
| 219 | r.w.logf(" provider list%s -> %d VMs %s", faultNote(f), len(vms), errText(err)) |
| 220 | } |
| 221 | return vms, err |
| 222 | } |
| 223 | |
| 224 | func (r *simRunner) Limits() isolatedjob.Limits { return r.fake.Limits() } |
| 225 | |
| 226 | // phaseLocked drops a VM's running evidence after a Suspend or Stop that |
| 227 | // was not throttled: its phase may have changed. |
| 228 | func (r *simRunner) phaseLocked(ref isolatedjob.Ref, err error) { |
| 229 | if !errors.Is(err, isolatedjob.ErrThrottled) { |
| 230 | delete(r.runningFor, ref) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // creditLocked is ref's throttle credit (R24 b): the length of its current |
| 235 | // run of consecutive reaper passes that each sent it a throttled Stop. A |
| 236 | // pass with none ends the run, so between passes the run is current only |
| 237 | // if the last pass threw one, and during a pass also if the one before did. |
| 238 | func (r *simRunner) creditLocked(ref isolatedjob.Ref) int { |
| 239 | last := r.passNo |
| 240 | if r.inPass { |
| 241 | last-- |
| 242 | } |
| 243 | if r.runPass[ref] < last { |
| 244 | return 0 |
| 245 | } |
| 246 | return r.stopRun[ref] |
| 247 | } |
| 248 | |
| 249 | // noteStopLocked records a Stop of ref. A throttled one in a pass extends |
| 250 | // the current run, or starts a new one; a Stop that took effect is |
| 251 | // recorded once (stoppedLocked). |
| 252 | func (r *simRunner) noteStopLocked(ref isolatedjob.Ref, throttled bool) { |
| 253 | switch { |
| 254 | case !throttled: |
| 255 | r.stoppedLocked(ref) |
| 256 | case r.inPass: |
| 257 | if r.creditLocked(ref) == 0 { |
| 258 | r.stopRun[ref] = 0 // an interrupted run ends with its credit |
| 259 | } |
| 260 | if r.stopRun[ref] == 0 || r.runPass[ref] != r.passNo { |
| 261 | r.stopRun[ref]++ |
| 262 | } |
| 263 | r.runPass[ref] = r.passNo |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // stoppedLocked records the first Stop of ref that took effect (or the |
| 268 | // provider's own end) with the throttle credit in force, and ends the run |
| 269 | // of throttled Stops. |
| 270 | func (r *simRunner) stoppedLocked(ref isolatedjob.Ref) { |
| 271 | if _, ok := r.stoppedB[ref]; !ok { |
| 272 | r.stoppedB[ref] = simStopAt{at: r.w.now(), credit: r.creditLocked(ref)} |
| 273 | } |
| 274 | r.stopRun[ref] = 0 |
| 275 | } |
| 276 | |
| 277 | // simDeferral follows R22 deferral for one VM with no saved Ref (R24a c): |
| 278 | // I4 does not apply while it does; once it ends, the bound runs from one |
| 279 | // interval after the first check that found it ended, plus one interval |
| 280 | // per later pass whose List failed (R24a d). |
| 281 | type simDeferral struct { |
| 282 | on, ended bool |
| 283 | at T |
| 284 | pass int |
| 285 | } |
| 286 | |
| 287 | func (d *simDeferral) observe(applies bool, now T, pass int) { |
| 288 | switch { |
| 289 | case applies: |
| 290 | d.on, d.ended = true, false |
| 291 | case d.on: |
| 292 | d.on, d.ended, d.at, d.pass = false, true, now, pass |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | func (d *simDeferral) bound(listFail []int) (T, bool) { |
| 297 | if !d.ended { |
| 298 | return 0, false |
| 299 | } |
| 300 | b := d.at + T(ReapInterval) |
| 301 | for _, p := range listFail { |
| 302 | if p > d.pass { |
| 303 | b += T(ReapInterval) |
| 304 | } |
| 305 | } |
| 306 | return b, true |
| 307 | } |
| 308 | |
| 309 | // end is the provider stopping a VM on its own, with no controller call. |
| 310 | func (r *simRunner) end(ref isolatedjob.Ref) { |
| 311 | r.mu.Lock() |
| 312 | defer r.mu.Unlock() |
| 313 | _ = r.fake.Stop(context.Background(), ref, "ended") |
| 314 | delete(r.runningFor, ref) |
| 315 | r.stoppedLocked(ref) |
| 316 | } |
| 317 | |
| 318 | // plant adds an orphan VM no Launch asked for. |
| 319 | func (r *simRunner) plant(name string) isolatedjob.Ref { |
| 320 | r.mu.Lock() |
| 321 | defer r.mu.Unlock() |
| 322 | ref := r.fake.Plant(isolatedjob.LaunchSpec{AttemptID: name}) |
| 323 | r.vms[ref] = &simVM{attempt: name, planted: true, created: r.w.now()} |
| 324 | return ref |
| 325 | } |
| 326 | |
| 327 | // beginPass applies the next incomplete-List window, if any, to the pass |
| 328 | // about to run. |
| 329 | func (r *simRunner) beginPass() { |
| 330 | r.mu.Lock() |
| 331 | defer r.mu.Unlock() |
| 332 | r.passNo++ |
| 333 | r.inPass = true |
| 334 | r.listBad = r.incomplete > 0 |
| 335 | if r.listBad { |
| 336 | r.incomplete-- |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | func (r *simRunner) endPass() { |
| 341 | r.mu.Lock() |
| 342 | defer r.mu.Unlock() |
| 343 | r.listBad, r.inPass = false, false |
| 344 | } |
| 345 | |
| 346 | // ownerLocked is the attempt a VM belongs to: the job whose launch ID its |
| 347 | // bootstrap carries, or else the attempt ID it was launched (or planted) |
| 348 | // under. The caller holds r.mu. |
| 349 | func (r *simRunner) ownerLocked(s *simSnap, ref isolatedjob.Ref) string { |
| 350 | v := r.vms[ref] |
| 351 | if v == nil { |
| 352 | return "" |
| 353 | } |
| 354 | if j := s.byLaunch[v.launchID]; v.launchID != "" && j != nil { |
| 355 | return j.attempt |
| 356 | } |
| 357 | return v.attempt |
| 358 | } |
| 359 | |
| 360 | func bootLaunchID(b []byte) string { |
| 361 | var boot hostedwire.Bootstrap |
| 362 | if json.Unmarshal(b, &boot) != nil { |
| 363 | return "" |
| 364 | } |
| 365 | return boot.LaunchID |
| 366 | } |
| 367 | |
| 368 | // simJob is one jobs row as the checks read it. |
| 369 | type simJob struct { |
| 370 | attempt, launchID, state, replaces string |
| 371 | ref isolatedjob.Ref // empty when none is saved |
| 372 | launchedT, stopT, drainT T |
| 373 | epoch, gen int64 |
| 374 | pauseStarted sql.NullInt64 |
| 375 | quiescent, cancelled bool |
| 376 | stopRequested, dispatched bool |
| 377 | proof string // stop_proof_json; empty when none |
| 378 | } |
| 379 | |
| 380 | // simResumeOp is one resume_ops row. |
| 381 | type simResumeOp struct { |
| 382 | attempt, id, status string |
| 383 | prepared int64 |
| 384 | result sql.NullInt64 |
| 385 | } |
| 386 | |
| 387 | // simSnap is the store and the fake at one moment. |
| 388 | type simSnap struct { |
| 389 | jobs map[string]*simJob |
| 390 | order []string // attempt IDs, sorted |
| 391 | byRef map[isolatedjob.Ref]*simJob |
| 392 | byLaunch map[string]*simJob |
| 393 | ops []simResumeOp |
| 394 | unmatched map[isolatedjob.Ref]T |
| 395 | vms []isolatedjob.Job // every VM the fake shows, read directly |
| 396 | vm map[isolatedjob.Ref]isolatedjob.Job |
| 397 | } |
| 398 | |
| 399 | // errSimRead rolls back the simulation's read transaction, so reading |
| 400 | // writes no checkpoint and costs no disk sync. |
| 401 | var errSimRead = errors.New("simulation read only") |
| 402 | |
| 403 | // read takes a snapshot: the jobs, resume operations and unmatched VMs in |
| 404 | // one rolled-back transaction, then the fake's VMs. |
| 405 | func (w *simWorld) read() (*simSnap, error) { |
| 406 | s := &simSnap{jobs: map[string]*simJob{}, byRef: map[isolatedjob.Ref]*simJob{}, byLaunch: map[string]*simJob{}, |
| 407 | unmatched: map[isolatedjob.Ref]T{}, vm: map[isolatedjob.Ref]isolatedjob.Job{}} |
| 408 | err := w.store.Tx(w.ctx, func(tx *sql.Tx) error { |
| 409 | rows, err := tx.QueryContext(w.ctx, `SELECT attempt_id, launch_id, state, coalesce(replaces_attempt, ''), |
| 410 | coalesce(vm_ref, ''), launched_t, stop_t, drain_t, epoch, pause_generation, pause_started_t, pause_quiescent, |
| 411 | pause_cancelled, stop_requested_t IS NOT NULL, last_dispatch_t IS NOT NULL, |
| 412 | coalesce(stop_proof_json, '') FROM jobs ORDER BY attempt_id`) |
| 413 | if err != nil { |
| 414 | return err |
| 415 | } |
| 416 | for rows.Next() { |
| 417 | j := &simJob{} |
| 418 | if err := rows.Scan(&j.attempt, &j.launchID, &j.state, &j.replaces, &j.ref, &j.launchedT, &j.stopT, &j.drainT, |
| 419 | &j.epoch, &j.gen, &j.pauseStarted, &j.quiescent, &j.cancelled, &j.stopRequested, &j.dispatched, |
| 420 | &j.proof); err != nil { |
| 421 | _ = rows.Close() |
| 422 | return err |
| 423 | } |
| 424 | s.jobs[j.attempt], s.byLaunch[j.launchID] = j, j |
| 425 | s.order = append(s.order, j.attempt) |
| 426 | if j.ref != "" { |
| 427 | s.byRef[j.ref] = j |
| 428 | } |
| 429 | } |
| 430 | if err := errors.Join(rows.Err(), rows.Close()); err != nil { |
| 431 | return err |
| 432 | } |
| 433 | rows, err = tx.QueryContext(w.ctx, `SELECT attempt_id, operation_id, status, prepared_epoch, result_epoch |
| 434 | FROM resume_ops ORDER BY attempt_id, operation_id`) |
| 435 | if err != nil { |
| 436 | return err |
| 437 | } |
| 438 | for rows.Next() { |
| 439 | var o simResumeOp |
| 440 | if err := rows.Scan(&o.attempt, &o.id, &o.status, &o.prepared, &o.result); err != nil { |
| 441 | _ = rows.Close() |
| 442 | return err |
| 443 | } |
| 444 | s.ops = append(s.ops, o) |
| 445 | } |
| 446 | if err := errors.Join(rows.Err(), rows.Close()); err != nil { |
| 447 | return err |
| 448 | } |
| 449 | um, err := unmatchedVMs(w.ctx, tx) |
| 450 | s.unmatched = um |
| 451 | if err != nil { |
| 452 | return err |
| 453 | } |
| 454 | return errSimRead |
| 455 | }) |
| 456 | if !errors.Is(err, errSimRead) { |
| 457 | return nil, fmt.Errorf("read the store: %w", err) |
| 458 | } |
| 459 | if s.vms, err = w.fake.List(context.Background()); err != nil { |
| 460 | return nil, fmt.Errorf("read the fake: %w", err) |
| 461 | } |
| 462 | for _, vm := range s.vms { |
| 463 | s.vm[vm.Ref] = vm |
| 464 | } |
| 465 | return s, nil |
| 466 | } |
| 467 | |
| 468 | // quiet reports whether no reaper pass can change anything: no VM that is |
| 469 | // not terminal, no intent, orphan, open stop, pause or pending resume. |
| 470 | func (s *simSnap) quiet() bool { |
| 471 | for _, vm := range s.vms { |
| 472 | if !vm.State.Terminal() { |
| 473 | return false |
| 474 | } |
| 475 | } |
| 476 | if len(s.unmatched) > 0 { |
| 477 | return false |
| 478 | } |
| 479 | for _, j := range s.jobs { |
| 480 | if j.state == JobWaiting || (j.proof == "" && (j.ref != "" || j.stopRequested)) || pauseState(j.state) { |
| 481 | return false |
| 482 | } |
| 483 | } |
| 484 | for _, o := range s.ops { |
| 485 | if o.status == opPending { |
| 486 | return false |
| 487 | } |
| 488 | } |
| 489 | return true |
| 490 | } |
| 491 | |
| 492 | // nextEvent is the earliest recorded drain or stop time after now. |
| 493 | func (s *simSnap) nextEvent(now T) (T, bool) { |
| 494 | var next T |
| 495 | found := false |
| 496 | for _, j := range s.jobs { |
| 497 | for _, at := range []T{j.drainT, j.stopT} { |
| 498 | if at > now && (!found || at < next) { |
| 499 | next, found = at, true |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | return next, found |
| 504 | } |
| 505 | |
| 506 | // liveOwnedLocked lists the live VMs that belong to attempt. The caller |
| 507 | // holds r.mu. |
| 508 | func (r *simRunner) liveOwnedLocked(s *simSnap, attempt string) []string { |
| 509 | var out []string |
| 510 | for _, vm := range s.vms { |
| 511 | if vm.State.Live() && r.ownerLocked(s, vm.Ref) == attempt { |
| 512 | out = append(out, fmt.Sprintf("%s %s", vm.Ref, vm.State)) |
| 513 | } |
| 514 | } |
| 515 | return out |
| 516 | } |
| 517 | |
| 518 | // checkOrphanStopLocked is I3, as the orphan stop is sent: the VM is no |
| 519 | // job's saved Ref and no waiting intent's VM, was recorded unmatched, and |
| 520 | // has had OrphanGrace of controller time since (by the store's record and |
| 521 | // by the simulation's own record of when the VM appeared), unless it was |
| 522 | // recorded before this process opened the store after a restart. |
| 523 | func (r *simRunner) checkOrphanStopLocked(ref isolatedjob.Ref) { |
| 524 | s, err := r.w.read() |
| 525 | if err != nil { |
| 526 | r.violate("I3: %v", err) |
| 527 | return |
| 528 | } |
| 529 | now := r.w.now() |
| 530 | if j := s.byRef[ref]; j != nil { |
| 531 | r.violate("I3: orphan stop of %s, the saved Ref of %s", ref, j.attempt) |
| 532 | } |
| 533 | if j := s.jobs[r.ownerLocked(s, ref)]; j != nil && j.state == JobWaiting { |
| 534 | r.violate("I3: orphan stop of %s, the VM of waiting intent %s", ref, j.attempt) |
| 535 | } |
| 536 | first, ok := s.unmatched[ref] |
| 537 | early := r.w.store.Restarted() && first < r.w.store.OpenedAt() |
| 538 | switch { |
| 539 | case !ok: |
| 540 | r.violate("I3: orphan stop of %s, which unmatched_vms does not hold", ref) |
| 541 | case now-first < T(OrphanGrace) && !early: |
| 542 | r.violate("I3: orphan stop of %s at %v, first seen at %v: grace not over", ref, simDur(now), simDur(first)) |
| 543 | } |
| 544 | if v := r.vms[ref]; v != nil && now-v.created < T(OrphanGrace) && !(r.w.restarted && v.created < r.w.openedAt) { |
| 545 | r.violate("I3: orphan stop of %s at %v; the VM appeared at %v", ref, simDur(now), simDur(v.created)) |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | // checkSuspendLocked is I5, as the provider Suspend is sent. The store |
| 550 | // must hold the job suspending in its current generation, acknowledged |
| 551 | // (pause_quiescent), not cancelled, its pause open; a Suspend call the |
| 552 | // simulation made must have named that stored generation; and the |
| 553 | // simulation's own history must agree: that generation is the last drain |
| 554 | // it saw accepted, at the stored pause start, and it saw it acknowledged in |
| 555 | // time. |
| 556 | func (r *simRunner) checkSuspendLocked(ref isolatedjob.Ref) { |
| 557 | s, err := r.w.read() |
| 558 | if err != nil { |
| 559 | r.violate("I5: %v", err) |
| 560 | return |
| 561 | } |
| 562 | j := s.byRef[ref] |
| 563 | if j == nil { |
| 564 | r.violate("I5: provider suspend of %s, which no job holds", ref) |
| 565 | return |
| 566 | } |
| 567 | if j.state != JobSuspending || !j.quiescent || j.cancelled || !j.pauseStarted.Valid { |
| 568 | r.violate("I5: provider suspend of %s (%s): stored state %s, generation %d, quiescent %v, cancelled %v, pause started %v", |
| 569 | ref, j.attempt, j.state, j.gen, j.quiescent, j.cancelled, j.pauseStarted) |
| 570 | } |
| 571 | if op := r.suspendOp; op != nil && op.attempt == j.attempt && op.gen != j.gen { |
| 572 | r.violate("I5: provider suspend of %s for named generation %d; the stored one is %d", ref, op.gen, j.gen) |
| 573 | } |
| 574 | if p := r.w.m.pause[j.attempt]; p == nil || !p.open || !p.acked || p.gen != j.gen || int64(p.drainedAt) != j.pauseStarted.Int64 { |
| 575 | r.violate("I5: provider suspend of %s (%s) at stored generation %d; the simulation's history is %+v", ref, j.attempt, j.gen, p) |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | // checkReplacementLocked is I6's launch half: a replacement's provider |
| 580 | // Launch needs the replaced attempt to hold stop proof and have no live VM. |
| 581 | func (r *simRunner) checkReplacementLocked(spec isolatedjob.LaunchSpec) { |
| 582 | s, err := r.w.read() |
| 583 | if err != nil { |
| 584 | r.violate("I6: %v", err) |
| 585 | return |
| 586 | } |
| 587 | j := s.byLaunch[bootLaunchID(spec.Bootstrap)] |
| 588 | if j == nil { |
| 589 | j = s.jobs[spec.AttemptID] |
| 590 | } |
| 591 | if j == nil || j.replaces == "" { |
| 592 | return |
| 593 | } |
| 594 | if old := s.jobs[j.replaces]; old == nil || old.proof == "" { |
| 595 | r.violate("I6: replacement %s launched before %s holds stop proof", j.attempt, j.replaces) |
| 596 | } |
| 597 | if live := r.liveOwnedLocked(s, j.replaces); len(live) > 0 { |
| 598 | r.violate("I6: replacement %s launched while %s still has %v", j.attempt, j.replaces, live) |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | // checkResumeLocked is I7's call half: a provider Resume needs a pending |
| 603 | // operation prepared at one above the job's epoch, which is not yet raised. |
| 604 | // It returns that operation's ID, the one later running evidence is for. |
| 605 | func (r *simRunner) checkResumeLocked(ref isolatedjob.Ref) string { |
| 606 | s, err := r.w.read() |
| 607 | if err != nil { |
| 608 | r.violate("I7: %v", err) |
| 609 | return "" |
| 610 | } |
| 611 | j := s.byRef[ref] |
| 612 | if j == nil { |
| 613 | r.violate("I7: provider resume of %s, which no job holds", ref) |
| 614 | return "" |
| 615 | } |
| 616 | var pending []simResumeOp |
| 617 | for _, o := range s.ops { |
| 618 | if o.attempt == j.attempt && o.status == opPending { |
| 619 | pending = append(pending, o) |
| 620 | } |
| 621 | } |
| 622 | switch { |
| 623 | case len(pending) != 1: |
| 624 | r.violate("I7: provider resume of %s (%s) with %d prepared operations", ref, j.attempt, len(pending)) |
| 625 | case pending[0].prepared != j.epoch+1: |
| 626 | r.violate("I7: provider resume of %s for operation %s prepared at epoch %d while the job's epoch is %d", |
| 627 | ref, pending[0].id, pending[0].prepared, j.epoch) |
| 628 | } |
| 629 | if len(pending) == 0 { |
| 630 | return "" |
| 631 | } |
| 632 | return pending[0].id |
| 633 | } |
| 634 | |
| 635 | // check runs every invariant on snapshot s and returns the violations, |
| 636 | // those the provider calls found first. M0 lines are the model's own |
| 637 | // consistency (the simulation's clock and deadlines agree with the store). |
| 638 | func (w *simWorld) check(s *simSnap) []string { |
| 639 | r := w.run |
| 640 | r.mu.Lock() |
| 641 | defer r.mu.Unlock() |
| 642 | bad := r.bad |
| 643 | r.bad = nil |
| 644 | add := func(format string, args ...any) { bad = append(bad, fmt.Sprintf(format, args...)) } |
| 645 | now := w.now() |
| 646 | if st := w.store.Clock().Now(); st != now { |
| 647 | add("M0: store clock reads %v, the model %v", simDur(st), simDur(now)) |
| 648 | } |
| 649 | for _, id := range s.order { |
| 650 | if _, ok := w.m.stopAt[id]; !ok { |
| 651 | w.m.stopAt[id] = w.opT + T(w.m.req[id].MaxLifetime-StopBefore) |
| 652 | if got := s.jobs[id].stopT; got != w.m.stopAt[id] { |
| 653 | add("M0: %s saved with stop time %v, the model expects %v", id, simDur(got), simDur(w.m.stopAt[id])) |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | // I1: at most one live VM per attempt. |
| 659 | live := map[string][]string{} |
| 660 | for _, vm := range s.vms { |
| 661 | if vm.State.Live() { |
| 662 | o := r.ownerLocked(s, vm.Ref) |
| 663 | live[o] = append(live[o], string(vm.Ref)) |
| 664 | } |
| 665 | } |
| 666 | for _, o := range sortedKeys(live) { |
| 667 | if len(live[o]) > 1 { |
| 668 | add("I1: attempt %s has %d live VMs: %v", o, len(live[o]), live[o]) |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | // I2: every VM is a saved Ref, matches a stored intent's attempt, or |
| 673 | // was planted. |
| 674 | for _, vm := range s.vms { |
| 675 | v := r.vms[vm.Ref] |
| 676 | switch { |
| 677 | case s.byRef[vm.Ref] != nil: |
| 678 | case v == nil: |
| 679 | add("I2: VM %s appeared without a Launch or a Plant", vm.Ref) |
| 680 | case v.planted, s.jobs[v.attempt] != nil: |
| 681 | default: |
| 682 | 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) |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | // I4, as ruling R24 words it: every live VM (stopping included) tied |
| 687 | // to a recorded attempt, by a saved Ref or by the fake's spec attempt |
| 688 | // ID, is live no later than max(stop_t, OpenedAt) + ReapInterval, plus |
| 689 | // one interval per pass of its current run of throttled Stops |
| 690 | // (creditLocked); a |
| 691 | // stopping VM also passes when its first effective Stop came within |
| 692 | // the bound in force then; a VM with no saved Ref gets OrphanGrace + |
| 693 | // ReapInterval more, and is exempt while R22 deferral applies, then |
| 694 | // bounded from one interval after it ends (simDeferral). R24a (d): a VM |
| 695 | // with no saved Ref also gets one interval for each pass since it |
| 696 | // appeared in which a List failed, as the reaper handles orphans only on |
| 697 | // complete Lists. And (e), after R20: after a restart, a job launched |
| 698 | // before the open gets one interval for each pass since the open in |
| 699 | // which a Get of its VM failed (at most RestartGetTries), as its stop |
| 700 | // time is re-based only on a Get that answers. And (f), carrying (c) |
| 701 | // over: a VM claimed late (a replay's Launch reply first carried its |
| 702 | // Ref, perhaps in the orphan recheck after the deadline step) is |
| 703 | // bounded no earlier than one interval after that reply. |
| 704 | deferral := false |
| 705 | for _, j := range s.jobs { |
| 706 | deferral = deferral || (j.state == JobWaiting && j.ref == "" && j.dispatched) |
| 707 | } |
| 708 | for _, vm := range s.vms { |
| 709 | j, v := s.byRef[vm.Ref], r.vms[vm.Ref] |
| 710 | noRef := j == nil |
| 711 | if noRef && v != nil { |
| 712 | j = s.jobs[v.attempt] |
| 713 | } |
| 714 | if j == nil || !vm.State.Live() { |
| 715 | continue |
| 716 | } |
| 717 | d := w.m.deferral[vm.Ref] |
| 718 | if noRef { |
| 719 | if d == nil { |
| 720 | d = &simDeferral{} |
| 721 | w.m.deferral[vm.Ref] = d |
| 722 | } |
| 723 | if d.observe(deferral, now, r.passNo); d.on { |
| 724 | continue |
| 725 | } |
| 726 | } |
| 727 | base := max(min(j.stopT, w.m.stopAt[j.attempt]), w.store.OpenedAt()) + T(ReapInterval) |
| 728 | if noRef { |
| 729 | base += T(OrphanGrace + ReapInterval) |
| 730 | for _, p := range r.listFail { |
| 731 | if v != nil && p >= v.pass { |
| 732 | base += T(ReapInterval) |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | if w.store.Restarted() && j.launchedT <= w.store.OpenedAt() { |
| 737 | n := 0 |
| 738 | for _, p := range r.getFail[vm.Ref] { |
| 739 | if p > r.openPass { |
| 740 | n++ |
| 741 | } |
| 742 | } |
| 743 | base += T(ReapInterval) * T(min(n, RestartGetTries)) |
| 744 | } |
| 745 | if v != nil && v.claimed > 0 { |
| 746 | base = max(base, v.claimed+T(ReapInterval)) |
| 747 | } |
| 748 | if d != nil { |
| 749 | if b, ok := d.bound(r.listFail); ok { |
| 750 | base = max(base, b) |
| 751 | } |
| 752 | } |
| 753 | credit := r.creditLocked(vm.Ref) |
| 754 | if now <= base+T(ReapInterval)*T(credit) { |
| 755 | continue |
| 756 | } |
| 757 | if st, ok := r.stoppedB[vm.Ref]; ok && vm.State == isolatedjob.StateStopping && st.at <= base+T(ReapInterval)*T(st.credit) { |
| 758 | continue |
| 759 | } |
| 760 | 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, |
| 761 | vm.State, simDur(now), simDur(j.stopT), simDur(base), credit, !noRef) |
| 762 | } |
| 763 | |
| 764 | // I5, the store against the simulation's history: a job's stored |
| 765 | // generation is the last drain the simulation saw accepted, started |
| 766 | // when it drained, and is acknowledged only if the simulation saw an |
| 767 | // acknowledgement of it in time. |
| 768 | for _, id := range s.order { |
| 769 | j, p := s.jobs[id], w.m.pause[id] |
| 770 | switch { |
| 771 | case p == nil && j.gen != 0: |
| 772 | add("I5: %s holds generation %d with no drain accepted", id, j.gen) |
| 773 | case p == nil: |
| 774 | case j.gen != p.gen: |
| 775 | add("I5: %s holds generation %d; the last drain accepted gave %d", id, j.gen, p.gen) |
| 776 | case j.pauseStarted.Valid && j.pauseStarted.Int64 != int64(p.drainedAt): |
| 777 | add("I5: %s pause started at %v; generation %d drained at %v", id, simDur(T(j.pauseStarted.Int64)), p.gen, simDur(p.drainedAt)) |
| 778 | case j.quiescent && !p.acked: |
| 779 | add("I5: %s generation %d is stored acknowledged; no acknowledgement of it came in time", id, j.gen) |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | // I6: proof only from a terminal state, and never while a VM of the |
| 784 | // attempt is live. |
| 785 | for _, id := range s.order { |
| 786 | j := s.jobs[id] |
| 787 | if j.proof == "" { |
| 788 | continue |
| 789 | } |
| 790 | var p hostedwire.StopProof |
| 791 | if err := json.Unmarshal([]byte(j.proof), &p); err != nil || !p.State.Terminal() { |
| 792 | add("I6: %s holds proof from state %q (%v)", id, p.State, err) |
| 793 | } |
| 794 | if l := r.liveOwnedLocked(s, id); len(l) > 0 { |
| 795 | add("I6: %s holds stop proof while %v", id, l) |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | // I7: the epoch is the number of done operations, each raised it by |
| 800 | // exactly one, a newly done one followed a running read after its last |
| 801 | // resume call, and done operations stay done with their epoch. |
| 802 | ops := map[string][]simResumeOp{} |
| 803 | done := map[[2]string]int64{} |
| 804 | for _, o := range s.ops { |
| 805 | ops[o.attempt] = append(ops[o.attempt], o) |
| 806 | if o.status == opDone { |
| 807 | done[[2]string{o.attempt, o.id}] = o.result.Int64 |
| 808 | } |
| 809 | } |
| 810 | for _, id := range s.order { |
| 811 | j := s.jobs[id] |
| 812 | n := int64(0) |
| 813 | for _, o := range ops[id] { |
| 814 | if o.status == opDone { |
| 815 | n++ |
| 816 | } |
| 817 | } |
| 818 | seen := map[int64]bool{} |
| 819 | for _, o := range ops[id] { |
| 820 | if o.status != opDone { |
| 821 | continue |
| 822 | } |
| 823 | // n done operations with distinct epochs in 1..n: each raised |
| 824 | // the epoch by one, once. |
| 825 | if !o.result.Valid || o.result.Int64 != o.prepared || o.prepared < 1 || o.prepared > n || seen[o.prepared] { |
| 826 | add("I7: %s operation %s done with epoch %v, prepared %d, of %d done", id, o.id, o.result, o.prepared, n) |
| 827 | } |
| 828 | seen[o.prepared] = true |
| 829 | key := [2]string{id, o.id} |
| 830 | if _, known := w.m.done[key]; !known { |
| 831 | if r.runningFor[j.ref] != o.id { |
| 832 | add("I7: %s operation %s committed with no running read of %s after a provider resume for it (evidence for %q)", |
| 833 | id, o.id, j.ref, r.runningFor[j.ref]) |
| 834 | } |
| 835 | delete(r.runningFor, j.ref) |
| 836 | w.m.done[key] = o.result.Int64 |
| 837 | w.closePause(id) |
| 838 | } |
| 839 | } |
| 840 | if j.epoch != n { |
| 841 | add("I7: %s has epoch %d after %d done resume operations", id, j.epoch, n) |
| 842 | } |
| 843 | } |
| 844 | for _, key := range sortedKeys(w.m.done) { |
| 845 | if e, ok := done[key]; !ok || e != w.m.done[key] { |
| 846 | add("I7: %s operation %s was done at epoch %d; now %v", key[0], key[1], w.m.done[key], e) |
| 847 | } |
| 848 | } |
| 849 | for _, x := range w.m.returned { |
| 850 | if e, ok := done[[2]string{x.attempt, x.op}]; !ok || e != x.epoch { |
| 851 | add("I7: Resume(%s, %s) returned epoch %d; the store holds %d (done %v)", x.attempt, x.op, x.epoch, e, ok) |
| 852 | } |
| 853 | } |
| 854 | w.m.returned = w.m.returned[:0] |
| 855 | return bad |
| 856 | } |
| 857 | |
| 858 | // sortedKeys returns m's keys in a fixed order, so reports are stable. |
| 859 | func sortedKeys[K comparable, V any](m map[K]V) []K { |
| 860 | out := slices.Collect(maps.Keys(m)) |
| 861 | slices.SortFunc(out, func(a, b K) int { return strings.Compare(fmt.Sprint(a), fmt.Sprint(b)) }) |
| 862 | return out |
| 863 | } |
| 864 | |
| 865 | // TestSimDeadlineCredits checks I4's two time credits directly, on the |
| 866 | // review's examples: a throttle run broken by a pass with no Stop gives no |
| 867 | // credit, and the bound after R22 deferral runs from the deferral's end. |
| 868 | func TestSimDeadlineCredits(t *testing.T) { |
| 869 | min := func(m int) T { return T(time.Duration(m) * time.Minute) } |
| 870 | // stop_t 10m, so the unextended bound is 11m. |
| 871 | for _, c := range []struct { |
| 872 | name string |
| 873 | throttled []int // minutes whose pass throttles the Stop |
| 874 | stopAt int // minute whose pass stops the VM |
| 875 | accepted bool |
| 876 | }{ |
| 877 | {"throttled at 10m, no Stop at 11m, stopped at 12m", []int{10}, 12, false}, |
| 878 | {"throttled at 10m and 11m, stopped at 12m", []int{10, 11}, 12, true}, |
| 879 | {"throttled at 10m, stopped at 11m", []int{10}, 11, true}, |
| 880 | } { |
| 881 | clk := isolatedjobtest.NewFakeClock(testWall) |
| 882 | r := newSimRunner(nil, &simWorld{clk: clk}) |
| 883 | for m := 10; m <= c.stopAt; m++ { |
| 884 | clk.AdvanceMono(time.Duration(min(m)) - clk.Mono()) |
| 885 | r.beginPass() |
| 886 | if slices.Contains(c.throttled, m) || m == c.stopAt { |
| 887 | r.noteStopLocked("vm-1", m != c.stopAt) |
| 888 | } |
| 889 | r.endPass() |
| 890 | } |
| 891 | st := r.stoppedB["vm-1"] |
| 892 | if got := st.at <= min(11)+T(ReapInterval)*T(st.credit); got != c.accepted { |
| 893 | t.Errorf("%s: stop at %v with credit %d accepted %v, want %v", c.name, simDur(st.at), st.credit, got, c.accepted) |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | // Deferred at 30m; the last waiting intent resolves in the 31m pass. |
| 898 | for _, c := range []struct { |
| 899 | name string |
| 900 | listFail []int // passes (numbered by minute) whose List failed |
| 901 | liveAt int |
| 902 | ok bool |
| 903 | }{ |
| 904 | {"incomplete List at 31m, stopped by the 32m pass", []int{31}, 32, true}, |
| 905 | {"complete Lists, still live at 33m", nil, 33, false}, |
| 906 | {"incomplete Lists at 31m and 32m, live at 33m", []int{31, 32}, 33, true}, |
| 907 | } { |
| 908 | d := &simDeferral{} |
| 909 | d.observe(true, min(30), 30) |
| 910 | d.observe(false, min(31), 31) |
| 911 | b, _ := d.bound(c.listFail) |
| 912 | if got := min(c.liveAt) <= b; got != c.ok { |
| 913 | t.Errorf("%s: live at %v within bound %v is %v, want %v", c.name, simDur(min(c.liveAt)), simDur(b), got, c.ok) |
| 914 | } |
| 915 | } |
| 916 | } |
| 917 | |