oficina / equipo Public

hostedctl: stop proof, unknown states and restart reconciliation

Get and Stop for the creating instance key only. Stop records the
request, then calls the provider's Stop and Get outside any
transaction; proof needs a terminal state or not-found after the
request, never stopping or unknown. A job with no VM ref is abandoned
and gets proof only from a complete List begun 2 minutes after the
request that shows no unlinked VM. Refresh reconciles every job with a
ref, sends a lost stop again, and after a restart re-bases each older
job once on the provider's age (only ever earlier) or stops it as
elapsed_unknown. Adds Store.OpenedAt and the mirrored VM job states.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9202c3d25edb25b79dad40c05c43e97d4ee7bcc4 parent f506a22
7 files changed, +1,386 −0
  • docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md +34 −0
  • internal/hostedctl/controller.go +1 −0
  • internal/hostedctl/refresh.go +299 −0
  • internal/hostedctl/states.go +12 −0
  • internal/hostedctl/stop.go +362 −0
  • internal/hostedctl/stop_test.go +673 −0
  • internal/hostedctl/store.go +5 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
index be232543..49464f74 100644
--- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
@@ -359,3 +359,37 @@ Review r1 findings 1, 2, 4 and 5 fixed; finding 3 settled by ruling R16 (limits
| X1 a repeat of a saved intent dispatches | `^TestConcurrentLaunchSameAttempt$` | `launch_test.go:471: view 0, returned while the provider call was held = {... State:starting VMRef:vm-0001 ...}, want waiting with no ref` | yes, passes |
| X2b replay alone sends changed bytes | `^TestCrashBetweenLaunchAndSave$` | `launch_test.go:514: Replay = hostedctl: launch att-1: provider refused: isolatedjob: conflict` | yes, passes |
| M2, M3, L1-L3, L4b, L5-L8, R1-R5b, R6c, X3, X4 | as in round 0 | each fails as before (now `launch_test.go:745`, `:740`, `:837`, `:851`, `:769`, `:379`); M2, L1 and L3 now end with the intent deferred as `waiting` by the dispatch gates, L8 as `abandoned` | yes, passes |
+
+## Task 11
+
+Get, Stop with stop proof, unknown states and Refresh with restart reconciliation: `internal/hostedctl/{stop.go,refresh.go,stop_test.go}`. Shared files, additive only: `states.go` (JobRunning, JobSuspending, JobSuspended, JobStopping, JobStopped), `store.go` (`(*Store) OpenedAt() T`), `controller.go` (one field, `rebased rebasedSet`). No schema change.
+
+- RED (stub with the names only): every new test failed on its assertion, for example `stop_test.go:158: Stop of a running VM = not built, want ErrStopPending (it is only stopping)`, `stop_test.go:436: Stop by another instance = not built, want ErrForbidden`, `stop_test.go:526: Refresh = not built`.
+- GREEN: `go test ./internal/hostedctl -run 'TestStop|TestUnknownState|TestLostStop|TestRestart' -count=1` ok 1.5 s; whole package `go test ./internal/hostedctl -count=1` ok 3.4 s on f506a22a; the new tests once under `-race`: ok.
+- Ruling R1: `TestRestartDowntimeExceedsWallDelta` asserts the job halves only; the orphan-grace clause lands with Task 13.
+- Every command below is `go test ./internal/hostedctl -run '<test>' -count=1`; every row was restored and its test passed again.
+
+| Mutation | Test | Observed failure | Restored |
+| --- | --- | --- | --- |
+| M1 accept `stopping` as proof (Stop) | `^TestStopProofNeedsTerminalState$` | `stop_test.go:186: Stop while the VM is stopping = <nil>, want ErrStopPending` | yes, passes |
+| M2a accept `unknown` as proof (Stop) | `^TestUnknownStateIsNeverProof$` | `stop_test.go:238: Stop with the provider state unknown = <nil>, want ErrStateUnknown` | yes, passes |
+| M2b accept `unknown` as proof (Refresh) | `^TestUnknownStateIsNeverProof$` | `stop_test.go:253: Refresh with an unknown state: state "stopped" (was "starting"), proof {... "state":"unknown" ...}; want it left alone` | yes, passes |
+| M3 `max` instead of `min` when re-basing | `^TestRestartUsesProviderAge$` | `stop_test.go:531: after Refresh: launched 60000000000 deadline 7260000000000 ...; want -2340000000000 4860000000000 ...` (wall back) and `launched 16260000000000 ...; want 60000000000 ...` (wall ahead) | yes, passes |
+| M4 `stop_t` not recomputed | `^TestRestartUsesProviderAge$` | `stop_test.go:531: after Refresh: launched -2340000000000 deadline 4860000000000 drain 2160000000000 stop 6660000000000; want ... stop 4260000000000` | yes, passes |
+| M5 trust the wall delta for a job without age (mark settled, no stop) | `^TestRestartDowntimeExceedsWallDelta$` | `stop_test.go:592: att-1 with no age: requested {0 false} reason { false}; want stopped with elapsed_unknown` | yes, passes |
+| M6 keep jobs whose elapsed time is unknown (`stopElapsedUnknown` returns at once) | `^TestRestartStopsWhenElapsedUnknown$` | `stop_test.go:619: att-1 after Refresh: requested {0 false} reason { false} state "starting"; want a stop for elapsed_unknown, stopping` | yes, passes |
+| M7 creator check dropped (Stop) | `^TestStopRoles$` | `stop_test.go:437: Stop by another instance = hostedctl: stop asked for; ... VM vm-0001 is stopping, want ErrForbidden` | yes, passes |
+| M7b creator check dropped (Get) | `^TestStopRoles$` | `stop_test.go:454: Get by another instance = <nil>, want ErrForbidden` | yes, passes |
+| M8 role check dropped (Stop) | `^TestStopRoles$` | `stop_test.go:437: Stop by an operator key with the creator's id = ... VM vm-0001 is stopping, want ErrForbidden` | yes, passes |
+| M9 Ref-less proof ignores unlinked live VMs | `^TestStopIntentWithoutRef$` | `stop_test.go:365: proof {"attempt_id":"att-1","vm_ref":"","state":"stopped",...} while an unlinked VM is live` | yes, passes |
+| M10 Ref-less proof without the 2-minute wait | `^TestStopIntentWithoutRef$` | `stop_test.go:411: proof {... "observed_at_ns":119999999999} from a list started under 2 minutes after the request` | yes, passes |
+| M10b 2-minute wait measured from the list's end | `^TestStopIntentWithoutRef$` | same line as M10 | yes, passes |
+| M11 Ref-less proof from an incomplete list | `^TestStopIntentWithoutRef$` | `stop_test.go:381: proof {...} from an incomplete list` | yes, passes |
+| M12 Ref-less check counts only live (not unknown) VMs | `^TestStopIntentWithoutRef$` | survives: the fake's List never reports `unknown` (FaultUnknownState is Get-only) | n/a |
+| M13 re-base not once per process | `^TestRestartStopsWhenElapsedUnknown$` | `stop_test.go:633: provider stops = [vm-0001 vm-0001 vm-0002], want only vm-0001` | yes, passes |
+| M14 pre-restart boundary `<` OpenedAt | `^TestRestartJobAtOpenTime$` | `stop_test.go:668: job launched at OpenedAt with no age: reason { false}, want elapsed_unknown` | yes, passes |
+| M15 Refresh does not send the stop again | `^TestLostStopReplyRetries$` | `stop_test.go:306: provider stops after Refresh = [vm-0001], want a second one` | yes, passes |
+| M16 gone VM is not proof | `^TestStopOfGoneVMSucceeds$` | `stop_test.go:331: Stop of a VM the provider no longer holds = (..., hostedctl: read VM vm-0001 of att-1 after stop: isolatedjob: not found: vm-0001), want {... State:stopped ...}` | yes, passes |
+| M17 a VM that ended while down gets no reason `ended` | `^TestRestartFindsVMGone$` | `stop_test.go:496: att-a after Refresh: state "stopped" reason { false} requested {0 false}; want stopped, ended, no request` | yes, passes |
+| M18 Stop does not abandon a waiting intent | `^TestStopIntentWithoutRef$` | `stop_test.go:354: after Stop: state "waiting" requested {60000000000 true} proof { false}; want abandoned at 60000000000, no proof` | yes, passes |
+| M19 saving proof rewrites `stop_t` | `^TestStopProofNeedsTerminalState$` | `stop_test.go:211: after proof: state "stopped" reason {task done true} stop_t 0 ...; want ... times 6600000000000 7200000000000 unchanged` | yes, passes |
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index cdad2c8f..73dbf75e 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -45,6 +45,7 @@ type Controller struct {
auditor isolatedjob.NetworkAuditor
alerter Alerter
audit auditState // the last network audit result (audit.go)
+ rebased rebasedSet // jobs re-based after a restart (refresh.go)
}
// New builds a controller. It refuses a nil dependency, including a nil
diff --git a/internal/hostedctl/refresh.go b/internal/hostedctl/refresh.go
new file mode 100644
index 00000000..1c47d654
--- /dev/null
+++ b/internal/hostedctl/refresh.go
@@ -0,0 +1,299 @@
+package hostedctl
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// ReflessProofDelay is how long, in controller time, after the stop request
+// a List must start before it can prove that a job with no VM Ref has no VM.
+// A launch whose reply was lost may still be landing until then.
+const ReflessProofDelay = 2 * time.Minute
+
+// rebasedSet holds the jobs whose elapsed time Refresh has settled since this
+// controller started: re-based on the provider's age, or stopped because the
+// provider gave none. Each pre-restart job is settled once per process.
+type rebasedSet struct {
+ mu sync.Mutex
+ done map[string]bool
+}
+
+func (s *rebasedSet) has(attempt string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.done[attempt]
+}
+
+func (s *rebasedSet) add(attempt string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.done == nil {
+ s.done = map[string]bool{}
+ }
+ s.done[attempt] = true
+}
+
+// Refresh reconciles the job table with the provider. One failing job does
+// not stop the others; Refresh returns their errors joined. No transaction
+// is held across a provider call.
+//
+// Every job with a VM Ref and no proof is read with Runner.Get:
+//
+// - a terminal state, or isolatedjob.ErrNotFound, is proof and is saved.
+// A job with no stop request ended on its own and gets the stop reason
+// "ended", so replacements may go ahead;
+// - after a restart, a job launched at or before Store.OpenedAt has an
+// untrusted elapsed time (the wall delta Open used says nothing about
+// the real downtime). Once per process, with a provider age, its
+// launched_t becomes min(launched_t, T before the Get minus the age) and
+// its deadline, drain and stop times are recomputed with Deadlines, each
+// only ever moved earlier. With no age, the controller stops it with the
+// reason "elapsed_unknown";
+// - an unknown state is left as it is;
+// - a live state is saved as the job's state, and a job with a stop
+// request whose VM is not yet stopping gets the provider stop again.
+//
+// Then, when a job with no VM Ref is abandoned and has a stop request, one
+// List: if it is complete, started at least ReflessProofDelay after that
+// request, and shows no VM that is not terminal and not a saved Ref of some
+// job, the job gets proof with an empty VMRef and state stopped. Until then
+// it stays pending; the orphan reaper stops any such VM.
+func (c *Controller) Refresh(ctx context.Context) error {
+ var withRef []string
+ refless := false
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ withRef, refless = withRef[:0], false
+ rows, err := tx.QueryContext(ctx, `SELECT attempt_id, vm_ref IS NOT NULL FROM jobs
+ WHERE stop_proof_json IS NULL
+ AND (vm_ref IS NOT NULL OR (state = ? AND stop_requested_t IS NOT NULL))
+ ORDER BY launched_t, attempt_id`, JobAbandoned)
+ if err != nil {
+ return fmt.Errorf("hostedctl: list jobs to refresh: %w", err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ var hasRef bool
+ if err := rows.Scan(&id, &hasRef); err != nil {
+ return fmt.Errorf("hostedctl: list jobs to refresh: %w", err)
+ }
+ if hasRef {
+ withRef = append(withRef, id)
+ } else {
+ refless = true
+ }
+ }
+ return rows.Err()
+ })
+ if err != nil {
+ return err
+ }
+ var errs []error
+ for _, id := range withRef {
+ if err := ctx.Err(); err != nil {
+ return errors.Join(append(errs, err)...)
+ }
+ if err := c.refreshOne(ctx, id); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ if refless {
+ if err := c.proveRefless(ctx); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// refreshOne reconciles one job with a VM Ref; see Refresh.
+func (c *Controller) refreshOne(ctx context.Context, attempt string) error {
+ var j jobRow
+ var reason sql.NullString
+ found := false
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ var err error
+ if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found {
+ return err
+ }
+ return tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&reason)
+ })
+ if err != nil {
+ return err
+ }
+ if !found || !j.ref.Valid || j.stopProof.Valid {
+ return nil
+ }
+ ref := isolatedjob.Ref(j.ref.String)
+ untrusted := c.store.Restarted() && T(j.launchedT) <= c.store.OpenedAt() && !c.rebased.has(attempt)
+
+ before := c.store.Clock().Now()
+ job, gerr := c.runner.Get(ctx, ref)
+ at := c.store.Clock().Now()
+ rec := context.WithoutCancel(ctx)
+ switch {
+ case errors.Is(gerr, isolatedjob.ErrNotFound):
+ _, err := c.recordProof(rec, "", attempt, StopProof{AttemptID: attempt, VMRef: ref,
+ State: isolatedjob.StateStopped, ObservedAt: at}, "refresh: provider holds no such VM")
+ return err
+ case gerr != nil:
+ return fmt.Errorf("hostedctl: refresh %s: read VM %s: %w", attempt, ref, gerr)
+ case job.State.Terminal():
+ _, err := c.recordProof(rec, "", attempt, StopProof{AttemptID: attempt, VMRef: ref,
+ State: job.State, ObservedAt: at}, "refresh: provider reports the VM "+string(job.State))
+ return err
+ }
+
+ if untrusted {
+ if !job.AgeKnown || job.ProviderAge < 0 {
+ return c.stopElapsedUnknown(ctx, attempt)
+ }
+ if err := c.rebase(rec, attempt, before-T(job.ProviderAge), job.ProviderAge); err != nil {
+ return err
+ }
+ c.rebased.add(attempt)
+ }
+ if !job.State.Live() {
+ return nil // unknown: neither proof nor a state worth saving
+ }
+ if err := c.mirrorState(rec, attempt, job.State); err != nil {
+ return err
+ }
+ if j.stopRequested.Valid && job.State != isolatedjob.StateStopping {
+ if perr := c.runner.Stop(ctx, ref, reason.String); perr != nil && !errors.Is(perr, isolatedjob.ErrNotFound) {
+ r := stopReq{attempt: attempt, account: j.account, task: j.task, ref: ref}
+ aerr := c.auditStop(rec, "", r, actionStopFailed, "refresh: provider stop call failed; it is sent again on the next refresh")
+ return errors.Join(fmt.Errorf("hostedctl: refresh %s: stop VM %s: %w", attempt, ref, perr), aerr)
+ }
+ }
+ return nil
+}
+
+// stopElapsedUnknown is the controller's own stop of a pre-restart job the
+// provider gave no age for. Once the request is recorded the job counts as
+// settled; a pending or unknown result is left for the next Refresh.
+func (c *Controller) stopElapsedUnknown(ctx context.Context, attempt string) error {
+ r, err := c.requestStop(context.WithoutCancel(ctx), "", attempt, reasonElapsedUnknown, false)
+ if err != nil {
+ return err
+ }
+ c.rebased.add(attempt)
+ if r.proof != nil {
+ return nil
+ }
+ _, err = c.driveStop(ctx, "", r)
+ if errors.Is(err, ErrStopPending) || errors.Is(err, ErrStateUnknown) {
+ return nil
+ }
+ return err
+}
+
+// rebase moves a pre-restart job's launch time back to cand when cand is
+// earlier, and its deadline, drain and stop times to those Deadlines gives
+// for it, each only when earlier than the stored one. It is audited even
+// when nothing moves.
+func (c *Controller) rebase(ctx context.Context, attempt string, cand T, age time.Duration) error {
+ return c.store.Tx(ctx, func(tx *sql.Tx) error {
+ j, found, err := loadJob(ctx, tx, attempt)
+ if err != nil || !found || j.stopProof.Valid {
+ return err
+ }
+ spec, err := decodeSpec(j.specJSON, attempt)
+ if err != nil {
+ return err
+ }
+ launched := min(T(j.launchedT), cand)
+ deadline, drain, stop := Deadlines(launched, spec.MaxLifetime)
+ deadline, drain, stop = min(deadline, T(j.deadlineT)), min(drain, T(j.drainT)), min(stop, T(j.stopT))
+ if _, err := tx.ExecContext(ctx, `UPDATE jobs SET launched_t = ?, deadline_t = ?, drain_t = ?, stop_t = ?,
+ revision = revision + 1 WHERE attempt_id = ?`,
+ int64(launched), int64(deadline), int64(drain), int64(stop), attempt); err != nil {
+ return fmt.Errorf("hostedctl: re-base %s: %w", attempt, err)
+ }
+ return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionRestartRebased,
+ Reason: fmt.Sprintf("after a restart the provider reports age %v; launched moved back by %v, stop time by %v",
+ age, time.Duration(T(j.launchedT)-launched), time.Duration(T(j.stopT)-stop)),
+ At: c.store.Clock().Now()})
+ })
+}
+
+// proveRefless issues proof for abandoned, stop-requested jobs with no VM
+// Ref; see Refresh. An incomplete List proves nothing and is not an error.
+func (c *Controller) proveRefless(ctx context.Context) error {
+ start := c.store.Clock().Now()
+ vms, err := c.runner.List(ctx)
+ at := c.store.Clock().Now()
+ if errors.Is(err, isolatedjob.ErrIncomplete) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("hostedctl: list VMs for stop proof: %w", err)
+ }
+ ctx = context.WithoutCancel(ctx) // record what the list showed even if the caller has gone
+ return c.store.Tx(ctx, func(tx *sql.Tx) error {
+ saved := map[isolatedjob.Ref]bool{}
+ rows, err := tx.QueryContext(ctx, `SELECT vm_ref FROM jobs WHERE vm_ref IS NOT NULL`)
+ if err != nil {
+ return fmt.Errorf("hostedctl: read saved VM refs: %w", err)
+ }
+ for rows.Next() {
+ var ref string
+ if err := rows.Scan(&ref); err != nil {
+ _ = rows.Close()
+ return fmt.Errorf("hostedctl: read saved VM refs: %w", err)
+ }
+ saved[isolatedjob.Ref(ref)] = true
+ }
+ if err := errors.Join(rows.Err(), rows.Close()); err != nil {
+ return fmt.Errorf("hostedctl: read saved VM refs: %w", err)
+ }
+ for _, vm := range vms {
+ // An unknown state may be a live VM, so only terminal ones pass.
+ if !vm.State.Terminal() && !saved[vm.Ref] {
+ return nil
+ }
+ }
+
+ var ids []string
+ rows, err = tx.QueryContext(ctx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NULL AND state = ?
+ AND stop_requested_t IS NOT NULL AND stop_proof_json IS NULL ORDER BY attempt_id`, JobAbandoned)
+ if err != nil {
+ return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err)
+ }
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ _ = rows.Close()
+ return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err)
+ }
+ ids = append(ids, id)
+ }
+ if err := errors.Join(rows.Err(), rows.Close()); err != nil {
+ return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err)
+ }
+ for _, id := range ids {
+ j, found, err := loadJob(ctx, tx, id)
+ if err != nil {
+ return err
+ }
+ if !found || j.ref.Valid || !j.stopRequested.Valid || j.stopProof.Valid {
+ continue
+ }
+ if start-T(j.stopRequested.Int64) < T(ReflessProofDelay) {
+ continue
+ }
+ p := StopProof{AttemptID: id, State: isolatedjob.StateStopped, ObservedAt: at}
+ if err := writeProof(ctx, tx, "", j, p, fmt.Sprintf(
+ "a complete list begun %v after the stop request shows no VM outside the job table",
+ time.Duration(start-T(j.stopRequested.Int64)))); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
diff --git a/internal/hostedctl/states.go b/internal/hostedctl/states.go
index 39aadaad..fdaecc37 100644
--- a/internal/hostedctl/states.go
+++ b/internal/hostedctl/states.go
@@ -14,3 +14,15 @@ const (
// reaper.
JobAbandoned = "abandoned"
)
+
+// Job states that mirror the VM's live state, as Stop and Refresh last read
+// it from the provider (stop.go, refresh.go), and the one terminal state.
+const (
+ JobRunning = "running"
+ JobSuspending = "suspending"
+ JobSuspended = "suspended"
+ JobStopping = "stopping"
+ // JobStopped: the job carries stop proof (stop_proof_json). Nothing
+ // moves it out of this state.
+ JobStopped = "stopped"
+)
diff --git a/internal/hostedctl/stop.go b/internal/hostedctl/stop.go
new file mode 100644
index 00000000..14e972b9
--- /dev/null
+++ b/internal/hostedctl/stop.go
@@ -0,0 +1,362 @@
+package hostedctl
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+var (
+ // ErrStopPending: the stop is recorded but the VM is not proven stopped
+ // yet: it is still live, or the job has no VM Ref and the provider has
+ // not yet been seen to hold no VM for it. Ask again later.
+ ErrStopPending = errors.New("hostedctl: stop asked for; the VM is not proven stopped yet")
+ // ErrStateUnknown: the provider reported a state this package does not
+ // know. It is never proof that the VM has stopped.
+ ErrStateUnknown = errors.New("hostedctl: the provider reports an unknown VM state; no stop proof")
+)
+
+// Stop reasons the controller writes itself.
+const (
+ // reasonElapsedUnknown: after a restart the provider gave no age for the
+ // VM, so how long it has lived is unknown and the controller stops it.
+ reasonElapsedUnknown = "elapsed_unknown"
+ // reasonEnded: the VM ended, or the provider forgot it, with no stop
+ // asked for.
+ reasonEnded = "ended"
+)
+
+// Audit actions written by Get, Stop and Refresh.
+const (
+ actionGetRefused = "get_refused"
+ actionStopRefused = "stop_refused"
+ actionStopRequested = "stop_requested"
+ actionStopRepeated = "stop_repeated"
+ actionStopFailed = "stop_failed"
+ actionStopStateUnknown = "stop_state_unknown"
+ actionStopProven = "stop_proven"
+ actionRestartRebased = "restart_rebased"
+)
+
+// StopProof says the provider reported the job's VM terminal, or held no
+// such VM once the stop was asked for. It gates replacement attempts.
+// VMRef is empty for a job that never had a Ref, and State is then
+// isolatedjob.StateStopped. ObservedAt is controller time.
+type StopProof struct {
+ AttemptID string
+ VMRef isolatedjob.Ref
+ State isolatedjob.State
+ ObservedAt T
+}
+
+func (p StopProof) wire() hostedwire.StopProof {
+ return hostedwire.StopProof{AttemptID: p.AttemptID, VMRef: p.VMRef, State: p.State, ObservedAt: time.Duration(p.ObservedAt)}
+}
+
+// decodeProof reads a stored jobs.stop_proof_json and checks it is for attempt.
+func decodeProof(text, attempt string) (StopProof, error) {
+ var w hostedwire.StopProof
+ if err := json.Unmarshal([]byte(text), &w); err != nil {
+ return StopProof{}, fmt.Errorf("hostedctl: stored stop proof for %s is unreadable: %w", attempt, err)
+ }
+ if w.AttemptID != attempt {
+ return StopProof{}, fmt.Errorf("hostedctl: stored stop proof for %s names attempt %s", attempt, w.AttemptID)
+ }
+ return StopProof{AttemptID: w.AttemptID, VMRef: w.VMRef, State: w.State, ObservedAt: T(w.ObservedAt)}, nil
+}
+
+// notCreator is the refusal for a key that did not launch attempt. An
+// unknown attempt gets the same text, so a refusal never tells a key whether
+// another key's attempt exists.
+func notCreator(attempt string) error {
+ return fmt.Errorf("%w: %s is not an attempt of this key", ErrForbidden, attempt)
+}
+
+// Get returns attempt's job as the store holds it. Only the instance key
+// that launched it may read it; anyone else, and any unknown attempt, gets
+// ErrForbidden and an audit row. Get makes no provider call.
+func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID string) (JobView, error) {
+ var view JobView
+ var refusal error
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ view, refusal = JobView{}, nil
+ now := c.store.Clock().Now()
+ a := Audit{Actor: by, Action: actionGetRefused, At: now}
+ if !printableASCII(attemptID, maxNameLen) {
+ refusal = fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)
+ a.Reason = refusal.Error()
+ return appendAudit(tx, a)
+ }
+ a.Attempt = attemptID
+ j, found, err := loadJob(ctx, tx, attemptID)
+ if err != nil {
+ return err
+ }
+ if by == "" || !found || j.actor != string(by) {
+ refusal = notCreator(attemptID)
+ if found {
+ a.Account, a.Task = j.account, j.task
+ }
+ a.Reason = refusal.Error()
+ return appendAudit(tx, a)
+ }
+ view = j.view(now)
+ return nil
+ })
+ if err != nil {
+ return JobView{}, err
+ }
+ if refusal != nil {
+ return JobView{}, refusal
+ }
+ return view, nil
+}
+
+// Stop asks for attempt's VM to stop and returns proof once it has.
+//
+// Only an instance key (RoleInstance) that launched attempt may stop it;
+// anyone else, an unknown attempt, or a malformed attempt ID or reason
+// (1 to 128 printable ASCII characters) gets an error and an audit row and
+// changes nothing. The controller's own stops do not come through here.
+//
+// In order: one transaction records stop_requested_t and stop_reason, unless
+// a stop was already asked for (the first reason is kept), and audits it. A
+// job that already holds proof returns it with no provider call. A job with
+// no VM Ref yet is marked JobAbandoned, so Replay never launches it, and
+// gets ErrStopPending: a lost launch reply may have made a VM the table does
+// not link, so Refresh issues its proof only once a complete List shows no
+// such VM. Otherwise, outside any transaction, Runner.Stop and then
+// Runner.Get:
+//
+// - a terminal state, or isolatedjob.ErrNotFound from Get, is proof: it
+// is saved with state JobStopped in one transaction and returned;
+// - a live state (stopping included) gives ErrStopPending;
+// - an unknown state gives ErrStateUnknown;
+// - an error from Runner.Stop (a lost reply, a throttle) is returned. The
+// provider's Stop is idempotent, so the next Stop, or the next Refresh,
+// sends it again.
+//
+// stop_t is never changed.
+func (c *Controller) Stop(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, reason string) (StopProof, error) {
+ switch {
+ case by == "" || key.Role != hostedwire.RoleInstance:
+ return StopProof{}, c.refuseStop(ctx, by, attemptID, fmt.Errorf("%w: stop needs the instance key that launched the attempt", ErrForbidden))
+ case !printableASCII(attemptID, maxNameLen):
+ return StopProof{}, c.refuseStop(ctx, by, "", fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen))
+ case !printableASCII(reason, maxNameLen):
+ return StopProof{}, c.refuseStop(ctx, by, attemptID, fmt.Errorf("%w: stop reason must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen))
+ }
+ r, err := c.requestStop(ctx, by, attemptID, reason, true)
+ if err != nil {
+ return StopProof{}, err
+ }
+ if r.proof != nil {
+ return *r.proof, nil
+ }
+ if r.ref == "" {
+ return StopProof{}, fmt.Errorf("%w: %s has no VM ref yet; proof waits for a complete list showing no unlinked VM", ErrStopPending, attemptID)
+ }
+ return c.driveStop(ctx, by, r)
+}
+
+// refuseStop audits a refusal that came before any job was read, in a short
+// transaction of its own, and returns err.
+func (c *Controller) refuseStop(ctx context.Context, by hostedwire.KeyID, attempt string, err error) error {
+ aerr := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: actionStopRefused,
+ Reason: err.Error(), At: c.store.Clock().Now()})
+ })
+ return errors.Join(err, aerr)
+}
+
+// stopReq is what requestStop read and recorded.
+type stopReq struct {
+ attempt, account, task string
+ ref isolatedjob.Ref // empty when the job has no VM Ref
+ reason string // the stored reason, sent to the provider
+ proof *StopProof // the stored proof, when there is one
+}
+
+// requestStop is Stop's first transaction, shared with the controller's own
+// stops (actor empty, creatorOnly false). It records the stop request and,
+// for a job with no Ref still waiting, abandons the intent.
+func (c *Controller) requestStop(ctx context.Context, actor hostedwire.KeyID, attempt, reason string, creatorOnly bool) (stopReq, error) {
+ var r stopReq
+ var refusal error
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ r, refusal = stopReq{}, nil
+ now := c.store.Clock().Now()
+ j, found, err := loadJob(ctx, tx, attempt)
+ if err != nil {
+ return err
+ }
+ a := Audit{Actor: actor, Attempt: attempt, At: now}
+ if found {
+ a.Account, a.Task = j.account, j.task
+ }
+ switch {
+ case !found && !creatorOnly:
+ return fmt.Errorf("hostedctl: stop %s: job is missing", attempt)
+ case !found || (creatorOnly && j.actor != string(actor)):
+ refusal = notCreator(attempt)
+ a.Action, a.Reason = actionStopRefused, refusal.Error()
+ return appendAudit(tx, a)
+ }
+ r = stopReq{attempt: attempt, account: j.account, task: j.task, ref: isolatedjob.Ref(j.ref.String)}
+ if j.stopProof.Valid {
+ p, err := decodeProof(j.stopProof.String, attempt)
+ r.proof = &p
+ return err
+ }
+ var stored sql.NullString
+ if err := tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&stored); err != nil {
+ return fmt.Errorf("hostedctl: read stop reason of %s: %w", attempt, err)
+ }
+ state := j.state
+ if !j.ref.Valid && state == JobWaiting {
+ state = JobAbandoned
+ }
+ r.reason = reason
+ if stored.Valid {
+ r.reason = stored.String
+ }
+ if j.stopRequested.Valid && state == j.state {
+ a.Action, a.Reason = actionStopRepeated, "stop asked for again: "+reason
+ return appendAudit(tx, a)
+ }
+ res, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_requested_t = coalesce(stop_requested_t, ?),
+ stop_reason = coalesce(stop_reason, ?), state = ?, revision = revision + 1
+ WHERE attempt_id = ? AND stop_proof_json IS NULL`, int64(now), reason, state, attempt)
+ if err != nil {
+ return fmt.Errorf("hostedctl: record stop request for %s: %w", attempt, err)
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return fmt.Errorf("hostedctl: record stop request for %s: %d rows (%v)", attempt, n, err)
+ }
+ a.Action, a.Reason = actionStopRequested, "stop asked for: "+reason
+ if state == JobAbandoned && j.state != JobAbandoned {
+ a.Reason += "; intent abandoned before any VM ref was saved"
+ }
+ return appendAudit(tx, a)
+ })
+ if err != nil {
+ return stopReq{}, err
+ }
+ if refusal != nil {
+ return stopReq{}, refusal
+ }
+ return r, nil
+}
+
+// driveStop sends the provider stop for a recorded request and then reads
+// the VM, outside any transaction. A failed stop call is audited, with a
+// fixed reason, and returned.
+func (c *Controller) driveStop(ctx context.Context, actor hostedwire.KeyID, r stopReq) (StopProof, error) {
+ if perr := c.runner.Stop(ctx, r.ref, r.reason); perr != nil && !errors.Is(perr, isolatedjob.ErrNotFound) {
+ aerr := c.auditStop(context.WithoutCancel(ctx), actor, r, actionStopFailed,
+ "provider stop call failed; it is sent again on the next stop or refresh")
+ return StopProof{}, errors.Join(fmt.Errorf("hostedctl: stop %s: %w", r.attempt, perr), aerr)
+ }
+ job, gerr := c.runner.Get(ctx, r.ref)
+ at := c.store.Clock().Now()
+ // Record what the provider said even if the caller has gone.
+ rec := context.WithoutCancel(ctx)
+ switch {
+ case errors.Is(gerr, isolatedjob.ErrNotFound):
+ return c.recordProof(rec, actor, r.attempt, StopProof{AttemptID: r.attempt, VMRef: r.ref,
+ State: isolatedjob.StateStopped, ObservedAt: at}, "provider holds no such VM after the stop request")
+ case gerr != nil:
+ return StopProof{}, fmt.Errorf("hostedctl: read VM %s of %s after stop: %w", r.ref, r.attempt, gerr)
+ case job.State.Terminal():
+ return c.recordProof(rec, actor, r.attempt, StopProof{AttemptID: r.attempt, VMRef: r.ref,
+ State: job.State, ObservedAt: at}, "provider reports the VM "+string(job.State))
+ case job.State.Live():
+ if err := c.mirrorState(rec, r.attempt, job.State); err != nil {
+ return StopProof{}, err
+ }
+ return StopProof{}, fmt.Errorf("%w: VM %s is %s", ErrStopPending, r.ref, job.State)
+ }
+ aerr := c.auditStop(rec, actor, r, actionStopStateUnknown, "provider state unknown; no proof")
+ return StopProof{}, errors.Join(fmt.Errorf("%w: VM %s of %s", ErrStateUnknown, r.ref, r.attempt), aerr)
+}
+
+// auditStop writes one audit row about r in a short transaction.
+func (c *Controller) auditStop(ctx context.Context, actor hostedwire.KeyID, r stopReq, action, reason string) error {
+ return c.store.Tx(ctx, func(tx *sql.Tx) error {
+ return appendAudit(tx, Audit{Actor: actor, Account: r.account, Task: r.task, Attempt: r.attempt,
+ Action: action, Reason: reason, At: c.store.Clock().Now()})
+ })
+}
+
+// recordProof saves p for a job with a VM Ref in one transaction, with the
+// job's state set to JobStopped, and returns it. A job that already holds
+// proof keeps it and returns that one. A job with no stop request ended on
+// its own: its stop_reason becomes reasonEnded, so replacements may go
+// ahead.
+func (c *Controller) recordProof(ctx context.Context, actor hostedwire.KeyID, attempt string, p StopProof, why string) (StopProof, error) {
+ out := p
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ out = p
+ j, found, err := loadJob(ctx, tx, attempt)
+ if err != nil {
+ return err
+ }
+ switch {
+ case !found:
+ return fmt.Errorf("hostedctl: stop proof for %s: job is missing", attempt)
+ case j.stopProof.Valid:
+ out, err = decodeProof(j.stopProof.String, attempt)
+ return err
+ case !j.ref.Valid || isolatedjob.Ref(j.ref.String) != p.VMRef:
+ return fmt.Errorf("hostedctl: stop proof for %s names VM %s, the job holds %q", attempt, p.VMRef, j.ref.String)
+ }
+ return writeProof(ctx, tx, actor, j, p, why)
+ })
+ if err != nil {
+ return StopProof{}, err
+ }
+ return out, nil
+}
+
+// writeProof saves p on j's row inside tx and audits it. j holds no proof.
+func writeProof(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRow, p StopProof, why string) error {
+ text, err := json.Marshal(p.wire())
+ if err != nil {
+ return fmt.Errorf("hostedctl: encode stop proof: %w", err)
+ }
+ ended := !j.stopRequested.Valid
+ res, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_proof_json = ?, state = ?,
+ stop_reason = CASE WHEN ? THEN coalesce(stop_reason, ?) ELSE stop_reason END, revision = revision + 1
+ WHERE attempt_id = ? AND stop_proof_json IS NULL`, string(text), JobStopped, ended, reasonEnded, j.attempt)
+ if err != nil {
+ return fmt.Errorf("hostedctl: save stop proof for %s: %w", j.attempt, err)
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return fmt.Errorf("hostedctl: save stop proof for %s: %d rows (%v)", j.attempt, n, err)
+ }
+ if ended {
+ why += "; no stop was asked for, so it ended on its own"
+ }
+ return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt,
+ Action: actionStopProven, Reason: why, At: p.ObservedAt})
+}
+
+// mirrorState saves a live VM state the provider reported as the job's
+// state, unless the job holds proof.
+func (c *Controller) mirrorState(ctx context.Context, attempt string, st isolatedjob.State) error {
+ return c.store.Tx(ctx, func(tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1
+ WHERE attempt_id = ? AND vm_ref IS NOT NULL AND stop_proof_json IS NULL AND state <> ?`,
+ string(st), attempt, string(st))
+ if err != nil {
+ return fmt.Errorf("hostedctl: save state of %s: %w", attempt, err)
+ }
+ return nil
+ })
+}
diff --git a/internal/hostedctl/stop_test.go b/internal/hostedctl/stop_test.go
new file mode 100644
index 00000000..7fccc5ae
--- /dev/null
+++ b/internal/hostedctl/stop_test.go
@@ -0,0 +1,673 @@
+package hostedctl
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// stopCols are the jobs columns stop and refresh write.
+type stopCols struct {
+ state string
+ requested sql.NullInt64
+ reason, proof sql.NullString
+ launched, deadline, drain, stop int64
+}
+
+func (e *launchEnv) stopCols(attempt string) stopCols {
+ e.t.Helper()
+ var s stopCols
+ if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT state, stop_requested_t, stop_reason, stop_proof_json,
+ launched_t, deadline_t, drain_t, stop_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(
+ &s.state, &s.requested, &s.reason, &s.proof, &s.launched, &s.deadline, &s.drain, &s.stop)
+ }); err != nil {
+ e.t.Fatalf("read stop columns of %s = %v", attempt, err)
+ }
+ return s
+}
+
+// wireProof decodes the stored proof of attempt, which must be there.
+func (e *launchEnv) wireProof(attempt string) hostedwire.StopProof {
+ e.t.Helper()
+ s := e.stopCols(attempt)
+ if !s.proof.Valid {
+ e.t.Fatalf("%s has no stored stop proof", attempt)
+ }
+ var p hostedwire.StopProof
+ if err := json.Unmarshal([]byte(s.proof.String), &p); err != nil {
+ e.t.Fatalf("stored proof %q is not the wire shape: %v", s.proof.String, err)
+ }
+ return p
+}
+
+// launchWith launches attempt for inst-1 with lifetime life and returns its
+// Ref.
+func (e *launchEnv) launchWith(attempt string, life time.Duration) isolatedjob.Ref {
+ e.t.Helper()
+ q := request(attempt)
+ q.MaxLifetime = life
+ v, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
+ if err != nil || v.VMRef == "" {
+ e.t.Fatalf("Launch(%s) = (%+v, %v), want a started VM", attempt, v, err)
+ }
+ return v.VMRef
+}
+
+// replace launches attempt as the replacement of replaced, for inst-1.
+func (e *launchEnv) replace(attempt, replaced string) error {
+ e.t.Helper()
+ q := request(attempt)
+ q.Replaces = replaced
+ _, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
+ return err
+}
+
+// down closes the store, as a controller that exits. up opens it again and
+// builds a new controller over the same fake provider. Time the test moves
+// between the two is downtime.
+func (e *launchEnv) down() {
+ e.t.Helper()
+ if err := e.store.Close(); err != nil {
+ e.t.Fatalf("Close = %v", err)
+ }
+}
+
+func (e *launchEnv) up() {
+ e.t.Helper()
+ e.store = openStore(e.t, e.path, e.clk)
+ e.newController()
+ if !e.store.Restarted() {
+ e.t.Fatal("Restarted() = false after a restart")
+ }
+}
+
+func (e *launchEnv) refresh() {
+ e.t.Helper()
+ if err := e.c.Refresh(e.ctx); err != nil {
+ e.t.Fatalf("Refresh = %v", err)
+ }
+}
+
+func (e *launchEnv) hasAudit(actor hostedwire.KeyID, attempt, action, reasonPart string) bool {
+ e.t.Helper()
+ for _, a := range auditRows(e.t, e.store) {
+ if a.Actor == actor && a.Attempt == attempt && a.Action == action && strings.Contains(a.Reason, reasonPart) {
+ return true
+ }
+ }
+ return false
+}
+
+// stopProbe wraps the fake provider. It records the order of Stop and Get
+// calls and, at each Stop, reads the job's stop columns from the store. The
+// read waits at most 2 s, so a transaction held across the call shows as an
+// error, not a hang.
+type stopProbe struct {
+ *isolatedjob.Fake
+ store *Store
+ ops []isolatedjob.Op
+ atStop []probeStop
+}
+
+type probeStop struct {
+ requested sql.NullInt64
+ reason sql.NullString
+ err error
+}
+
+func (p *stopProbe) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error {
+ rctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+ var s probeStop
+ s.err = p.store.Tx(rctx, func(tx *sql.Tx) error {
+ return tx.QueryRowContext(rctx, `SELECT stop_requested_t, stop_reason FROM jobs WHERE vm_ref = ?`,
+ string(ref)).Scan(&s.requested, &s.reason)
+ })
+ p.atStop = append(p.atStop, s)
+ p.ops = append(p.ops, isolatedjob.OpStop)
+ return p.Fake.Stop(ctx, ref, reason)
+}
+
+func (p *stopProbe) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
+ p.ops = append(p.ops, isolatedjob.OpGet)
+ return p.Fake.Get(ctx, ref)
+}
+
+func TestStopRecordsRequestBeforeProvider(t *testing.T) {
+ e := newLaunchEnv(t)
+ probe := &stopProbe{Fake: e.fake, store: e.store}
+ e.run = probe
+ e.newController()
+ e.audit()
+ e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+ e.clk.AdvanceMono(7 * time.Minute)
+ asked := e.store.Clock().Now()
+
+ _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
+ if !errors.Is(err, ErrStopPending) {
+ t.Fatalf("Stop of a running VM = %v, want ErrStopPending (it is only stopping)", err)
+ }
+ if !slices.Equal(probe.ops, []isolatedjob.Op{isolatedjob.OpStop, isolatedjob.OpGet}) {
+ t.Fatalf("provider calls = %v, want stop then get", probe.ops)
+ }
+ seen := probe.atStop[0]
+ if seen.err != nil {
+ t.Fatalf("reading the store during the provider stop = %v; a transaction is held across it", seen.err)
+ }
+ if !seen.requested.Valid || T(seen.requested.Int64) != asked || seen.reason.String != "task done" {
+ t.Fatalf("at the provider stop: stop_requested_t %v, reason %v; want %d and \"task done\" already saved",
+ seen.requested, seen.reason, asked)
+ }
+ if s := e.stopCols("att-1"); s.proof.Valid || s.state != JobStopping {
+ t.Fatalf("after Stop: state %q, proof %v; want stopping and no proof", s.state, s.proof)
+ }
+ if !e.hasAudit("inst-1", "att-1", actionStopRequested, "task done") {
+ t.Fatal("no stop_requested audit row by inst-1")
+ }
+}
+
+func TestStopProofNeedsTerminalState(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref := e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+ before := e.stopCols("att-1")
+
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
+ t.Fatalf("Stop while the VM is stopping = %v, want ErrStopPending", err)
+ }
+ if s := e.stopCols("att-1"); s.proof.Valid {
+ t.Fatalf("a stopping VM gave proof %s", s.proof.String)
+ }
+ if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
+ t.Fatalf("replacement while the VM is stopping = %v, want ErrReplacementLive", err)
+ }
+
+ e.fake.Tick() // stopping to stopped
+ e.clk.AdvanceMono(time.Minute)
+ at := e.store.Clock().Now()
+ p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "again")
+ if err != nil {
+ t.Fatalf("Stop of a stopped VM = %v, want proof", err)
+ }
+ want := StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at}
+ if p != want {
+ t.Fatalf("proof = %+v, want %+v", p, want)
+ }
+ if w := e.wireProof("att-1"); w != (hostedwire.StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: time.Duration(at)}) {
+ t.Fatalf("stored proof = %+v, want the wire shape of %+v", w, want)
+ }
+ s := e.stopCols("att-1")
+ if s.state != JobStopped || s.reason.String != "task done" || s.stop != before.stop || s.deadline != before.deadline {
+ t.Fatalf("after proof: state %q reason %v stop_t %d deadline_t %d; want stopped, the first reason, times %d %d unchanged",
+ s.state, s.reason, s.stop, s.deadline, before.stop, before.deadline)
+ }
+
+ stops, gets := e.fake.Calls(isolatedjob.OpStop), e.fake.Calls(isolatedjob.OpGet)
+ again, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "once more")
+ if err != nil || again != p {
+ t.Fatalf("Stop of a proven job = (%+v, %v), want the stored proof %+v", again, err, p)
+ }
+ if e.fake.Calls(isolatedjob.OpStop) != stops || e.fake.Calls(isolatedjob.OpGet) != gets {
+ t.Fatal("Stop of a proven job called the provider")
+ }
+ if err := e.replace("att-2", "att-1"); err != nil {
+ t.Fatalf("replacement after proof = %v", err)
+ }
+ if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.State != JobStopped || v.VMRef != ref {
+ t.Fatalf("Get after proof = (%+v, %v), want stopped with ref %s", v, err, ref)
+ }
+}
+
+func TestUnknownStateIsNeverProof(t *testing.T) {
+ e := newLaunchEnv(t)
+ e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStateUnknown) {
+ t.Fatalf("Stop with the provider state unknown = %v, want ErrStateUnknown", err)
+ }
+ if s := e.stopCols("att-1"); s.proof.Valid || s.state == JobStopped {
+ t.Fatalf("unknown state gave state %q, proof %v", s.state, s.proof)
+ }
+ if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
+ t.Fatalf("replacement after an unknown state = %v, want ErrReplacementLive", err)
+ }
+
+ // The VM has really stopped, but the provider still reports unknown.
+ e.fake.Tick()
+ stateBefore := e.stopCols("att-1").state
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
+ e.refresh()
+ if s := e.stopCols("att-1"); s.proof.Valid || s.state != stateBefore {
+ t.Fatalf("Refresh with an unknown state: state %q (was %q), proof %v; want it left alone", s.state, stateBefore, s.proof)
+ }
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStateUnknown) {
+ t.Fatalf("second Stop with the state unknown = %v, want ErrStateUnknown", err)
+ }
+ if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
+ t.Fatalf("replacement after a second unknown state = %v, want ErrReplacementLive", err)
+ }
+
+ // Once the provider answers, the proof comes.
+ if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.State != isolatedjob.StateStopped {
+ t.Fatalf("Stop once the state is known = (%+v, %v), want stopped proof", p, err)
+ }
+}
+
+func TestLostStopReplyRetries(t *testing.T) {
+ t.Run("reply lost after the stop took effect", func(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref := e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+ e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultLostReply)
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, isolatedjob.ErrLostReply) {
+ t.Fatalf("Stop with a lost reply = %v, want the provider error", err)
+ }
+ if s := e.stopCols("att-1"); !s.requested.Valid || s.proof.Valid {
+ t.Fatalf("after a lost reply: requested %v proof %v; want the request kept and no proof", s.requested, s.proof)
+ }
+ if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
+ t.Fatalf("replacement after a lost stop reply = %v, want ErrReplacementLive", err)
+ }
+ e.fake.Tick()
+ p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
+ if err != nil || p.VMRef != ref || p.State != isolatedjob.StateStopped {
+ t.Fatalf("retried Stop = (%+v, %v), want proof for %s", p, err, ref)
+ }
+ if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref, ref}) {
+ t.Fatalf("provider stops = %v, want the stop sent again", got)
+ }
+ })
+ t.Run("stop throttled, sent again by Refresh", func(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref := e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+ e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle)
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, isolatedjob.ErrThrottled) {
+ t.Fatalf("throttled Stop = %v, want the provider error", err)
+ }
+ if live := e.fake.LiveByAttempt()["att-1"]; live != 1 {
+ t.Fatalf("live VMs after a throttled stop = %d, want 1", live)
+ }
+ e.refresh() // the VM is still running: Refresh sends the stop again
+ if got := e.fake.StopsIssued(); len(got) != 2 {
+ t.Fatalf("provider stops after Refresh = %v, want a second one", got)
+ }
+ e.fake.Tick()
+ e.fake.Tick()
+ e.refresh()
+ w := e.wireProof("att-1")
+ if w.VMRef != ref || w.State != isolatedjob.StateStopped {
+ t.Fatalf("proof after Refresh = %+v, want stopped %s", w, ref)
+ }
+ if s := e.stopCols("att-1"); s.reason.String != "task done" {
+ t.Fatalf("stop reason = %v, want the requested one, not ended", s.reason)
+ }
+ })
+}
+
+func TestStopOfGoneVMSucceeds(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref := e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+ e.fake.Vanish(ref)
+ e.clk.AdvanceMono(time.Minute)
+ at := e.store.Clock().Now()
+ p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
+ want := StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at}
+ if err != nil || p != want {
+ t.Fatalf("Stop of a VM the provider no longer holds = (%+v, %v), want %+v", p, err, want)
+ }
+ if err := e.replace("att-2", "att-1"); err != nil {
+ t.Fatalf("replacement after proof = %v", err)
+ }
+}
+
+func TestStopIntentWithoutRef(t *testing.T) {
+ t.Run("lost launch reply left a VM", func(t *testing.T) {
+ e := newLaunchEnv(t)
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply)
+ if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err == nil {
+ t.Fatal("Launch with a lost reply = nil error")
+ }
+ if e.fake.LiveByAttempt()["att-1"] != 1 {
+ t.Fatal("the lost launch made no VM")
+ }
+ e.clk.AdvanceMono(time.Minute)
+ asked := e.store.Clock().Now()
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
+ t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err)
+ }
+ if s := e.stopCols("att-1"); s.state != JobAbandoned || T(s.requested.Int64) != asked || s.proof.Valid {
+ t.Fatalf("after Stop: state %q requested %v proof %v; want abandoned at %d, no proof", s.state, s.requested, s.proof, asked)
+ }
+ launches := e.fake.Calls(isolatedjob.OpLaunch)
+ if err := e.c.Replay(e.ctx); err != nil || e.fake.Calls(isolatedjob.OpLaunch) != launches {
+ t.Fatalf("Replay after Stop = %v with %d launches, want none", err, e.fake.Calls(isolatedjob.OpLaunch)-launches)
+ }
+
+ // The lost reply's VM is live and no job holds its Ref: no proof.
+ e.clk.AdvanceMono(5 * time.Minute)
+ e.refresh()
+ if s := e.stopCols("att-1"); s.proof.Valid {
+ t.Fatalf("proof %s while an unlinked VM is live", s.proof.String)
+ }
+
+ // The orphan reaper (Task 13) stops it; stand in for it.
+ vms, err := e.fake.List(e.ctx)
+ if err != nil || len(vms) != 1 {
+ t.Fatalf("List = (%v, %v), want the one orphan", vms, err)
+ }
+ if err := e.fake.Stop(e.ctx, vms[0].Ref, "orphan"); err != nil {
+ t.Fatal(err)
+ }
+ e.fake.Tick()
+
+ e.fake.Inject(isolatedjob.OpList, isolatedjob.FaultIncompleteList)
+ _ = e.c.Refresh(e.ctx)
+ if s := e.stopCols("att-1"); s.proof.Valid {
+ t.Fatalf("proof %s from an incomplete list", s.proof.String)
+ }
+
+ at := e.store.Clock().Now()
+ e.refresh()
+ w := e.wireProof("att-1")
+ if w != (hostedwire.StopProof{AttemptID: "att-1", State: isolatedjob.StateStopped, ObservedAt: time.Duration(at)}) {
+ t.Fatalf("proof = %+v, want att-1, no ref, stopped, at %d", w, at)
+ }
+ p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "again")
+ if err != nil || p.VMRef != "" || p.State != isolatedjob.StateStopped {
+ t.Fatalf("Stop after proof = (%+v, %v), want the stored proof", p, err)
+ }
+ e.audit()
+ if err := e.replace("att-2", "att-1"); err != nil {
+ t.Fatalf("replacement after proof = %v", err)
+ }
+ })
+ t.Run("list must start 2 minutes after the request", func(t *testing.T) {
+ e := newLaunchEnv(t)
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
+ t.Fatalf("throttled Launch = %v", err)
+ }
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
+ t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err)
+ }
+ e.clk.AdvanceMono(2*time.Minute - time.Nanosecond)
+ e.refresh()
+ if s := e.stopCols("att-1"); s.proof.Valid {
+ t.Fatalf("proof %s from a list started under 2 minutes after the request", s.proof.String)
+ }
+ e.clk.AdvanceMono(time.Nanosecond)
+ e.refresh()
+ if w := e.wireProof("att-1"); w.VMRef != "" || w.State != isolatedjob.StateStopped {
+ t.Fatalf("proof = %+v, want no ref and stopped", w)
+ }
+ })
+}
+
+func TestStopRoles(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref := e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+
+ for _, tc := range []struct {
+ name string
+ by hostedwire.KeyID
+ key hostedwire.VerifyKey
+ }{
+ {"another instance", "inst-2", instKey},
+ {"an operator", "op-1", opKey},
+ {"an operator key with the creator's id", "inst-1", opKey},
+ {"no key id", "", instKey},
+ } {
+ if _, err := e.c.Stop(e.ctx, tc.by, tc.key, "att-1", "mine now"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Stop by %s = %v, want ErrForbidden", tc.name, err)
+ }
+ if a := e.lastAudit(); a.Actor != tc.by || a.Action != actionStopRefused {
+ t.Fatalf("audit after Stop by %s = %+v, want stop_refused by %q", tc.name, a, tc.by)
+ }
+ }
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-9", "no such"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Stop of an unknown attempt = %v, want ErrForbidden", err)
+ }
+ if got := e.fake.StopsIssued(); len(got) != 0 {
+ t.Fatalf("refused stops reached the provider: %v", got)
+ }
+ if s := e.stopCols("att-1"); s.requested.Valid {
+ t.Fatalf("a refused stop recorded a request at %d", s.requested.Int64)
+ }
+
+ if _, err := e.c.Get(e.ctx, "inst-2", "att-1"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Get by another instance = %v, want ErrForbidden", err)
+ }
+ if a := e.lastAudit(); a.Actor != "inst-2" || a.Action != actionGetRefused {
+ t.Fatalf("audit after Get by another instance = %+v, want get_refused", a)
+ }
+ if _, err := e.c.Get(e.ctx, "inst-1", "att-9"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err)
+ }
+ if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.VMRef != ref || v.AttemptID != "att-1" {
+ t.Fatalf("Get by the creator = (%+v, %v), want the job", v, err)
+ }
+ if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
+ t.Fatalf("Stop by the creator = %v, want ErrStopPending", err)
+ }
+}
+
+func TestRestartFindsVMGone(t *testing.T) {
+ e := newLaunchEnv(t)
+ refA := e.launchWith("att-a", 2*time.Hour)
+ refB := e.launchWith("att-b", 2*time.Hour)
+ e.fake.Tick()
+
+ // While the controller is down, A's VM disappears and B's reaches its
+ // lifetime and stops.
+ e.down()
+ e.fake.Vanish(refA)
+ e.clk.AdvanceMono(2 * time.Hour)
+ e.fake.Tick()
+ e.fake.Tick()
+ e.clk.SetWall(testWall.Add(2 * time.Hour))
+ e.up()
+
+ e.refresh()
+ for _, c := range []struct {
+ attempt string
+ ref isolatedjob.Ref
+ }{{"att-a", refA}, {"att-b", refB}} {
+ w := e.wireProof(c.attempt)
+ if w.VMRef != c.ref || w.State != isolatedjob.StateStopped {
+ t.Fatalf("proof for %s = %+v, want stopped %s", c.attempt, w, c.ref)
+ }
+ if s := e.stopCols(c.attempt); s.state != JobStopped || s.reason.String != reasonEnded || s.requested.Valid {
+ t.Fatalf("%s after Refresh: state %q reason %v requested %v; want stopped, ended, no request",
+ c.attempt, s.state, s.reason, s.requested)
+ }
+ }
+ if got := e.fake.StopsIssued(); len(got) != 0 {
+ t.Fatalf("Refresh stopped %v; both VMs had already ended", got)
+ }
+ e.audit()
+ if err := e.replace("att-a2", "att-a"); err != nil {
+ t.Fatalf("replacement of a VM that ended while the controller was down = %v", err)
+ }
+}
+
+func TestRestartUsesProviderAge(t *testing.T) {
+ const life = 2 * time.Hour
+ run := func(t *testing.T, downtime, wallMove time.Duration) (old, got stopCols, want T) {
+ e := newLaunchEnv(t)
+ e.clk.AdvanceMono(time.Minute)
+ monoAtLaunch := e.clk.Mono()
+ e.launchWith("att-1", life)
+ e.fake.Tick()
+ e.clk.AdvanceMono(20 * time.Minute)
+ old = e.stopCols("att-1")
+
+ e.down()
+ e.clk.AdvanceMono(downtime)
+ e.clk.SetWall(testWall.Add(wallMove))
+ e.up()
+
+ age := e.clk.Mono() - monoAtLaunch // what the provider reports
+ want = min(T(old.launched), e.store.Clock().Now()-T(age))
+ e.refresh()
+ got = e.stopCols("att-1")
+ wd, wdr, ws := Deadlines(want, life)
+ if T(got.launched) != want || T(got.deadline) != wd || T(got.drain) != wdr || T(got.stop) != ws {
+ t.Fatalf("after Refresh: launched %d deadline %d drain %d stop %d; want %d %d %d %d",
+ got.launched, got.deadline, got.drain, got.stop, want, wd, wdr, ws)
+ }
+ if got.deadline > old.deadline || got.drain > old.drain || got.stop > old.stop || got.launched > old.launched {
+ t.Fatalf("Refresh moved a time later: %+v from %+v", got, old)
+ }
+ if !e.hasAudit("", "att-1", actionRestartRebased, "") {
+ t.Fatal("no restart_rebased audit row")
+ }
+ return old, got, want
+ }
+ t.Run("wall clock went back", func(t *testing.T) {
+ old, got, _ := run(t, 40*time.Minute, -3*time.Hour)
+ if got.launched >= old.launched || got.stop >= old.stop {
+ t.Fatalf("40 min of downtime with the wall clock back: launched %d stop %d, want both earlier than %d %d",
+ got.launched, got.stop, old.launched, old.stop)
+ }
+ })
+ t.Run("wall clock far ahead", func(t *testing.T) {
+ old, got, _ := run(t, 30*time.Minute, 5*time.Hour)
+ if got.launched != old.launched || got.stop != old.stop {
+ t.Fatalf("wall delta beyond the provider age moved times: %+v from %+v", got, old)
+ }
+ })
+}
+
+func TestRestartDowntimeExceedsWallDelta(t *testing.T) {
+ const life = 4 * time.Hour
+ e := newLaunchEnv(t)
+ ref1 := e.launchWith("att-1", life) // its age will be unknown
+ e.clk.AdvanceMono(time.Minute)
+ monoAt2 := e.clk.Mono()
+ e.launchWith("att-2", life)
+ e.fake.Tick()
+ old2 := e.stopCols("att-2")
+
+ // Two hours of real downtime; the wall clock reads only 10 min on.
+ e.down()
+ e.clk.AdvanceMono(2 * time.Hour)
+ e.clk.SetWall(testWall.Add(10 * time.Minute))
+ e.up()
+
+ now := e.store.Clock().Now()
+ if got := time.Duration(now - T(old2.launched)); got > 15*time.Minute {
+ t.Fatalf("controller time moved %v across the restart; the test needs the wall delta to understate it", got)
+ }
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) // att-1 is read first
+ e.refresh()
+
+ want := now - T(e.clk.Mono()-monoAt2)
+ wd, wdr, ws := Deadlines(want, life)
+ got := e.stopCols("att-2")
+ if T(got.launched) != want || T(got.deadline) != wd || T(got.drain) != wdr || T(got.stop) != ws {
+ t.Fatalf("att-2 with a trusted age: launched %d deadline %d drain %d stop %d; want %d %d %d %d",
+ got.launched, got.deadline, got.drain, got.stop, want, wd, wdr, ws)
+ }
+ if got.requested.Valid {
+ t.Fatal("att-2 has a trusted age but was stopped")
+ }
+ s1 := e.stopCols("att-1")
+ if !s1.requested.Valid || s1.reason.String != reasonElapsedUnknown {
+ t.Fatalf("att-1 with no age: requested %v reason %v; want stopped with %s", s1.requested, s1.reason, reasonElapsedUnknown)
+ }
+ if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1}) {
+ t.Fatalf("provider stops = %v, want only %s", got, ref1)
+ }
+}
+
+func TestRestartStopsWhenElapsedUnknown(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref1 := e.launchWith("att-1", 2*time.Hour) // age unknown after the restart
+ e.clk.AdvanceMono(time.Minute)
+ e.launchWith("att-3", 2*time.Hour) // age known after the restart
+ e.fake.Tick()
+
+ e.down()
+ e.clk.AdvanceMono(10 * time.Minute)
+ e.clk.SetWall(testWall.Add(10 * time.Minute))
+ e.up()
+ e.audit()
+ e.clk.AdvanceMono(time.Minute)
+ e.launchWith("att-2", 2*time.Hour) // launched after the restart
+ e.fake.Tick()
+
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
+ e.refresh()
+ s1 := e.stopCols("att-1")
+ if !s1.requested.Valid || s1.reason.String != reasonElapsedUnknown || s1.state != JobStopping {
+ t.Fatalf("att-1 after Refresh: requested %v reason %v state %q; want a stop for %s, stopping",
+ s1.requested, s1.reason, s1.state, reasonElapsedUnknown)
+ }
+ if !e.hasAudit("", "att-1", actionStopRequested, reasonElapsedUnknown) {
+ t.Fatal("no stop_requested audit row by the controller for att-1")
+ }
+
+ // Each job is re-based once per process: a later unknown age stops
+ // neither the job already re-based nor one launched after the restart.
+ for range 3 {
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
+ }
+ e.refresh()
+ if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1}) {
+ t.Fatalf("provider stops = %v, want only %s", got, ref1)
+ }
+ for _, a := range []string{"att-2", "att-3"} {
+ if s := e.stopCols(a); s.requested.Valid {
+ t.Fatalf("%s was stopped (%v); its elapsed time is known", a, s.reason)
+ }
+ }
+
+ e.fake.Tick()
+ e.refresh()
+ if w := e.wireProof("att-1"); w.VMRef != ref1 || w.State != isolatedjob.StateStopped {
+ t.Fatalf("proof for att-1 = %+v, want stopped %s", w, ref1)
+ }
+ if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown {
+ t.Fatalf("att-1 reason after proof = %v, want %s kept", s.reason, reasonElapsedUnknown)
+ }
+}
+
+// A wall clock behind the checkpoint restores T to the checkpoint itself, so
+// a job saved just before the exit can have launched_t equal to OpenedAt. It
+// still existed before the restart.
+func TestRestartJobAtOpenTime(t *testing.T) {
+ e := newLaunchEnv(t)
+ ref := e.launchWith("att-1", 2*time.Hour)
+ e.fake.Tick()
+ e.down()
+ e.clk.AdvanceMono(3 * time.Hour)
+ e.clk.SetWall(testWall.Add(-time.Hour))
+ e.up()
+ if s := e.stopCols("att-1"); T(s.launched) != e.store.OpenedAt() {
+ t.Fatalf("launched_t %d, OpenedAt %d; the test needs them equal", s.launched, e.store.OpenedAt())
+ }
+ e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
+ e.refresh()
+ if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown {
+ t.Fatalf("job launched at OpenedAt with no age: reason %v, want %s", s.reason, reasonElapsedUnknown)
+ }
+ if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref}) {
+ t.Fatalf("provider stops = %v, want %s", got, ref)
+ }
+}
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go
index 2c9ae493..0bff3620 100644
--- a/internal/hostedctl/store.go
+++ b/internal/hostedctl/store.go
@@ -316,6 +316,11 @@ func (s *Store) Clock() *CtlClock { return s.clock }
// has lived.
func (s *Store) Restarted() bool { return s.restarted }
+// OpenedAt returns controller time at Open. Every T stored before Open is at
+// or below it, so after a restart a job launched at or before OpenedAt
+// existed before this process opened the store.
+func (s *Store) OpenedAt() T { return s.clock.base }
+
// StartupAlerts returns the undelivered alerts from alert_outbox, as loaded
// by Open and not yet delivered by New, oldest first.
func (s *Store) StartupAlerts() []Alert {