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 of a suspended VM is // accepted at once but the VM is still reported suspended until the next // Tick moves it to running, as AWS keeps a VM SUSPENDED while its /resume // hook runs; a second Resume in that window is accepted and changes nothing. // Resume of a running VM does nothing. Stop moves any live VM to stopping, // dropping a pending resume, 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 until Vanish removes them. // // 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 calls map[Op]int 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 resuming bool // Resume accepted; the next Tick moves suspended to running // vanished: the provider no longer shows the VM. The record stays so // the client token still replays to the same Ref and spec. vanished 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{}, calls: map[Op]int{}, 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() f.calls[op]++ 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.visibleLocked(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.visibleLocked(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 asks a suspended VM to resume; it reports suspended until the next // Tick. Suspended time ends when the resume is accepted. A running VM, or one // whose resume is already pending, 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.visibleLocked(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.resuming = true 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.visibleLocked(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.resuming = false 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 { if vm, ok := f.visibleLocked(ref); ok { jobs = append(jobs, f.jobLocked(vm)) } } 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, ok := f.visibleLocked(ref) if !ok { continue } switch vm.state { case StateStarting: vm.state = StateRunning case StateSuspending: vm.state = StateSuspended case StateSuspended: if vm.resuming { vm.state, vm.resuming = StateRunning, false } 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 } // visibleLocked returns the VM for ref unless the fake never held it or it // has vanished. The caller holds f.mu. func (f *Fake) visibleLocked(ref Ref) (*fakeVM, bool) { vm, ok := f.vms[ref] if !ok || vm.vanished { return nil, false } return vm, true } // Vanish makes the provider forget the VM for ref, in any state, as when a // stopped VM ages out or a VM is removed behind the controller's back. Get, // Suspend and Resume then return ErrNotFound, Stop returns nil, and List and // LiveByAttempt leave it out. It is not a Stop and is not recorded in // StopsIssued. The client token survives: a Launch replay of the same spec // still returns ref and a changed spec still conflicts. A ref the fake never // held is ignored. func (f *Fake) Vanish(ref Ref) { f.mu.Lock() defer f.mu.Unlock() if vm, ok := f.vms[ref]; ok { vm.vanished = true vm.resuming = false } } // Calls returns how many calls of op reached the fake provider: those past // spec validation and the context check, throttled ones included. func (f *Fake) Calls(op Op) int { f.mu.Lock() defer f.mu.Unlock() return f.calls[op] } // 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.vanished && 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) )