oficina / equipo Public

isolatedjob: in-memory fake and adapter contract suite

Fake is an in-memory Runner and NetworkAuditor with one-shot faults
(throttle, lost reply, incomplete list, unknown state, unknown age), a
Tick-driven lifecycle and a lifetime backstop that counts suspended time.
isolatedjobtest holds FakeClock and the Contract suite that the AWS
adapter will also run behind the hostedlive tag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4f31b9eb95f5ff401b7014b162a55581a3ffc94d parent c65ae02
5 files changed, +1,176 −0
  • docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md +15 −0
  • internal/isolatedjob/fake.go +469 −0
  • internal/isolatedjob/fake_test.go +413 −0
  • internal/isolatedjob/isolatedjobtest/clock.go +56 −0
  • internal/isolatedjob/isolatedjobtest/contract.go +223 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
index aae7f5de..b047ac8b 100644
--- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
@@ -100,3 +100,18 @@ Every guard now has a mutation. `SystemClock` takes its wall and elapsed sources
| clock: start loses monotonic reading (`start: now().Round(0), now:`) | `go test ./internal/isolatedjob -run 'TestSystemClock$' -count=1` | `isolatedjob_test.go:234: start = 2026-11-22 16:04:31.981554794 +0000 GMT has no monotonic reading` | yes, passes |
| clock: Wall derived from Mono (`return c.start.Add(c.Mono()).Round(0)`) | `go test ./internal/isolatedjob -run 'TestSystemClockWallJump' -count=1` | `isolatedjob_test.go:264: step 1: Wall = 2026-11-22 12:00:10 +0000 UTC, want 2026-11-22 11:00:05 +0000 UTC` | yes, passes |
| clock: Wall keeps monotonic reading (`return c.now()`) | `go test ./internal/isolatedjob -run 'TestSystemClock$' -count=1` | `isolatedjob_test.go:227: Wall = 2026-11-22 16:04:32.430137707 +0000 GMT m=+0.000216344 carries a monotonic reading` | yes, passes |
+
+## Task 6
+
+`isolatedjob.Fake` (an in-memory `Runner` and `NetworkAuditor`, limits from `SpikeLimits()`) and `isolatedjobtest` (`FakeClock`, `Harness`, `Contract`). Faults are one-shot and queue in order per op. `Tick` steps starting, suspending and stopping on, then the backstop stops VMs whose lifetime since launch (suspended time included while `SuspendUsesLifetime`) has reached their `MaxLifetime`. Resume moves a suspended VM straight to running; Resume of a running VM is a no-op.
+
+| Mutation | Command | Observed failure | Restored |
+| --- | --- | --- | --- |
+| idempotency keyed on Ref (`f.byAttempt[string(vm.ref)] = vm.ref`) | `go test ./internal/isolatedjob -run 'TestFakeContract/LaunchIdempotentOnAttempt' -count=1` | `contract.go:83: second Launch(contract-91c43af87640-1) = vm-0002, want vm-0001: one attempt must be one VM` | yes, passes |
+| Tick leaves suspended time out (`if !f.limits.SuspendUsesLifetime \|\| true {`) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:212: Get(vm-0001).State = suspended, want stopping` | yes, passes |
+| throttle applies the call (`if fl == FaultThrottle && false {`) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:116: throttled Launch = ("vm-0001", <nil>), want ("", ErrThrottled)` | yes, passes |
+| lost reply skips the effect (`if fl == FaultLostReply { return "", ErrLostReply }` before `launchLocked`) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:134: LiveByAttempt after a lost reply = map[], want a1:1 (the launch happened)` | yes, passes |
+| incomplete list ignored (`case FaultIncompleteList + "x":` in List) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:155: faulted List = ([{vm-0001 starting ...}], <nil>), want (nil, ErrIncomplete)` | yes, passes |
+| unknown state ignored (`case FaultUnknownState + "x":` in Get) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:166: Get(vm-0001).State = running, want unknown` | yes, passes |
+| age unknown ignored (`case FaultAgeUnknown + "x":` in Get) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:175: faulted Get = {... AgeKnown:true}, want AgeKnown false and still running` | yes, passes |
+| faults not used up (`f.faults[op] = q[0:]`) | `go test ./internal/isolatedjob -run 'TestFakeFaults' -count=1` | `fake_test.go:121: Launch(a1) = isolatedjob: throttled: fake launch` (and every other row) | yes, passes |
diff --git a/internal/isolatedjob/fake.go b/internal/isolatedjob/fake.go
new file mode 100644
index 00000000..4e738a93
--- /dev/null
+++ b/internal/isolatedjob/fake.go
@@ -0,0 +1,469 @@
+package isolatedjob
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "sync"
+ "time"
+)
+
+// Op names one Runner call, so a test can aim a fault at it.
+type Op string
+
+const (
+ OpLaunch Op = "launch"
+ OpGet Op = "get"
+ OpSuspend Op = "suspend"
+ OpResume Op = "resume"
+ OpStop Op = "stop"
+ OpList Op = "list"
+)
+
+// Fault is a provider misbehaviour the Fake can play once.
+type Fault string
+
+const (
+ // FaultThrottle: the call does nothing and returns ErrThrottled. Any op.
+ FaultThrottle Fault = "throttle"
+ // FaultLostReply: the call takes effect, then returns ErrLostReply in
+ // place of its answer. Any op.
+ FaultLostReply Fault = "lost reply"
+ // FaultIncompleteList: List returns (nil, ErrIncomplete). OpList only.
+ FaultIncompleteList Fault = "incomplete list"
+ // FaultUnknownState: Get reports StateUnknown; the VM is unchanged.
+ // OpGet only.
+ FaultUnknownState Fault = "unknown state"
+ // FaultAgeUnknown: Get reports AgeKnown false. OpGet only.
+ FaultAgeUnknown Fault = "age unknown"
+)
+
+// ErrLostReply is what a call hit by FaultLostReply returns. It is none of
+// the package's sentinels on purpose: the caller cannot tell whether the call
+// took effect, as with a timeout on a real provider.
+var ErrLostReply = errors.New("isolatedjob fake: reply lost; the call may have taken effect")
+
+// SpikeLimits returns the limits the 2026-11-18 spike found on AWS Lambda
+// MicroVMs (spec §15): 8 hours of lifetime counting suspended time, a
+// 4096-byte bootstrap, and open connections dropped by suspend.
+func SpikeLimits() Limits {
+ return Limits{
+ MaxLifetime: 28800 * time.Second,
+ MaxBootstrapBytes: 4096,
+ SuspendUsesLifetime: true,
+ ConnectionsSurvive: false,
+ }
+}
+
+// Fake is an in-memory Runner and NetworkAuditor for tests. It is safe for
+// concurrent use.
+//
+// Lifecycle. Launch creates a VM in starting. Tick moves every VM one step:
+// starting to running, suspending to suspended, stopping to stopped. Suspend
+// needs a running VM and moves it to suspending. Resume moves a suspended VM
+// straight to running (AWS has no resuming state) and does nothing to a
+// running one. Stop moves any live VM to stopping and does nothing to a
+// stopped VM or a ref it never held. Other calls on a VM in the wrong state
+// return ErrConflict; calls on an unknown ref return ErrNotFound. Stopped VMs
+// stay visible to Get and List.
+//
+// Backstop. While the backstop is on (the default), Tick also moves to
+// stopping every VM whose lifetime has reached its spec's MaxLifetime, with
+// a reason naming the lifetime. Lifetime is measured on the clock's Mono from
+// launch and includes suspended time, unless the Limits say suspended time
+// does not count.
+//
+// Launch is idempotent on AttemptID, like a provider client token: the same
+// spec returns the same Ref even after that VM has stopped, and a different
+// spec under the same AttemptID returns ErrConflict. Launch validates the
+// spec against the fake's Limits first, so a bad spec never reaches the fake
+// provider and uses up no fault.
+//
+// Faults. Inject queues a fault for one op. The next call of that op takes
+// the oldest queued fault and uses it up, whatever the call's outcome. A call
+// whose context is already done returns the context's error and takes no
+// fault.
+type Fake struct {
+ clock Clock
+ limits Limits
+
+ mu sync.Mutex
+ backstop bool
+ nextID int
+ vms map[Ref]*fakeVM
+ order []Ref // creation order, for List
+ byAttempt map[string]Ref // the client-token table; Plant does not write it
+ faults map[Op][]Fault
+ stops []Ref
+ audit NetworkAudit
+ auditErr error
+}
+
+type fakeVM struct {
+ ref Ref
+ spec LaunchSpec
+ state State
+ reason string
+ startedAt time.Time // Wall at launch
+ launched time.Duration // Mono at launch
+
+ // Suspended time, for providers whose lifetime leaves it out.
+ paused time.Duration // finished suspensions
+ pausedSince time.Duration // Mono when the current suspension began
+ isPaused bool
+}
+
+// NewFake returns a Fake reading time from c and reporting limits l. Pass
+// SpikeLimits() for the limits the real provider has.
+func NewFake(c Clock, l Limits) *Fake {
+ return &Fake{
+ clock: c,
+ limits: l,
+ backstop: true,
+ vms: map[Ref]*fakeVM{},
+ byAttempt: map[string]Ref{},
+ faults: map[Op][]Fault{},
+ audit: NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true},
+ }
+}
+
+// Inject queues f for the next call of op. It panics when op cannot have f,
+// such as FaultIncompleteList on OpGet.
+func (f *Fake) Inject(op Op, fl Fault) {
+ ok := false
+ switch fl {
+ case FaultThrottle, FaultLostReply:
+ ok = slices.Contains([]Op{OpLaunch, OpGet, OpSuspend, OpResume, OpStop, OpList}, op)
+ case FaultIncompleteList:
+ ok = op == OpList
+ case FaultUnknownState, FaultAgeUnknown:
+ ok = op == OpGet
+ }
+ if !ok {
+ panic(fmt.Sprintf("isolatedjob fake: op %q cannot have fault %q", op, fl))
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.faults[op] = append(f.faults[op], fl)
+}
+
+// takeFault removes and returns the oldest fault queued for op, or "".
+// The caller holds f.mu.
+func (f *Fake) takeFault(op Op) Fault {
+ q := f.faults[op]
+ if len(q) == 0 {
+ return ""
+ }
+ f.faults[op] = q[1:]
+ return q[0]
+}
+
+// begin starts one call of op: it checks ctx, takes the call's fault and
+// returns it, with the lock held. A throttle comes back as ErrThrottled.
+func (f *Fake) begin(ctx context.Context, op Op) (Fault, error) {
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ f.mu.Lock()
+ fl := f.takeFault(op)
+ if fl == FaultThrottle {
+ f.mu.Unlock()
+ return fl, fmt.Errorf("%w: fake %s", ErrThrottled, op)
+ }
+ return fl, nil
+}
+
+// finish turns a lost reply into ErrLostReply; otherwise it returns err.
+func finish(fl Fault, op Op, err error) error {
+ if fl == FaultLostReply {
+ return fmt.Errorf("%w (fake %s)", ErrLostReply, op)
+ }
+ return err
+}
+
+// Launch starts a VM for s, or returns the VM already started for
+// s.AttemptID.
+func (f *Fake) Launch(ctx context.Context, s LaunchSpec) (Ref, error) {
+ if err := s.Validate(f.limits); err != nil {
+ return "", err
+ }
+ fl, err := f.begin(ctx, OpLaunch)
+ if err != nil {
+ return "", err
+ }
+ defer f.mu.Unlock()
+ ref, err := f.launchLocked(s)
+ if err = finish(fl, OpLaunch, err); err != nil {
+ return "", err
+ }
+ return ref, nil
+}
+
+func (f *Fake) launchLocked(s LaunchSpec) (Ref, error) {
+ if ref, ok := f.byAttempt[s.AttemptID]; ok {
+ if !sameSpec(f.vms[ref].spec, s) {
+ return "", fmt.Errorf("%w: attempt %s was launched with a different spec", ErrConflict, s.AttemptID)
+ }
+ return ref, nil
+ }
+ vm := f.addLocked(s, StateStarting)
+ f.byAttempt[s.AttemptID] = vm.ref
+ return vm.ref, nil
+}
+
+func sameSpec(a, b LaunchSpec) bool {
+ return a.AttemptID == b.AttemptID && a.Image == b.Image && a.Size == b.Size &&
+ a.MaxLifetime == b.MaxLifetime && bytes.Equal(a.Bootstrap, b.Bootstrap)
+}
+
+func (f *Fake) addLocked(s LaunchSpec, st State) *fakeVM {
+ f.nextID++
+ s.Bootstrap = bytes.Clone(s.Bootstrap)
+ vm := &fakeVM{
+ ref: Ref(fmt.Sprintf("vm-%04d", f.nextID)),
+ spec: s,
+ state: st,
+ startedAt: f.clock.Wall(),
+ launched: f.clock.Mono(),
+ }
+ f.vms[vm.ref] = vm
+ f.order = append(f.order, vm.ref)
+ return vm
+}
+
+// Plant adds a running VM that no Launch asked for, as an orphan left on the
+// provider, and returns its Ref. It counts in LiveByAttempt under
+// s.AttemptID, but a later Launch of s.AttemptID does not find it. s is not
+// validated; a zero MaxLifetime means the fake's Limits().MaxLifetime.
+func (f *Fake) Plant(s LaunchSpec) Ref {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.addLocked(s, StateRunning).ref
+}
+
+// Get reads one VM.
+func (f *Fake) Get(ctx context.Context, ref Ref) (Job, error) {
+ fl, err := f.begin(ctx, OpGet)
+ if err != nil {
+ return Job{}, err
+ }
+ defer f.mu.Unlock()
+ vm, ok := f.vms[ref]
+ if !ok {
+ return Job{}, finish(fl, OpGet, fmt.Errorf("%w: %s", ErrNotFound, ref))
+ }
+ job := f.jobLocked(vm)
+ switch fl {
+ case FaultUnknownState:
+ job.State = StateUnknown
+ case FaultAgeUnknown:
+ job.ProviderAge, job.AgeKnown = 0, false
+ case FaultLostReply:
+ return Job{}, finish(fl, OpGet, nil)
+ }
+ return job, nil
+}
+
+func (f *Fake) jobLocked(vm *fakeVM) Job {
+ return Job{
+ Ref: vm.ref,
+ State: vm.state,
+ StartedAt: vm.startedAt,
+ Reason: vm.reason,
+ ProviderAge: f.clock.Mono() - vm.launched,
+ AgeKnown: true,
+ }
+}
+
+// Suspend moves a running VM to suspending.
+func (f *Fake) Suspend(ctx context.Context, ref Ref) error {
+ fl, err := f.begin(ctx, OpSuspend)
+ if err != nil {
+ return err
+ }
+ defer f.mu.Unlock()
+ vm, ok := f.vms[ref]
+ switch {
+ case !ok:
+ err = fmt.Errorf("%w: %s", ErrNotFound, ref)
+ case vm.state != StateRunning:
+ err = fmt.Errorf("%w: suspend %s while %s", ErrConflict, ref, vm.state)
+ default:
+ vm.state = StateSuspending
+ vm.isPaused, vm.pausedSince = true, f.clock.Mono()
+ }
+ return finish(fl, OpSuspend, err)
+}
+
+// Resume moves a suspended VM to running. A running VM is left alone.
+func (f *Fake) Resume(ctx context.Context, ref Ref) error {
+ fl, err := f.begin(ctx, OpResume)
+ if err != nil {
+ return err
+ }
+ defer f.mu.Unlock()
+ vm, ok := f.vms[ref]
+ switch {
+ case !ok:
+ err = fmt.Errorf("%w: %s", ErrNotFound, ref)
+ case vm.state == StateRunning:
+ case vm.state != StateSuspended:
+ err = fmt.Errorf("%w: resume %s while %s", ErrConflict, ref, vm.state)
+ default:
+ vm.state = StateRunning
+ vm.unpause(f.clock.Mono())
+ }
+ return finish(fl, OpResume, err)
+}
+
+func (vm *fakeVM) unpause(now time.Duration) {
+ if vm.isPaused {
+ vm.paused += now - vm.pausedSince
+ vm.isPaused = false
+ }
+}
+
+// Stop moves a live VM to stopping. A stopped VM, a stopping VM and a ref the
+// fake never held all succeed with no change. Every call that reaches the
+// fake is recorded for StopsIssued, throttled or not.
+func (f *Fake) Stop(ctx context.Context, ref Ref, reason string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ f.mu.Lock()
+ f.stops = append(f.stops, ref)
+ f.mu.Unlock()
+ fl, err := f.begin(ctx, OpStop)
+ if err != nil {
+ return err
+ }
+ defer f.mu.Unlock()
+ if vm, ok := f.vms[ref]; ok && vm.state.Live() && vm.state != StateStopping {
+ f.stopLocked(vm, reason)
+ }
+ return finish(fl, OpStop, nil)
+}
+
+func (f *Fake) stopLocked(vm *fakeVM, reason string) {
+ vm.state = StateStopping
+ vm.reason = reason
+ vm.unpause(f.clock.Mono())
+}
+
+// List returns every VM the fake holds, stopped ones included, in launch
+// order.
+func (f *Fake) List(ctx context.Context) ([]Job, error) {
+ fl, err := f.begin(ctx, OpList)
+ if err != nil {
+ return nil, err
+ }
+ defer f.mu.Unlock()
+ switch fl {
+ case FaultIncompleteList:
+ return nil, fmt.Errorf("%w: fake list", ErrIncomplete)
+ case FaultLostReply:
+ return nil, finish(fl, OpList, nil)
+ }
+ jobs := make([]Job, 0, len(f.order))
+ for _, ref := range f.order {
+ jobs = append(jobs, f.jobLocked(f.vms[ref]))
+ }
+ return jobs, nil
+}
+
+// Limits returns the limits the fake was made with.
+func (f *Fake) Limits() Limits { return f.limits }
+
+// Tick moves every VM one lifecycle step, then, with the backstop on, stops
+// the VMs whose lifetime has run out.
+func (f *Fake) Tick() {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ now := f.clock.Mono()
+ for _, ref := range f.order {
+ vm := f.vms[ref]
+ switch vm.state {
+ case StateStarting:
+ vm.state = StateRunning
+ case StateSuspending:
+ vm.state = StateSuspended
+ case StateStopping:
+ vm.state = StateStopped
+ }
+ limit := vm.spec.MaxLifetime
+ if limit <= 0 {
+ limit = f.limits.MaxLifetime // a planted VM may name none
+ }
+ if f.backstop && vm.state.Live() && vm.state != StateStopping && f.lifetimeLocked(vm, now) >= limit {
+ f.stopLocked(vm, fmt.Sprintf("maximum lifetime %v reached", limit))
+ }
+ }
+}
+
+// lifetimeLocked is how much of its lifetime vm has used at now.
+func (f *Fake) lifetimeLocked(vm *fakeVM, now time.Duration) time.Duration {
+ used := now - vm.launched
+ if !f.limits.SuspendUsesLifetime {
+ used -= vm.paused
+ if vm.isPaused {
+ used -= now - vm.pausedSince
+ }
+ }
+ return used
+}
+
+// SetBackstop turns the lifetime backstop on or off. It is on by default.
+func (f *Fake) SetBackstop(on bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.backstop = on
+}
+
+// LiveByAttempt counts the live VMs under each attempt ID, planted ones
+// included. Attempts with no live VM are left out.
+func (f *Fake) LiveByAttempt() map[string]int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ out := map[string]int{}
+ for _, vm := range f.vms {
+ if vm.state.Live() {
+ out[vm.spec.AttemptID]++
+ }
+ }
+ return out
+}
+
+// StopsIssued returns the refs passed to Stop, in call order.
+func (f *Fake) StopsIssued() []Ref {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return slices.Clone(f.stops)
+}
+
+// SetAudit sets what AuditNetwork returns. The default is a passing audit
+// with no egress destinations.
+func (f *Fake) SetAudit(a NetworkAudit, err error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ a.EgressOnly = slices.Clone(a.EgressOnly)
+ f.audit, f.auditErr = a, err
+}
+
+// AuditNetwork returns what SetAudit last set.
+func (f *Fake) AuditNetwork(ctx context.Context) (NetworkAudit, error) {
+ if err := ctx.Err(); err != nil {
+ return NetworkAudit{}, err
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ a := f.audit
+ a.EgressOnly = slices.Clone(a.EgressOnly)
+ return a, f.auditErr
+}
+
+var (
+ _ Runner = (*Fake)(nil)
+ _ NetworkAuditor = (*Fake)(nil)
+)
diff --git a/internal/isolatedjob/fake_test.go b/internal/isolatedjob/fake_test.go
new file mode 100644
index 00000000..0ebf79e2
--- /dev/null
+++ b/internal/isolatedjob/fake_test.go
@@ -0,0 +1,413 @@
+package isolatedjob_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/netip"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+)
+
+const fakeDigest = isolatedjob.ImageDigest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
+
+var fakeStart = time.Date(2026, 11, 22, 9, 0, 0, 0, time.UTC)
+
+func newFake(t *testing.T) (*isolatedjob.Fake, *isolatedjobtest.FakeClock) {
+ t.Helper()
+ c := isolatedjobtest.NewFakeClock(fakeStart)
+ return isolatedjob.NewFake(c, isolatedjob.SpikeLimits()), c
+}
+
+func fakeSpec(attempt string) isolatedjob.LaunchSpec {
+ return isolatedjob.LaunchSpec{
+ AttemptID: attempt,
+ Image: fakeDigest,
+ Size: isolatedjob.SizeSmall,
+ MaxLifetime: time.Hour,
+ Bootstrap: []byte("one-time-code"),
+ }
+}
+
+// settleFake ticks the fake until want holds, reading the VM before each tick.
+func settleFake(f *isolatedjob.Fake) func(context.Context, isolatedjob.Ref, func(isolatedjob.State) bool) (isolatedjob.Job, error) {
+ return func(ctx context.Context, ref isolatedjob.Ref, want func(isolatedjob.State) bool) (isolatedjob.Job, error) {
+ const maxTicks = 10
+ var job isolatedjob.Job
+ for range maxTicks + 1 {
+ var err error
+ job, err = f.Get(ctx, ref)
+ if err != nil {
+ return job, err
+ }
+ if want(job.State) {
+ return job, nil
+ }
+ f.Tick()
+ }
+ return job, fmt.Errorf("fake VM %s still %s after %d ticks", ref, job.State, maxTicks)
+ }
+}
+
+func TestFakeContract(t *testing.T) {
+ f, _ := newFake(t)
+ isolatedjobtest.Contract(t, isolatedjobtest.Harness{Runner: f, Image: fakeDigest, Settle: settleFake(f)})
+}
+
+func mustLaunch(t *testing.T, f *isolatedjob.Fake, s isolatedjob.LaunchSpec) isolatedjob.Ref {
+ t.Helper()
+ ref, err := f.Launch(context.Background(), s)
+ if err != nil {
+ t.Fatalf("Launch(%s) = %v", s.AttemptID, err)
+ }
+ return ref
+}
+
+func mustGet(t *testing.T, f *isolatedjob.Fake, ref isolatedjob.Ref) isolatedjob.Job {
+ t.Helper()
+ job, err := f.Get(context.Background(), ref)
+ if err != nil {
+ t.Fatalf("Get(%s) = %v", ref, err)
+ }
+ return job
+}
+
+func wantState(t *testing.T, f *isolatedjob.Fake, ref isolatedjob.Ref, want isolatedjob.State) {
+ t.Helper()
+ if got := mustGet(t, f, ref).State; got != want {
+ t.Fatalf("Get(%s).State = %s, want %s", ref, got, want)
+ }
+}
+
+// running launches a VM and ticks it to running.
+func running(t *testing.T, f *isolatedjob.Fake, s isolatedjob.LaunchSpec) isolatedjob.Ref {
+ t.Helper()
+ ref := mustLaunch(t, f, s)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ return ref
+}
+
+func isSentinel(err error) bool {
+ for _, s := range []error{isolatedjob.ErrNotFound, isolatedjob.ErrInvalid, isolatedjob.ErrConflict,
+ isolatedjob.ErrThrottled, isolatedjob.ErrIncomplete, isolatedjob.ErrBootstrapTooLarge} {
+ if errors.Is(err, s) {
+ return true
+ }
+ }
+ return false
+}
+
+// TestFakeFaults has one row per fault. Every row also checks that the fault
+// was used up by the one call it hit.
+func TestFakeFaults(t *testing.T) {
+ ctx := context.Background()
+ t.Run("throttle does nothing", func(t *testing.T) {
+ f, _ := newFake(t)
+ f.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ ref, err := f.Launch(ctx, fakeSpec("a1"))
+ if !errors.Is(err, isolatedjob.ErrThrottled) || ref != "" {
+ t.Fatalf("throttled Launch = (%q, %v), want (\"\", ErrThrottled)", ref, err)
+ }
+ if live := f.LiveByAttempt(); len(live) != 0 {
+ t.Fatalf("LiveByAttempt after a throttled launch = %v, want none", live)
+ }
+ mustLaunch(t, f, fakeSpec("a1"))
+ if live := f.LiveByAttempt(); live["a1"] != 1 {
+ t.Fatalf("LiveByAttempt after the next launch = %v, want a1:1", live)
+ }
+ })
+ t.Run("lost reply applies then errs", func(t *testing.T) {
+ f, _ := newFake(t)
+ f.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply)
+ ref, err := f.Launch(ctx, fakeSpec("a1"))
+ if !errors.Is(err, isolatedjob.ErrLostReply) || isSentinel(err) || ref != "" {
+ t.Fatalf("lost-reply Launch = (%q, %v), want (\"\", ErrLostReply) and no sentinel", ref, err)
+ }
+ if live := f.LiveByAttempt(); live["a1"] != 1 {
+ t.Fatalf("LiveByAttempt after a lost reply = %v, want a1:1 (the launch happened)", live)
+ }
+ again := mustLaunch(t, f, fakeSpec("a1"))
+ if live := f.LiveByAttempt(); live["a1"] != 1 {
+ t.Fatalf("LiveByAttempt after the retry = %v, want a1:1", live)
+ }
+ f.Inject(isolatedjob.OpStop, isolatedjob.FaultLostReply)
+ if err := f.Stop(ctx, again, "test"); !errors.Is(err, isolatedjob.ErrLostReply) {
+ t.Fatalf("lost-reply Stop = %v, want ErrLostReply", err)
+ }
+ wantState(t, f, again, isolatedjob.StateStopping)
+ if err := f.Stop(ctx, again, "test"); err != nil {
+ t.Fatalf("the next Stop = %v, want nil", err)
+ }
+ })
+ t.Run("incomplete list", func(t *testing.T) {
+ f, _ := newFake(t)
+ ref := mustLaunch(t, f, fakeSpec("a1"))
+ f.Inject(isolatedjob.OpList, isolatedjob.FaultIncompleteList)
+ jobs, err := f.List(ctx)
+ if !errors.Is(err, isolatedjob.ErrIncomplete) || jobs != nil {
+ t.Fatalf("faulted List = (%v, %v), want (nil, ErrIncomplete)", jobs, err)
+ }
+ jobs, err = f.List(ctx)
+ if err != nil || len(jobs) != 1 || jobs[0].Ref != ref {
+ t.Fatalf("the next List = (%v, %v), want just %s", jobs, err, ref)
+ }
+ })
+ t.Run("unknown state on get", func(t *testing.T) {
+ f, _ := newFake(t)
+ ref := running(t, f, fakeSpec("a1"))
+ f.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
+ wantState(t, f, ref, isolatedjob.StateUnknown)
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ })
+ t.Run("age unknown on get", func(t *testing.T) {
+ f, c := newFake(t)
+ ref := running(t, f, fakeSpec("a1"))
+ c.AdvanceMono(5 * time.Minute)
+ f.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
+ if job := mustGet(t, f, ref); job.AgeKnown || job.State != isolatedjob.StateRunning {
+ t.Fatalf("faulted Get = %+v, want AgeKnown false and still running", job)
+ }
+ if job := mustGet(t, f, ref); !job.AgeKnown || job.ProviderAge != 5*time.Minute {
+ t.Fatalf("the next Get = %+v, want AgeKnown and ProviderAge 5m", job)
+ }
+ })
+ t.Run("faults queue in order", func(t *testing.T) {
+ f, _ := newFake(t)
+ ref := running(t, f, fakeSpec("a1"))
+ f.Inject(isolatedjob.OpSuspend, isolatedjob.FaultThrottle)
+ f.Inject(isolatedjob.OpSuspend, isolatedjob.FaultLostReply)
+ if err := f.Suspend(ctx, ref); !errors.Is(err, isolatedjob.ErrThrottled) {
+ t.Fatalf("first Suspend = %v, want ErrThrottled", err)
+ }
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ if err := f.Suspend(ctx, ref); !errors.Is(err, isolatedjob.ErrLostReply) {
+ t.Fatalf("second Suspend = %v, want ErrLostReply", err)
+ }
+ wantState(t, f, ref, isolatedjob.StateSuspending)
+ f.Tick()
+ if err := f.Resume(ctx, ref); err != nil {
+ t.Fatalf("Resume with no fault queued = %v", err)
+ }
+ })
+ t.Run("tick counts suspended time", func(t *testing.T) {
+ f, c := newFake(t)
+ ref := running(t, f, fakeSpec("a1")) // one-hour lifetime
+ c.AdvanceMono(10 * time.Minute)
+ if err := f.Suspend(ctx, ref); err != nil {
+ t.Fatal(err)
+ }
+ f.Tick()
+ c.AdvanceMono(49 * time.Minute)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateSuspended)
+ c.AdvanceMono(time.Minute)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateStopping)
+ f.Tick()
+ job := mustGet(t, f, ref)
+ if job.State != isolatedjob.StateStopped || !strings.Contains(job.Reason, "lifetime") {
+ t.Fatalf("Get after the backstop = %+v, want stopped with a lifetime reason", job)
+ }
+ if live := f.LiveByAttempt(); len(live) != 0 {
+ t.Fatalf("LiveByAttempt = %v, want none", live)
+ }
+ })
+ t.Run("suspended time excluded when the provider says so", func(t *testing.T) {
+ c := isolatedjobtest.NewFakeClock(fakeStart)
+ l := isolatedjob.SpikeLimits()
+ l.SuspendUsesLifetime = false
+ f := isolatedjob.NewFake(c, l)
+ ref := running(t, f, fakeSpec("a1"))
+ c.AdvanceMono(10 * time.Minute)
+ if err := f.Suspend(ctx, ref); err != nil {
+ t.Fatal(err)
+ }
+ f.Tick()
+ c.AdvanceMono(2 * time.Hour)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateSuspended)
+ if err := f.Resume(ctx, ref); err != nil {
+ t.Fatal(err)
+ }
+ c.AdvanceMono(49 * time.Minute)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ c.AdvanceMono(time.Minute)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateStopping)
+ })
+}
+
+func TestFakeLifecycle(t *testing.T) {
+ ctx := context.Background()
+ t.Run("states step on tick", func(t *testing.T) {
+ f, _ := newFake(t)
+ ref := mustLaunch(t, f, fakeSpec("a1"))
+ wantState(t, f, ref, isolatedjob.StateStarting)
+ if err := f.Suspend(ctx, ref); !errors.Is(err, isolatedjob.ErrConflict) {
+ t.Fatalf("Suspend while starting = %v, want ErrConflict", err)
+ }
+ if err := f.Resume(ctx, ref); !errors.Is(err, isolatedjob.ErrConflict) {
+ t.Fatalf("Resume while starting = %v, want ErrConflict", err)
+ }
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ if err := f.Suspend(ctx, ref); err != nil {
+ t.Fatal(err)
+ }
+ wantState(t, f, ref, isolatedjob.StateSuspending)
+ if err := f.Suspend(ctx, ref); !errors.Is(err, isolatedjob.ErrConflict) {
+ t.Fatalf("Suspend while suspending = %v, want ErrConflict", err)
+ }
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateSuspended)
+ if err := f.Resume(ctx, ref); err != nil {
+ t.Fatal(err)
+ }
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ if err := f.Stop(ctx, ref, "done"); err != nil {
+ t.Fatal(err)
+ }
+ wantState(t, f, ref, isolatedjob.StateStopping)
+ if err := f.Resume(ctx, ref); !errors.Is(err, isolatedjob.ErrConflict) {
+ t.Fatalf("Resume while stopping = %v, want ErrConflict", err)
+ }
+ f.Tick()
+ if job := mustGet(t, f, ref); job.State != isolatedjob.StateStopped || job.Reason != "done" {
+ t.Fatalf("Get after stop = %+v, want stopped with reason done", job)
+ }
+ for _, call := range []func(context.Context, isolatedjob.Ref) error{f.Suspend, f.Resume} {
+ if err := call(ctx, "vm-missing"); !errors.Is(err, isolatedjob.ErrNotFound) {
+ t.Fatalf("Suspend or Resume of an unknown ref = %v, want ErrNotFound", err)
+ }
+ }
+ if _, err := f.Get(ctx, "vm-missing"); !errors.Is(err, isolatedjob.ErrNotFound) {
+ t.Fatalf("Get of an unknown ref = %v, want ErrNotFound", err)
+ }
+ })
+ t.Run("launch replays after stop and refuses bad specs", func(t *testing.T) {
+ f, _ := newFake(t)
+ ref := mustLaunch(t, f, fakeSpec("a1"))
+ if err := f.Stop(ctx, ref, "x"); err != nil {
+ t.Fatal(err)
+ }
+ f.Tick()
+ if again := mustLaunch(t, f, fakeSpec("a1")); again != ref {
+ t.Fatalf("Launch after stop = %s, want the stopped VM %s (client token replay)", again, ref)
+ }
+ bad := fakeSpec("a2")
+ bad.Size = "medium"
+ if _, err := f.Launch(ctx, bad); !errors.Is(err, isolatedjob.ErrInvalid) {
+ t.Fatalf("Launch with a bad size = %v, want ErrInvalid", err)
+ }
+ if jobs, _ := f.List(ctx); len(jobs) != 1 {
+ t.Fatalf("List = %v, want only the first VM", jobs)
+ }
+ })
+ t.Run("times come from the clock", func(t *testing.T) {
+ f, c := newFake(t)
+ ref := mustLaunch(t, f, fakeSpec("a1"))
+ c.SetWall(fakeStart.Add(-24 * time.Hour))
+ c.AdvanceMono(90 * time.Second)
+ job := mustGet(t, f, ref)
+ if !job.StartedAt.Equal(fakeStart) || job.ProviderAge != 90*time.Second || !job.AgeKnown {
+ t.Fatalf("Get = %+v, want StartedAt %v, ProviderAge 90s, AgeKnown", job, fakeStart)
+ }
+ })
+ t.Run("backstop off keeps the VM", func(t *testing.T) {
+ f, c := newFake(t)
+ f.SetBackstop(false)
+ ref := running(t, f, fakeSpec("a1"))
+ c.AdvanceMono(2 * time.Hour)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateRunning)
+ f.SetBackstop(true)
+ f.Tick()
+ wantState(t, f, ref, isolatedjob.StateStopping)
+ })
+ t.Run("plant, live count and stops issued", func(t *testing.T) {
+ f, _ := newFake(t)
+ orphan := f.Plant(fakeSpec("a1"))
+ wantState(t, f, orphan, isolatedjob.StateRunning)
+ other := mustLaunch(t, f, fakeSpec("a2"))
+ if live := f.LiveByAttempt(); len(live) != 2 || live["a1"] != 1 || live["a2"] != 1 {
+ t.Fatalf("LiveByAttempt = %v, want a1:1 a2:1", live)
+ }
+ for _, r := range []isolatedjob.Ref{orphan, "vm-missing", orphan} {
+ if err := f.Stop(ctx, r, "reap"); err != nil {
+ t.Fatalf("Stop(%s) = %v", r, err)
+ }
+ }
+ want := []isolatedjob.Ref{orphan, "vm-missing", orphan}
+ if got := f.StopsIssued(); !slices.Equal(got, want) {
+ t.Fatalf("StopsIssued = %v, want %v", got, want)
+ }
+ f.Tick()
+ if live := f.LiveByAttempt(); len(live) != 1 || live["a2"] != 1 {
+ t.Fatalf("LiveByAttempt after the reap = %v, want a2:1 (%s)", live, other)
+ }
+ })
+ t.Run("network audit", func(t *testing.T) {
+ f, _ := newFake(t)
+ a, err := f.AuditNetwork(ctx)
+ if err != nil || a.OK(nil) != nil {
+ t.Fatalf("default AuditNetwork = (%+v, %v), want a passing audit", a, err)
+ }
+ set := isolatedjob.NetworkAudit{EgressOnly: []netip.AddrPort{netip.MustParseAddrPort("10.0.0.1:3128")}}
+ boom := errors.New("describe failed")
+ f.SetAudit(set, boom)
+ a, err = f.AuditNetwork(ctx)
+ if !errors.Is(err, boom) || len(a.EgressOnly) != 1 {
+ t.Fatalf("AuditNetwork after SetAudit = (%+v, %v)", a, err)
+ }
+ })
+ t.Run("concurrent launches of one attempt", func(t *testing.T) {
+ f, _ := newFake(t)
+ refs := make([]isolatedjob.Ref, 20)
+ var wg sync.WaitGroup
+ for i := range refs {
+ wg.Go(func() {
+ ref, err := f.Launch(ctx, fakeSpec("a1"))
+ if err != nil {
+ t.Errorf("Launch = %v", err)
+ }
+ refs[i] = ref
+ })
+ }
+ wg.Wait()
+ if live := f.LiveByAttempt(); live["a1"] != 1 {
+ t.Fatalf("LiveByAttempt = %v, want a1:1", live)
+ }
+ for _, r := range refs {
+ if r != refs[0] {
+ t.Fatalf("refs = %v, want all the same", refs)
+ }
+ }
+ })
+ t.Run("inject refuses a fault the op cannot have", func(t *testing.T) {
+ f, _ := newFake(t)
+ defer func() {
+ if recover() == nil {
+ t.Fatal("Inject(OpGet, FaultIncompleteList) did not panic")
+ }
+ }()
+ f.Inject(isolatedjob.OpGet, isolatedjob.FaultIncompleteList)
+ })
+ t.Run("limits as the spike found", func(t *testing.T) {
+ want := isolatedjob.Limits{MaxLifetime: 28800 * time.Second, MaxBootstrapBytes: 4096, SuspendUsesLifetime: true}
+ if got := isolatedjob.SpikeLimits(); got != want {
+ t.Fatalf("SpikeLimits = %+v, want %+v", got, want)
+ }
+ f, _ := newFake(t)
+ if f.Limits() != want {
+ t.Fatalf("Limits = %+v, want %+v", f.Limits(), want)
+ }
+ })
+}
diff --git a/internal/isolatedjob/isolatedjobtest/clock.go b/internal/isolatedjob/isolatedjobtest/clock.go
new file mode 100644
index 00000000..5992f92a
--- /dev/null
+++ b/internal/isolatedjob/isolatedjobtest/clock.go
@@ -0,0 +1,56 @@
+// Package isolatedjobtest holds test helpers for isolatedjob: a clock a test
+// moves by hand and the contract suite every Runner must pass.
+package isolatedjobtest
+
+import (
+ "fmt"
+ "sync"
+ "time"
+)
+
+// FakeClock is an isolatedjob.Clock that moves only when a test moves it.
+// Wall and Mono are set separately, so a test can move the calendar time back
+// while elapsed time moves forward. It is safe for concurrent use.
+type FakeClock struct {
+ mu sync.Mutex
+ wall time.Time
+ mono time.Duration
+}
+
+// NewFakeClock returns a clock reading wall, with Mono at zero.
+func NewFakeClock(wall time.Time) *FakeClock {
+ return &FakeClock{wall: wall}
+}
+
+// Wall returns the calendar time last set.
+func (c *FakeClock) Wall() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.wall
+}
+
+// Mono returns the elapsed time so far.
+func (c *FakeClock) Mono() time.Duration {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.mono
+}
+
+// SetWall sets the calendar time to any value, earlier or later. Mono does
+// not move.
+func (c *FakeClock) SetWall(t time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.wall = t
+}
+
+// AdvanceMono moves elapsed time forward by d. Elapsed time never goes back,
+// so a negative d panics. Wall does not move.
+func (c *FakeClock) AdvanceMono(d time.Duration) {
+ if d < 0 {
+ panic(fmt.Sprintf("isolatedjobtest: AdvanceMono(%v): elapsed time never goes back", d))
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.mono += d
+}
diff --git a/internal/isolatedjob/isolatedjobtest/contract.go b/internal/isolatedjob/isolatedjobtest/contract.go
new file mode 100644
index 00000000..094689ed
--- /dev/null
+++ b/internal/isolatedjob/isolatedjobtest/contract.go
@@ -0,0 +1,223 @@
+package isolatedjobtest
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "slices"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// Harness is what Contract needs from one Runner implementation.
+type Harness struct {
+ Runner isolatedjob.Runner
+ // Image is a certified image the runner can launch.
+ Image isolatedjob.ImageDigest
+ // Settle waits until the VM's state satisfies want and returns the job
+ // as last read. It returns an error when the VM cannot be read (which
+ // may wrap isolatedjob.ErrNotFound) or when the state does not arrive in
+ // the implementation's own time bound.
+ Settle func(ctx context.Context, ref isolatedjob.Ref, want func(isolatedjob.State) bool) (isolatedjob.Job, error)
+}
+
+// contractLifetime keeps VMs launched by a live run short.
+const contractLifetime = 15 * time.Minute
+
+// Contract checks the behaviour every Runner must share. It uses only the
+// Runner interface and h.Settle, so it runs against the fake and, behind the
+// hostedlive build tag, against a real provider. Each subtest stops the VMs it
+// launched. Attempt IDs carry a random part, so a second run against a
+// provider that remembers client tokens does not get the first run's VMs.
+func Contract(t *testing.T, h Harness) {
+ t.Helper()
+ run := randomHex(t, 6)
+ n := 0
+ attempt := func() string {
+ n++
+ return fmt.Sprintf("contract-%s-%d", run, n)
+ }
+ spec := func() isolatedjob.LaunchSpec {
+ return isolatedjob.LaunchSpec{
+ AttemptID: attempt(),
+ Image: h.Image,
+ Size: isolatedjob.SizeSmall,
+ MaxLifetime: min(contractLifetime, h.Runner.Limits().MaxLifetime),
+ Bootstrap: []byte("contract-bootstrap"),
+ }
+ }
+ launch := func(t *testing.T, s isolatedjob.LaunchSpec) isolatedjob.Ref {
+ t.Helper()
+ ref, err := h.Runner.Launch(context.Background(), s)
+ if err != nil {
+ t.Fatalf("Launch(%s) = %v, want a ref", s.AttemptID, err)
+ }
+ t.Cleanup(func() {
+ if err := h.Runner.Stop(context.Background(), ref, "contract cleanup"); err != nil {
+ t.Errorf("cleanup Stop(%s) = %v", ref, err)
+ }
+ })
+ return ref
+ }
+ settle := func(t *testing.T, ref isolatedjob.Ref, want isolatedjob.State) isolatedjob.Job {
+ t.Helper()
+ job, err := h.Settle(context.Background(), ref, func(s isolatedjob.State) bool { return s == want })
+ if err != nil {
+ t.Fatalf("Settle(%s, %s) = %v", ref, want, err)
+ }
+ return job
+ }
+
+ t.Run("LaunchIdempotentOnAttempt", func(t *testing.T) {
+ s := spec()
+ first := launch(t, s)
+ again, err := h.Runner.Launch(context.Background(), s)
+ if err != nil {
+ t.Fatalf("second Launch(%s) = %v, want the first ref", s.AttemptID, err)
+ }
+ if again != first {
+ t.Fatalf("second Launch(%s) = %s, want %s: one attempt must be one VM", s.AttemptID, again, first)
+ }
+ job, err := h.Runner.Get(context.Background(), first)
+ if err != nil {
+ t.Fatalf("Get(%s) = %v", first, err)
+ }
+ if !job.State.Live() {
+ t.Fatalf("Get(%s).State = %s, want a live state", first, job.State)
+ }
+ })
+
+ t.Run("ChangedSpecConflicts", func(t *testing.T) {
+ s := spec()
+ first := launch(t, s)
+ changed := s
+ changed.Bootstrap = []byte("another-bootstrap")
+ ref, err := h.Runner.Launch(context.Background(), changed)
+ if !errors.Is(err, isolatedjob.ErrConflict) {
+ t.Fatalf("Launch with the same attempt and a new bootstrap = (%q, %v), want ErrConflict", ref, err)
+ }
+ if ref == first {
+ t.Fatalf("Launch with a changed spec returned the first VM %s", first)
+ }
+ })
+
+ t.Run("StopTwice", func(t *testing.T) {
+ ref := launch(t, spec())
+ for i := 1; i <= 2; i++ {
+ if err := h.Runner.Stop(context.Background(), ref, "contract stop twice"); err != nil {
+ t.Fatalf("Stop %d of %s = %v, want nil", i, ref, err)
+ }
+ }
+ })
+
+ t.Run("StopUnknownRef", func(t *testing.T) {
+ ref := isolatedjob.Ref("contract-never-launched-" + run)
+ if err := h.Runner.Stop(context.Background(), ref, "contract unknown ref"); err != nil {
+ t.Fatalf("Stop(%s) of a ref the provider never held = %v, want nil", ref, err)
+ }
+ })
+
+ t.Run("GetAfterStop", func(t *testing.T) {
+ ref := launch(t, spec())
+ if err := h.Runner.Stop(context.Background(), ref, "contract get after stop"); err != nil {
+ t.Fatalf("Stop(%s) = %v", ref, err)
+ }
+ _, err := h.Settle(context.Background(), ref, isolatedjob.State.Terminal)
+ if err != nil && !errors.Is(err, isolatedjob.ErrNotFound) {
+ t.Fatalf("Settle(%s, terminal) = %v, want a terminal state or ErrNotFound", ref, err)
+ }
+ job, err := h.Runner.Get(context.Background(), ref)
+ switch {
+ case errors.Is(err, isolatedjob.ErrNotFound):
+ case err != nil:
+ t.Fatalf("Get(%s) after stop = %v, want a terminal state or ErrNotFound", ref, err)
+ case !job.State.Terminal():
+ t.Fatalf("Get(%s) after stop = %s, want a terminal state or ErrNotFound, never %s", ref, job.State, isolatedjob.StateUnknown)
+ }
+ })
+
+ t.Run("SuspendResumeRoundTrip", func(t *testing.T) {
+ ref := launch(t, spec())
+ settle(t, ref, isolatedjob.StateRunning)
+ if err := h.Runner.Suspend(context.Background(), ref); err != nil {
+ t.Fatalf("Suspend(%s) = %v", ref, err)
+ }
+ settle(t, ref, isolatedjob.StateSuspended)
+ if err := h.Runner.Resume(context.Background(), ref); err != nil {
+ t.Fatalf("Resume(%s) = %v", ref, err)
+ }
+ settle(t, ref, isolatedjob.StateRunning)
+ })
+
+ t.Run("ResumeRunningIsNoop", func(t *testing.T) {
+ ref := launch(t, spec())
+ settle(t, ref, isolatedjob.StateRunning)
+ if err := h.Runner.Resume(context.Background(), ref); err != nil {
+ t.Fatalf("Resume(%s) of a running VM = %v, want nil", ref, err)
+ }
+ job, err := h.Runner.Get(context.Background(), ref)
+ if err != nil {
+ t.Fatalf("Get(%s) = %v", ref, err)
+ }
+ if job.State != isolatedjob.StateRunning {
+ t.Fatalf("Get(%s).State after a no-op resume = %s, want %s", ref, job.State, isolatedjob.StateRunning)
+ }
+ })
+
+ t.Run("OversizeBootstrapRefusedBeforeProvider", func(t *testing.T) {
+ before := listRefs(t, h.Runner)
+ s := spec()
+ s.Bootstrap = make([]byte, h.Runner.Limits().MaxBootstrapBytes+1)
+ for i := range s.Bootstrap {
+ s.Bootstrap[i] = 'x'
+ }
+ ref, err := h.Runner.Launch(context.Background(), s)
+ if ref != "" {
+ t.Cleanup(func() { _ = h.Runner.Stop(context.Background(), ref, "contract cleanup") })
+ }
+ if !errors.Is(err, isolatedjob.ErrBootstrapTooLarge) {
+ t.Fatalf("Launch with a %d-byte bootstrap = (%q, %v), want ErrBootstrapTooLarge", len(s.Bootstrap), ref, err)
+ }
+ for _, r := range listRefs(t, h.Runner) {
+ if !slices.Contains(before, r) {
+ t.Fatalf("List after a refused launch holds new VM %s; the refusal must come before the provider", r)
+ }
+ }
+ })
+
+ t.Run("LimitsAreSane", func(t *testing.T) {
+ l := h.Runner.Limits()
+ if l.MaxLifetime <= 0 || l.MaxLifetime > isolatedjob.HardMaxLifetime {
+ t.Errorf("Limits().MaxLifetime = %v, want above zero and at most %v", l.MaxLifetime, isolatedjob.HardMaxLifetime)
+ }
+ if l.MaxBootstrapBytes <= 0 {
+ t.Errorf("Limits().MaxBootstrapBytes = %d, want above zero", l.MaxBootstrapBytes)
+ }
+ })
+}
+
+func listRefs(t *testing.T, r isolatedjob.Runner) []isolatedjob.Ref {
+ t.Helper()
+ jobs, err := r.List(context.Background())
+ if err != nil {
+ t.Fatalf("List = %v", err)
+ }
+ refs := make([]isolatedjob.Ref, 0, len(jobs))
+ for _, j := range jobs {
+ refs = append(refs, j.Ref)
+ }
+ return refs
+}
+
+func randomHex(t *testing.T, n int) string {
+ t.Helper()
+ b := make([]byte, n)
+ if _, err := rand.Read(b); err != nil {
+ t.Fatalf("random attempt id: %v", err)
+ }
+ return hex.EncodeToString(b)
+}