oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "context"
5 "encoding/json"
6 "io"
7 "os"
8 "path/filepath"
9 "sync/atomic"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/runner/containment"
14 "amadan.net/oficina/equipo/internal/runner/provider"
15 "amadan.net/oficina/equipo/internal/runnerproto"
16)
17
18func TestDirectBugWorkflow(t *testing.T) { runDirectBugGraph(t) }
19
20func directNamespaceFixture(t *testing.T) (*Supervisor, *attemptState, *containment.Manager, provider.ProcessHost, provider.Launch) {
21 t.Helper()
22 s, r, _, _ := cleanupFixture(t)
23 r.Direct = true
24 r.Claim.Assignment.TaskID = "task"
25 r.Owner = ProcessOwner{}
26 r.Proof = nil
27 scratch := filepath.Join(t.TempDir(), "scratch")
28 mustJournal(t, os.Mkdir(scratch, 0700))
29 work := t.TempDir()
30 mods := t.TempDir()
31 binary, err := filepath.EvalSymlinks("/usr/bin/python3")
32 mustJournal(t, err)
33 helper, err := os.Executable()
34 mustJournal(t, err)
35 m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch})
36 mustJournal(t, err)
37 s.namespaces = m
38 _, err = s.journal.ReconcileDirect(context.Background(), m)
39 mustJournal(t, err)
40 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"}
41 argv := []string{"/opt/codex", "-u", "-c", `import os,time
42for name in ['model','code-mode-host','relay','mcp','check']:
43 if os.fork()==0:
44 os.setsid()
45 time.sleep(60)
46 os._exit(0)
47print('ready',flush=True)
48time.sleep(60)`}
49 p, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: work, Binary: binary, RunnerBinary: helper, Bwrap: "/usr/bin/bwrap", GoRoot: mods, ModuleCache: mods, Argv: argv, Env: env})
50 mustJournal(t, err)
51 return s, r, m, NewDirectHost(s.journal, m), provider.Launch{AttemptKey: "model-fixture", Workspace: work, Policy: p}
52}
53
54func TestDirectCancelWaitsForNamespaces(t *testing.T) {
55 s, r, m, host, l := directNamespaceFixture(t)
56 ctx, cancel := context.WithCancel(context.Background())
57 defer cancel()
58 ctx = s.namespaceContext(ctx, r)
59 p, err := host.Start(ctx, l, []string{"/opt/codex", "-u", "-c", `import os,time
60for name in ['model','code-mode-host','relay','mcp','check']:
61 if os.fork()==0:
62 os.setsid()
63 time.sleep(60)
64 os._exit(0)
65print('ready',flush=True)
66time.sleep(60)`})
67 mustJournal(t, err)
68 t.Cleanup(func() {
69 m.Stop(context.Background(), p.ID())
70 p.Stdout().Close()
71 p.Stderr().Close()
72 p.Stdin().Close()
73 })
74 var manifest struct{ Argv []string }
75 mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
76 l.AttemptKey = "check-fixture"
77 check, err := host.Start(ctx, l, manifest.Argv)
78 mustJournal(t, err)
79 t.Cleanup(func() {
80 m.Stop(context.Background(), check.ID())
81 check.Stdout().Close()
82 check.Stderr().Close()
83 check.Stdin().Close()
84 })
85 b := make([]byte, 6)
86 _, err = io.ReadFull(p.Stdout(), b)
87 mustJournal(t, err)
88 if string(b) != "ready\n" {
89 t.Fatal("fixture did not launch")
90 }
91 if r.Phase == "contained" {
92 t.Fatal("capacity released on launch")
93 }
94 proof, err := s.cleanup(context.Background(), r)
95 mustJournal(t, err)
96 if proof.Version != 2 || len(proof.Namespaces) != 2 || r.Phase != "contained" {
97 t.Fatalf("missing namespace proof: %+v", proof)
98 }
99 if _, err = p.Wait(context.Background()); err != nil {
100 t.Fatal(err)
101 }
102}
103
104func TestDirectBugLaunchAdmission(t *testing.T) {
105 s, r, m, host, l := directNamespaceFixture(t)
106 s.api = &supervisorAPI{order: new([]string), fail: true}
107 ctx, cancel := context.WithTimeout(s.namespaceContext(context.Background(), r), time.Second)
108 defer cancel()
109 var manifest struct{ Argv []string }
110 if err := json.Unmarshal(l.Policy.Manifest, &manifest); err != nil {
111 t.Fatal(err)
112 }
113 if _, err := host.Start(ctx, l, manifest.Argv); err == nil {
114 t.Fatal("namespace ran without launch ACK")
115 }
116 records, err := m.Records(context.Background())
117 mustJournal(t, err)
118 for _, record := range records {
119 proof, err := m.Recover(context.Background(), record)
120 if err != nil || !proof.Verified {
121 t.Fatalf("refused launch not contained: %v", err)
122 }
123 }
124}
125
126func TestDirectRestartAndLeaseLossLiveCapture(t *testing.T) {
127 j, l, _, p := directFixture(t, "codex")
128 reader, writer := io.Pipe()
129 p.out = reader
130 defer writer.Close()
131 ctx, cancel := context.WithCancel(context.Background())
132 defer cancel()
133 c, err := NewCaptureFactory(j).Open(ctx, p, l)
134 mustJournal(t, err)
135 if _, err = j.RecoverDirect(context.Background()); err == nil {
136 t.Fatal("recovery admitted while capture was live")
137 }
138 cancel()
139 <-c.Done
140 if _, err = j.RecoverDirect(context.Background()); err != nil {
141 t.Fatal(err)
142 }
143}
144
145func TestDirectCancelWaitsForNamespacesUnproven(t *testing.T) {
146 s, r, _, _, _ := directNamespaceFixture(t)
147 n := namespaceState{Owner: attemptKey(r.Claim.Scope, r.Claim.Handle), Record: containment.Record{ID: "missing", AttemptKey: "check-missing"}}
148 mustJournal(t, s.journal.saveState(context.Background(), "namespace", "missing", n))
149 if _, err := s.cleanup(context.Background(), r); err == nil || r.Phase == "contained" {
150 t.Fatal("unproven check namespace released capacity")
151 }
152}
153
154func TestDirectRestartAndLeaseLoss(t *testing.T) {
155 for _, kind := range []string{"rollback", "suspend", "membership", "connection"} {
156 t.Run(kind, func(t *testing.T) {
157 s, r, m, host, l := directNamespaceFixture(t)
158 ctx, cancel := context.WithCancelCause(s.namespaceContext(context.Background(), r))
159 defer cancel(nil)
160 var manifest struct{ Argv []string }
161 mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
162 p, err := host.Start(ctx, l, manifest.Argv)
163 mustJournal(t, err)
164 t.Cleanup(func() {
165 m.Stop(context.Background(), p.ID())
166 p.Stdout().Close()
167 p.Stderr().Close()
168 p.Stdin().Close()
169 })
170 b := make([]byte, 6)
171 _, err = io.ReadFull(p.Stdout(), b)
172 mustJournal(t, err)
173 now := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"}
174 lease, err := newLease(now, now.Wall.Add(time.Minute), now.Wall.Add(5*time.Minute))
175 mustJournal(t, err)
176 var reads atomic.Int32
177 s.clock = clockFuncR3(func() (ClockReading, error) {
178 v := now
179 if reads.Add(1) > 1 {
180 switch kind {
181 case "rollback":
182 v.Wall = v.Wall.Add(-time.Second)
183 case "suspend":
184 v.Elapsed += time.Minute
185 default:
186 v.Elapsed += 16 * time.Second
187 v.Wall = v.Wall.Add(16 * time.Second)
188 }
189 }
190 return v, nil
191 })
192 s.api = apiFuncR3(func(_ context.Context, _ string, _ runnerproto.RunnerRequest, out any) error {
193 if kind == "membership" {
194 return provider.ErrIdentity
195 }
196 *out.(*time.Time) = now.Wall.Add(time.Minute)
197 return nil
198 })
199 s.activeCurrent = func(context.Context) error {
200 if kind == "connection" {
201 return provider.ErrIdentity
202 }
203 return nil
204 }
205 done := make(chan struct{})
206 go s.watchLease(ctx, cancel, r, lease, done)
207 select {
208 case <-done:
209 case <-time.After(3 * time.Second):
210 t.Fatal("watchdog did not stop")
211 }
212 cleanup, stop := context.WithTimeout(context.Background(), 3*time.Second)
213 defer stop()
214 if _, err = p.Wait(cleanup); err != nil {
215 t.Fatalf("namespace survived authority loss: %v", err)
216 }
217 proof, err := m.Stop(cleanup, p.ID())
218 if err != nil || !proof.Verified {
219 t.Fatalf("no namespace proof: %v", err)
220 }
221 })
222 }
223}
224
225func TestDirectUnacknowledgedNamespace(t *testing.T) {
226 for _, kind := range []string{"crash-before-upload", "stop-race"} {
227 t.Run(kind, func(t *testing.T) {
228 s, r, _, host, l := directNamespaceFixture(t)
229 mustJournal(t, s.save(context.Background(), r))
230 s.api = apiFuncR3(func(context.Context, string, runnerproto.RunnerRequest, any) error { return ErrNotClaimed })
231 var manifest struct{ Argv []string }
232 mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
233 if _, err := host.Start(s.namespaceContext(context.Background(), r), l, manifest.Argv); err == nil {
234 t.Fatal("unacknowledged launch ran")
235 }
236 if kind == "crash-before-upload" {
237 _, err := s.journal.db.Exec("DELETE FROM journal_events")
238 mustJournal(t, err)
239 }
240 s.api = apiFuncR3(func(_ context.Context, op string, q runnerproto.RunnerRequest, out any) error {
241 if op == "events" {
242 return ErrNotClaimed
243 }
244 if op == "contained" {
245 var proof ContainmentProof
246 mustJournal(t, json.Unmarshal(q.Proof, &proof))
247 if len(proof.Namespaces) != 0 {
248 t.Fatal("unacknowledged namespace reported as started")
249 }
250 }
251 return nil
252 })
253 mustJournal(t, s.Recover(context.Background()))
254 pending, err := s.journal.Pending(context.Background(), 128)
255 mustJournal(t, err)
256 if len(pending) != 0 {
257 t.Fatal("rejected launch kept pending")
258 }
259 })
260 }
261}
262