package runner import ( "context" "encoding/json" "io" "os" "path/filepath" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) func TestDirectBugWorkflow(t *testing.T) { runDirectBugGraph(t) } func directNamespaceFixture(t *testing.T) (*Supervisor, *attemptState, *containment.Manager, provider.ProcessHost, provider.Launch) { t.Helper() s, r, _, _ := cleanupFixture(t) r.Direct = true r.Claim.Assignment.TaskID = "task" r.Owner = ProcessOwner{} r.Proof = nil scratch := filepath.Join(t.TempDir(), "scratch") mustJournal(t, os.Mkdir(scratch, 0700)) work := t.TempDir() mods := t.TempDir() binary, err := filepath.EvalSymlinks("/usr/bin/python3") mustJournal(t, err) helper, err := os.Executable() mustJournal(t, err) m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch}) mustJournal(t, err) s.namespaces = m _, err = s.journal.ReconcileDirect(context.Background(), m) mustJournal(t, err) env := map[string]string{"GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"} argv := []string{"/opt/codex", "-u", "-c", `import os,time for name in ['model','code-mode-host','relay','mcp','check']: if os.fork()==0: os.setsid() time.sleep(60) os._exit(0) print('ready',flush=True) time.sleep(60)`} p, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: work, Binary: binary, RunnerBinary: helper, Bwrap: "/usr/bin/bwrap", GoRoot: mods, ModuleCache: mods, Argv: argv, Env: env}) mustJournal(t, err) return s, r, m, NewDirectHost(s.journal, m), provider.Launch{AttemptKey: "model-fixture", Workspace: work, Policy: p} } func TestDirectCancelWaitsForNamespaces(t *testing.T) { s, r, m, host, l := directNamespaceFixture(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctx = s.namespaceContext(ctx, r) p, err := host.Start(ctx, l, []string{"/opt/codex", "-u", "-c", `import os,time for name in ['model','code-mode-host','relay','mcp','check']: if os.fork()==0: os.setsid() time.sleep(60) os._exit(0) print('ready',flush=True) time.sleep(60)`}) mustJournal(t, err) t.Cleanup(func() { m.Stop(context.Background(), p.ID()) p.Stdout().Close() p.Stderr().Close() p.Stdin().Close() }) var manifest struct{ Argv []string } mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest)) l.AttemptKey = "check-fixture" check, err := host.Start(ctx, l, manifest.Argv) mustJournal(t, err) t.Cleanup(func() { m.Stop(context.Background(), check.ID()) check.Stdout().Close() check.Stderr().Close() check.Stdin().Close() }) b := make([]byte, 6) _, err = io.ReadFull(p.Stdout(), b) mustJournal(t, err) if string(b) != "ready\n" { t.Fatal("fixture did not launch") } if r.Phase == "contained" { t.Fatal("capacity released on launch") } proof, err := s.cleanup(context.Background(), r) mustJournal(t, err) if proof.Version != 2 || len(proof.Namespaces) != 2 || r.Phase != "contained" { t.Fatalf("missing namespace proof: %+v", proof) } if _, err = p.Wait(context.Background()); err != nil { t.Fatal(err) } } func TestDirectBugLaunchAdmission(t *testing.T) { s, r, m, host, l := directNamespaceFixture(t) s.api = &supervisorAPI{order: new([]string), fail: true} ctx, cancel := context.WithTimeout(s.namespaceContext(context.Background(), r), time.Second) defer cancel() var manifest struct{ Argv []string } if err := json.Unmarshal(l.Policy.Manifest, &manifest); err != nil { t.Fatal(err) } if _, err := host.Start(ctx, l, manifest.Argv); err == nil { t.Fatal("namespace ran without launch ACK") } records, err := m.Records(context.Background()) mustJournal(t, err) for _, record := range records { proof, err := m.Recover(context.Background(), record) if err != nil || !proof.Verified { t.Fatalf("refused launch not contained: %v", err) } } } func TestDirectRestartAndLeaseLossLiveCapture(t *testing.T) { j, l, _, p := directFixture(t, "codex") reader, writer := io.Pipe() p.out = reader defer writer.Close() ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := NewCaptureFactory(j).Open(ctx, p, l) mustJournal(t, err) if _, err = j.RecoverDirect(context.Background()); err == nil { t.Fatal("recovery admitted while capture was live") } cancel() <-c.Done if _, err = j.RecoverDirect(context.Background()); err != nil { t.Fatal(err) } } func TestDirectCancelWaitsForNamespacesUnproven(t *testing.T) { s, r, _, _, _ := directNamespaceFixture(t) n := namespaceState{Owner: attemptKey(r.Claim.Scope, r.Claim.Handle), Record: containment.Record{ID: "missing", AttemptKey: "check-missing"}} mustJournal(t, s.journal.saveState(context.Background(), "namespace", "missing", n)) if _, err := s.cleanup(context.Background(), r); err == nil || r.Phase == "contained" { t.Fatal("unproven check namespace released capacity") } } func TestDirectRestartAndLeaseLoss(t *testing.T) { for _, kind := range []string{"rollback", "suspend", "membership", "connection"} { t.Run(kind, func(t *testing.T) { s, r, m, host, l := directNamespaceFixture(t) ctx, cancel := context.WithCancelCause(s.namespaceContext(context.Background(), r)) defer cancel(nil) var manifest struct{ Argv []string } mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest)) p, err := host.Start(ctx, l, manifest.Argv) mustJournal(t, err) t.Cleanup(func() { m.Stop(context.Background(), p.ID()) p.Stdout().Close() p.Stderr().Close() p.Stdin().Close() }) b := make([]byte, 6) _, err = io.ReadFull(p.Stdout(), b) mustJournal(t, err) now := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"} lease, err := newLease(now, now.Wall.Add(time.Minute), now.Wall.Add(5*time.Minute)) mustJournal(t, err) var reads atomic.Int32 s.clock = clockFuncR3(func() (ClockReading, error) { v := now if reads.Add(1) > 1 { switch kind { case "rollback": v.Wall = v.Wall.Add(-time.Second) case "suspend": v.Elapsed += time.Minute default: v.Elapsed += 16 * time.Second v.Wall = v.Wall.Add(16 * time.Second) } } return v, nil }) s.api = apiFuncR3(func(_ context.Context, _ string, _ runnerproto.RunnerRequest, out any) error { if kind == "membership" { return provider.ErrIdentity } *out.(*time.Time) = now.Wall.Add(time.Minute) return nil }) s.activeCurrent = func(context.Context) error { if kind == "connection" { return provider.ErrIdentity } return nil } done := make(chan struct{}) go s.watchLease(ctx, cancel, r, lease, done) select { case <-done: case <-time.After(3 * time.Second): t.Fatal("watchdog did not stop") } cleanup, stop := context.WithTimeout(context.Background(), 3*time.Second) defer stop() if _, err = p.Wait(cleanup); err != nil { t.Fatalf("namespace survived authority loss: %v", err) } proof, err := m.Stop(cleanup, p.ID()) if err != nil || !proof.Verified { t.Fatalf("no namespace proof: %v", err) } }) } } func TestDirectUnacknowledgedNamespace(t *testing.T) { for _, kind := range []string{"crash-before-upload", "stop-race"} { t.Run(kind, func(t *testing.T) { s, r, _, host, l := directNamespaceFixture(t) mustJournal(t, s.save(context.Background(), r)) s.api = apiFuncR3(func(context.Context, string, runnerproto.RunnerRequest, any) error { return ErrNotClaimed }) var manifest struct{ Argv []string } mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest)) if _, err := host.Start(s.namespaceContext(context.Background(), r), l, manifest.Argv); err == nil { t.Fatal("unacknowledged launch ran") } if kind == "crash-before-upload" { _, err := s.journal.db.Exec("DELETE FROM journal_events") mustJournal(t, err) } s.api = apiFuncR3(func(_ context.Context, op string, q runnerproto.RunnerRequest, out any) error { if op == "events" { return ErrNotClaimed } if op == "contained" { var proof ContainmentProof mustJournal(t, json.Unmarshal(q.Proof, &proof)) if len(proof.Namespaces) != 0 { t.Fatal("unacknowledged namespace reported as started") } } return nil }) mustJournal(t, s.Recover(context.Background())) pending, err := s.journal.Pending(context.Background(), 128) mustJournal(t, err) if len(pending) != 0 { t.Fatal("rejected launch kept pending") } }) } }