oficina / equipo Public

hostedclient: a hostedlive driver for the Task 17 sequence

TestLiveControllerSequence drives one Small VM through a running
controller with the instance client: launch, running, drain, quiescent,
suspend, suspended, resume (epoch and timings logged), running, stop
with proof. TestLiveCrashRecovery is the two-step check for a controller
killed between the provider call and transaction 2: launch against the
crash build, then after a restart one VM for the attempt in GET /v1/vms
and a stop with proof. Both run only with -tags hostedlive and the
EQUIPO_HOSTED_LIVE_* environment; neither has been run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1ebf6e6191cb5d5914b63b32299f8f600072724a parent d94d745
2 files changed, +406 −0
  • docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md +11 −0
  • internal/hostedclient/live_test.go +395 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
index 7b77a3f9..8b5dfc97 100644
--- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
@@ -1037,3 +1037,14 @@ Offline preparation for the live check; no AWS call was made. The live pieces co
| --- | --- | --- | --- |
| Remove the visibility wait (`appear` not called in the contract's `launch`) | `go test ./internal/isolatedjob -run 'TestFakeContract' -count=1` | `contract.go:151: Get(vm-0001) = isolatedjob: not found: vm-0001 is not visible yet` | yes, passes |
| Drop the per-call deadline (`call` returns `context.WithCancel`) | same | `fake_test.go:136: contract made 19 Get or List calls without a deadline (0 with one), want none without` | yes, passes |
+
+### The hostedclient live driver
+
+- `internal/hostedclient/live_test.go` (`hostedlive` only): `TestLiveControllerSequence` drives one
+ Small VM through a running controller (launch, running, drain, quiescent, suspend, suspended,
+ resume with its epoch, running, stop with proof) and logs every timing and the epoch;
+ `TestLiveCrashRecovery` is the two-step crash check (`launch` against a controller that exits
+ after the provider call, `recover` after a restart: one VM for the attempt in `GET /v1/vms`, then
+ stop with proof). Both skip without `EQUIPO_HOSTED_LIVE_URL` and stop their VM on failure.
+- Checks: `go vet -tags hostedlive ./internal/hostedclient`, `go vet ./internal/hostedclient`,
+ `go test ./internal/hostedclient -count=1` ok. Not run (live). No guard to mutate.
diff --git a/internal/hostedclient/live_test.go b/internal/hostedclient/live_test.go
new file mode 100644
index 00000000..1569c944
--- /dev/null
+++ b/internal/hostedclient/live_test.go
@@ -0,0 +1,395 @@
+//go:build hostedlive
+
+package hostedclient
+
+// Live drivers for Task 17. They talk to a running equipo-hosted-controller
+// through this package's client, so they launch and stop real VMs. They run
+// only by hand, with -tags hostedlive and the environment below; without
+// EQUIPO_HOSTED_LIVE_URL they skip.
+//
+// EQUIPO_HOSTED_LIVE_URL https origin of the controller, such as https://127.0.0.1:8443
+// EQUIPO_HOSTED_LIVE_CA_FILE PEM certificate the controller's TLS certificate chains to
+// EQUIPO_HOSTED_LIVE_KEY_ID the instance key's ID in the controller's verify_keys
+// EQUIPO_HOSTED_LIVE_KEY_FILE the instance key: a 32-byte ed25519 seed in standard base64
+// EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE the controller's public key: 32 bytes in standard base64
+// EQUIPO_HOSTED_LIVE_IMAGE the image digest to launch (sha256:...), in the allowlist
+//
+// TestLiveCrashRecovery also reads EQUIPO_HOSTED_LIVE_CRASH_STEP,
+// EQUIPO_HOSTED_LIVE_ATTEMPT and, for its recover step,
+// EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID and EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE.
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+const (
+ liveURLEnv = "EQUIPO_HOSTED_LIVE_URL"
+ liveCAFileEnv = "EQUIPO_HOSTED_LIVE_CA_FILE"
+ liveKeyIDEnv = "EQUIPO_HOSTED_LIVE_KEY_ID"
+ liveKeyFileEnv = "EQUIPO_HOSTED_LIVE_KEY_FILE"
+ liveCtlKeyFileEnv = "EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE"
+ liveImageEnv = "EQUIPO_HOSTED_LIVE_IMAGE"
+ liveCrashStepEnv = "EQUIPO_HOSTED_LIVE_CRASH_STEP"
+ liveAttemptEnv = "EQUIPO_HOSTED_LIVE_ATTEMPT"
+ liveOpKeyIDEnv = "EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID"
+ liveOpKeyFileEnv = "EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE"
+ liveLifetime = time.Hour
+ liveCallTimeout = 2 * time.Minute // a launch waits on the provider
+ liveStateBound = 5 * time.Minute // the controller reads VM states once per reaper pass (60 s)
+ livePoll = 5 * time.Second
+ liveCleanupStopTime = 5 * time.Minute
+)
+
+// liveEnv is a client for the controller the environment names.
+type liveEnv struct {
+ cl *Client
+ origin string
+ ctl ed25519.PublicKey
+ rt http.RoundTripper
+ image isolatedjob.ImageDigest
+}
+
+func newLiveEnv(t *testing.T) *liveEnv {
+ t.Helper()
+ origin := os.Getenv(liveURLEnv)
+ if origin == "" {
+ t.Skip(liveURLEnv + " is not set")
+ }
+ pem, err := os.ReadFile(liveNeed(t, liveCAFileEnv))
+ if err != nil {
+ t.Fatalf("CA file: %v", err)
+ }
+ pool := x509.NewCertPool()
+ if !pool.AppendCertsFromPEM(pem) {
+ t.Fatalf("%s holds no PEM certificate", liveCAFileEnv)
+ }
+ rt := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}}
+ e := &liveEnv{
+ origin: strings.TrimSuffix(origin, "/"),
+ ctl: readLivePublic(t, liveNeed(t, liveCtlKeyFileEnv)),
+ rt: rt,
+ image: isolatedjob.ImageDigest(liveNeed(t, liveImageEnv)),
+ }
+ t.Setenv(FlagEnv, "1")
+ e.cl, err = New(Config{BaseURL: origin, KeyID: hostedwire.KeyID(liveNeed(t, liveKeyIDEnv)),
+ Key: readLiveSeed(t, liveNeed(t, liveKeyFileEnv)), ControllerKey: e.ctl,
+ HTTP: &http.Client{Timeout: liveCallTimeout, Transport: rt}})
+ if err != nil {
+ t.Fatalf("hostedclient.New: %v", err)
+ }
+ return e
+}
+
+func liveNeed(t *testing.T, name string) string {
+ t.Helper()
+ v := os.Getenv(name)
+ if v == "" {
+ t.Fatalf("%s is not set", name)
+ }
+ return v
+}
+
+// readLiveSeed reads a 32-byte ed25519 seed in standard base64, the format
+// of the controller's signing_key_file.
+func readLiveSeed(t *testing.T, path string) ed25519.PrivateKey {
+ t.Helper()
+ seed := readLiveB64(t, path, ed25519.SeedSize)
+ return ed25519.NewKeyFromSeed(seed)
+}
+
+// readLivePublic reads a 32-byte ed25519 public key in standard base64, the
+// format of a verify_keys public_key.
+func readLivePublic(t *testing.T, path string) ed25519.PublicKey {
+ t.Helper()
+ return ed25519.PublicKey(readLiveB64(t, path, ed25519.PublicKeySize))
+}
+
+func readLiveB64(t *testing.T, path string, size int) []byte {
+ t.Helper()
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("key file: %v", err)
+ }
+ b, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
+ if err != nil || len(b) != size {
+ t.Fatalf("key file %s must hold %d bytes in standard base64", path, size)
+ }
+ return b
+}
+
+func liveAttempt(t *testing.T) string {
+ t.Helper()
+ if a := os.Getenv(liveAttemptEnv); a != "" {
+ return a
+ }
+ b := make([]byte, 6)
+ if _, err := rand.Read(b); err != nil {
+ t.Fatal(err)
+ }
+ return "task17-" + hex.EncodeToString(b)
+}
+
+func (e *liveEnv) launchRequest(attempt string) hostedwire.LaunchRequest {
+ return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task17-live", Account: "task17-live",
+ Image: e.image, Size: isolatedjob.SizeSmall, MaxLifetimeMS: liveLifetime.Milliseconds(),
+ InstanceCode: "task17-code-" + attempt}
+}
+
+// waitFor reads the job until done accepts its view, for at most
+// liveStateBound, and returns the view and the time taken. A job that
+// reaches stopped or abandoned without done accepting it fails the test.
+func (e *liveEnv) waitFor(t *testing.T, attempt, what string, done func(hostedwire.JobView) bool) (hostedwire.JobView, time.Duration) {
+ t.Helper()
+ start := time.Now()
+ for {
+ v, err := e.cl.Get(context.Background(), attempt)
+ if err != nil {
+ t.Fatalf("Get(%s) while waiting for %s: %v", attempt, what, err)
+ }
+ if done(v) {
+ return v, time.Since(start)
+ }
+ if v.State == "stopped" || v.State == "abandoned" {
+ t.Fatalf("job %s is %s while waiting for %s", attempt, v.State, what)
+ }
+ if time.Since(start) > liveStateBound {
+ t.Fatalf("job %s still %s after %v, want %s", attempt, v.State, liveStateBound, what)
+ }
+ time.Sleep(livePoll)
+ }
+}
+
+func stateIs(s string) func(hostedwire.JobView) bool {
+ return func(v hostedwire.JobView) bool { return v.State == s }
+}
+
+// stopUntilProof asks for a stop until the controller has proof, for at
+// most bound, and returns the proof, the calls made and the time taken.
+func (e *liveEnv) stopUntilProof(attempt, reason string, bound time.Duration) (hostedwire.StopProof, int, time.Duration, error) {
+ start := time.Now()
+ for calls := 1; ; calls++ {
+ proof, err := e.cl.Stop(context.Background(), attempt, reason)
+ if err == nil {
+ return proof, calls, time.Since(start), nil
+ }
+ if !errors.Is(err, ErrStopPending) && !errors.Is(err, ErrThrottled) || time.Since(start) > bound {
+ return proof, calls, time.Since(start), err
+ }
+ time.Sleep(livePoll)
+ }
+}
+
+// stopOnFailure stops attempt's VM if the test ends without proof.
+func (e *liveEnv) stopOnFailure(t *testing.T, attempt string, proven *bool) {
+ t.Cleanup(func() {
+ if *proven {
+ return
+ }
+ proof, calls, took, err := e.stopUntilProof(attempt, "task17 cleanup", liveCleanupStopTime)
+ if err != nil {
+ t.Errorf("cleanup stop of %s after %d calls and %v: %v; check the provider for a VM left running", attempt, calls, took, err)
+ return
+ }
+ t.Logf("cleanup stop of %s: proof %s %s", attempt, proof.VMRef, proof.State)
+ })
+}
+
+// TestLiveControllerSequence drives one Small VM through the controller:
+// launch, running, drain, quiescent, suspend, suspended, resume, running,
+// stop with proof. It logs each timing and the epoch.
+func TestLiveControllerSequence(t *testing.T) {
+ e := newLiveEnv(t)
+ ctx := context.Background()
+ attempt := liveAttempt(t)
+ t.Logf("attempt %s, image %s, size small", attempt, e.image)
+ proven := false
+ e.stopOnFailure(t, attempt, &proven)
+
+ start := time.Now()
+ view, err := e.cl.Launch(ctx, e.launchRequest(attempt))
+ launchCall := time.Since(start)
+ if err != nil {
+ t.Fatalf("Launch(%s) after %v: %v", attempt, launchCall, err)
+ }
+ t.Logf("launch: call %v, state %s, vm %s, epoch %d", launchCall, view.State, view.VMRef, view.Epoch)
+ running, toRunning := e.waitFor(t, attempt, "running", stateIs("running"))
+ t.Logf("running: %v after the launch call returned; vm %s, epoch %d", toRunning, running.VMRef, running.Epoch)
+
+ start = time.Now()
+ gen, err := e.cl.Drain(ctx, attempt)
+ drainCall := time.Since(start)
+ if err != nil {
+ t.Fatalf("Drain: %v", err)
+ }
+ start = time.Now()
+ if err := e.cl.Quiescent(ctx, attempt, gen); err != nil {
+ t.Fatalf("Quiescent(%d): %v", gen, err)
+ }
+ quiescentCall := time.Since(start)
+ start = time.Now()
+ if err := e.cl.Suspend(ctx, attempt, gen); err != nil {
+ t.Fatalf("Suspend(%d): %v", gen, err)
+ }
+ suspendCall := time.Since(start)
+ t.Logf("pause: generation %d, drain call %v, quiescent call %v, suspend call %v", gen, drainCall, quiescentCall, suspendCall)
+ _, toSuspended := e.waitFor(t, attempt, "suspended", stateIs("suspended"))
+ t.Logf("suspended: %v after the suspend call returned", toSuspended)
+
+ opID := "resume-" + attempt
+ start = time.Now()
+ var epoch int64
+ resumeCalls := 0
+ for {
+ resumeCalls++
+ epoch, err = e.cl.Resume(ctx, attempt, opID)
+ if err == nil {
+ break
+ }
+ if !errors.Is(err, ErrResumePending) || time.Since(start) > liveStateBound {
+ t.Fatalf("Resume(%s) call %d after %v: %v", opID, resumeCalls, time.Since(start), err)
+ }
+ time.Sleep(livePoll)
+ }
+ resumeTook := time.Since(start)
+ t.Logf("resume: epoch %d (was %d), %d calls, %v from the first call to the epoch", epoch, running.Epoch, resumeCalls, resumeTook)
+ after, toRunningAgain := e.waitFor(t, attempt, "running after resume", stateIs("running"))
+ if after.Epoch != epoch {
+ t.Errorf("job epoch after resume = %d, want %d", after.Epoch, epoch)
+ }
+ t.Logf("running after resume: %v after the epoch came back", toRunningAgain)
+
+ proof, stopCalls, stopTook, err := e.stopUntilProof(attempt, "task17 done", liveStateBound)
+ if err != nil {
+ t.Fatalf("Stop(%s) after %d calls and %v: %v", attempt, stopCalls, stopTook, err)
+ }
+ proven = true
+ t.Logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, stopCalls, stopTook)
+ t.Logf("timings: launch_call=%v to_running=%v drain_call=%v quiescent_call=%v suspend_call=%v to_suspended=%v resume=%v resume_calls=%d epoch=%d to_running_after_resume=%v stop_to_proof=%v stop_calls=%d",
+ launchCall, toRunning, drainCall, quiescentCall, suspendCall, toSuspended, resumeTook, resumeCalls, epoch, toRunningAgain, stopTook, stopCalls)
+}
+
+// TestLiveCrashRecovery is the "kill the controller between the provider
+// call and transaction 2" check, in two steps against two controller runs
+// that share one database:
+//
+// - EQUIPO_HOSTED_LIVE_CRASH_STEP=launch, against a controller built with
+// -tags hostedlive and run with EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1: the
+// launch reaches the provider, the controller exits before saving the
+// Ref, and the call fails in transport.
+// - EQUIPO_HOSTED_LIVE_CRASH_STEP=recover, after restarting the controller
+// without EQUIPO_HOSTED_CRASH_AFTER_LAUNCH: the reaper's replay claims the
+// VM, the operator's VM list shows exactly one VM for the attempt, and
+// the VM is stopped with proof.
+//
+// Both steps need the same EQUIPO_HOSTED_LIVE_ATTEMPT.
+func TestLiveCrashRecovery(t *testing.T) {
+ e := newLiveEnv(t)
+ attempt := liveNeed(t, liveAttemptEnv)
+ switch step := liveNeed(t, liveCrashStepEnv); step {
+ case "launch":
+ start := time.Now()
+ view, err := e.cl.Launch(context.Background(), e.launchRequest(attempt))
+ if err == nil {
+ t.Fatalf("Launch(%s) = %+v, nil: the controller answered; was it built with -tags hostedlive and run with EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1? Stop this VM now", attempt, view)
+ }
+ if !errors.Is(err, ErrTransport) {
+ t.Fatalf("Launch(%s) = %v, want a transport failure from the controller exiting", attempt, err)
+ }
+ t.Logf("launch: the controller went away %v into the call (%v); restart it without the crash switch and run the recover step", time.Since(start), err)
+ case "recover":
+ opID := hostedwire.KeyID(liveNeed(t, liveOpKeyIDEnv))
+ opKey := readLiveSeed(t, liveNeed(t, liveOpKeyFileEnv))
+ proven := false
+ e.stopOnFailure(t, attempt, &proven)
+ v, took := e.waitFor(t, attempt, "a saved VM ref", func(v hostedwire.JobView) bool {
+ return v.VMRef != "" && (v.State == "starting" || v.State == "running")
+ })
+ t.Logf("recover: job %s holds vm %s (%s) %v after the first read", attempt, v.VMRef, v.State, took)
+ vms := e.listVMs(t, opID, opKey)
+ mine, unowned := 0, 0
+ for _, vm := range vms {
+ t.Logf("listed vm %s state %s attempt %q", vm.VMRef, vm.State, vm.AttemptID)
+ switch {
+ case vm.AttemptID == attempt:
+ mine++
+ if vm.VMRef != v.VMRef {
+ t.Errorf("listed vm %s for %s, but the job holds %s", vm.VMRef, attempt, v.VMRef)
+ }
+ case vm.AttemptID == "" && vm.State.Live():
+ unowned++
+ }
+ }
+ if mine != 1 {
+ t.Errorf("the provider lists %d VMs for %s, want exactly 1", mine, attempt)
+ }
+ if unowned != 0 {
+ t.Errorf("the provider lists %d live VMs no job owns, want 0", unowned)
+ }
+ proof, calls, stopTook, err := e.stopUntilProof(attempt, "task17 crash check done", liveStateBound)
+ if err != nil {
+ t.Fatalf("Stop(%s) after %d calls and %v: %v", attempt, calls, stopTook, err)
+ }
+ proven = true
+ t.Logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, calls, stopTook)
+ default:
+ t.Fatalf("%s = %q, want launch or recover", liveCrashStepEnv, step)
+ }
+}
+
+// listVMs is GET /v1/vms signed with the operator key. The client has no
+// operator method, so the exchange is done here the way the client does
+// it: one RoundTrip, the answer verified against the request's nonce
+// before its status or body is used.
+func (e *liveEnv) listVMs(t *testing.T, id hostedwire.KeyID, key ed25519.PrivateKey) []hostedwire.VMView {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), liveCallTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.origin+"/v1/vms", http.NoBody)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nonce, err := hostedwire.NewNonce()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := hostedwire.SignRequest(req, nil, id, key, time.Now(), nonce); err != nil {
+ t.Fatalf("sign /v1/vms: %v", err)
+ }
+ resp, err := e.rt.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("GET /v1/vms: %v", err)
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1))
+ if err != nil {
+ t.Fatalf("GET /v1/vms body: %v", err)
+ }
+ if err := hostedwire.VerifyResponse(resp, body, nonce, e.ctl); err != nil {
+ t.Fatalf("GET /v1/vms answer does not verify: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET /v1/vms = %d %s", resp.StatusCode, body)
+ }
+ var list hostedwire.VMListResponse
+ if err := hostedwire.DecodeStrict(bytes.NewReader(body), &list); err != nil {
+ t.Fatalf("GET /v1/vms body: %v", err)
+ }
+ return list.VMs
+}