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 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "sync/atomic"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/runner/containment"
18 "amadan.net/oficina/equipo/internal/runner/provider"
19)
20
21type directProcess struct {
22 writable io.WriteCloser
23 input bytes.Buffer
24 out io.ReadCloser
25 errout io.ReadCloser
26 stopped atomic.Bool
27 record containment.Record
28}
29type directInput struct{ *bytes.Buffer }
30
31func (directInput) Close() error { return nil }
32func (p *directProcess) ID() string { return p.record.ID }
33func (p *directProcess) Stdin() io.WriteCloser {
34 if p.writable != nil {
35 return p.writable
36 }
37 return directInput{&p.input}
38}
39func (p *directProcess) Stdout() io.ReadCloser { return p.out }
40func (p *directProcess) Stderr() io.ReadCloser { return p.errout }
41func (p *directProcess) Wait(context.Context) (provider.Exit, error) { return provider.Exit{}, nil }
42func (p *directProcess) Contain(context.Context) error {
43 p.stopped.Store(true)
44 p.out.Close()
45 p.errout.Close()
46 return nil
47}
48func (p *directProcess) Record() containment.Record { return p.record }
49func directFixture(t *testing.T, name string) (*Journal, provider.Launch, provider.Session, *directProcess) {
50 t.Helper()
51 j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db"))
52 mustJournal(t, err)
53 t.Cleanup(func() { j.Close() })
54 version := "0.165.0"
55 if name == "claude" {
56 version = "2.1.312"
57 }
58 l := provider.Launch{AttemptKey: "attempt", Selection: provider.Selection{Provider: name, AccountID: "account", Family: name, Model: "model", ConnectionID: "connection"}, Binding: provider.Binding{ID: "binding", Provider: name, AccountID: "account", Expected: provider.Identity{ProviderVersion: version}}, Policy: provider.Policy{Hash: "policy", ManifestHash: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", Manifest: json.RawMessage(`{}`)}}
59 s := provider.Session{ID: "session", AttemptKey: l.AttemptKey, Provider: name, AccountID: "account", Family: name, Model: "model"}
60 p := &directProcess{record: containment.Record{ID: strings.Repeat("a", 32), AttemptKey: l.AttemptKey, ManifestHash: "namespace-manifest", PolicyHash: l.Policy.Hash}, out: io.NopCloser(strings.NewReader("")), errout: io.NopCloser(strings.NewReader(""))}
61 mustJournal(t, j.recordDirectLaunch(context.Background(), l, p.record))
62 return j, l, s, p
63}
64func directTurn() provider.Turn {
65 return provider.Turn{ID: "turn", AdmissionID: "admission", Prompt: "hello"}
66}
67func directPrompt(name string) []byte {
68 if name == "claude" {
69 return []byte("{\"type\":\"user\",\"session_id\":\"session\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n")
70 }
71 return []byte("{\"id\":1,\"method\":\"turn/start\",\"params\":{\"threadId\":\"session\",\"input\":[{\"type\":\"text\",\"text\":\"hello\"}]}}\n")
72}
73func TestDirectCrashBoundaries(t *testing.T) {
74 for _, name := range []string{"claude", "codex"} {
75 for _, stage := range []string{"intent", "before-stdin", "after-stdin", "before-frame", "after-frame", "before-upload", "server-before-ack"} {
76 t.Run(name+"/"+stage, func(t *testing.T) {
77 j, l, s, p := directFixture(t, name)
78 ctx, cancel := context.WithCancel(context.Background())
79 defer cancel()
80 // Keep stdout open until the simulated crash.
81 r, w := io.Pipe()
82 p.out = r
83 defer w.Close()
84 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
85 mustJournal(t, err)
86 if _, err = cap.Input.Write(directPrompt(name)); err == nil || p.input.Len() != 0 {
87 t.Fatal("prompt bypassed intent")
88 }
89 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
90 if stage != "intent" && stage != "before-stdin" {
91 _, err = cap.Input.Write(directPrompt(name))
92 mustJournal(t, err)
93 }
94 if stage == "after-frame" || stage == "before-upload" || stage == "server-before-ack" {
95 mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"type":"result","session_id":"session","subtype":"success","is_error":false}`)))
96 }
97 cancel()
98 <-cap.Done
99 path := j.path
100 mustJournal(t, j.Close())
101 reopened, err := OpenJournal(context.Background(), path)
102 mustJournal(t, err)
103 defer reopened.Close()
104 rows, err := reopened.RecoverDirect(context.Background())
105 mustJournal(t, err)
106 if len(rows) != 1 || rows[0].State != "waiting_for_person" || rows[0].Usage != nil {
107 t.Fatalf("uncertain recovery: %+v", rows)
108 }
109 if reopened.BeginTurn(context.Background(), s, directTurn()) == nil {
110 t.Fatal("restart admitted uncertain prompt again")
111 }
112 })
113 }
114 }
115}
116func TestDirectJournalFailureContains(t *testing.T) {
117 for _, kind := range []string{"torn", "unterminated", "malformed", "duplicate-key", "oversized", "disk-full", "outbox-full", "outbox-crossing", "blocked", "stderr"} {
118 t.Run(kind, func(t *testing.T) {
119 j, l, _, p := directFixture(t, "claude")
120 ctx, cancel := context.WithCancel(context.Background())
121 defer cancel()
122 raw := "{\"type\":\"system\",\"input_tokens\":9007199254740993,\"authorization\":\"Bearer secret\"}\n"
123 switch kind {
124 case "torn":
125 raw = `{"type":"system"`
126 case "unterminated":
127 raw = `{"type":"system"}`
128 case "malformed":
129 raw = "secret-sentinel\n"
130 case "duplicate-key":
131 raw = "{\"type\":1,\"type\":2}\n"
132 case "oversized":
133 raw = "{\"text\":\"" + strings.Repeat("x", 1<<20) + "\"}\n"
134 case "disk-full":
135 var pages int
136 mustJournal(t, j.db.QueryRow("PRAGMA page_count").Scan(&pages))
137 _, err := j.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages))
138 mustJournal(t, err)
139 raw = "{\"text\":\"" + strings.Repeat("a", 20000) + "\"}\n"
140 case "outbox-full":
141 _, err := j.db.Exec("INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES('full','full','full','{}',?)", MaxJournalBytes)
142 mustJournal(t, err)
143 case "outbox-crossing":
144 j.maxBytes = 256
145 raw = "{\"text\":\"" + strings.Repeat("x", 512) + "\"}\n"
146 case "blocked":
147 r, w := io.Pipe()
148 p.out = r
149 defer w.Close()
150 case "stderr":
151 p.errout = io.NopCloser(strings.NewReader(strings.Repeat("x", 70000)))
152 }
153 if kind != "blocked" {
154 p.out = io.NopCloser(strings.NewReader(raw))
155 }
156 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
157 if err != nil {
158 if !p.stopped.Load() {
159 t.Fatal("open failure did not contain")
160 }
161 return
162 }
163 if kind == "blocked" {
164 cancel()
165 }
166 if kind == "stderr" {
167 for range cap.Frames {
168 }
169 if err = <-cap.Done; err != nil {
170 t.Fatal(err)
171 }
172 var n int
173 mustJournal(t, j.db.QueryRow("SELECT length(diagnostics) FROM direct_attempts").Scan(&n))
174 if n > 64<<10 {
175 t.Fatal("unbounded stderr")
176 }
177 return
178 }
179 select {
180 case _, ok := <-cap.Frames:
181 if ok {
182 t.Fatal("uncommitted or invalid frame escaped")
183 }
184 case <-time.After(2 * time.Second):
185 t.Fatal("capture blocked")
186 }
187 if err = <-cap.Done; err == nil || !p.stopped.Load() || (kind == "malformed" && (!strings.Contains(err.Error(), "stdout_invalid_json") || strings.Contains(err.Error(), "secret-sentinel"))) {
188 t.Fatalf("not contained or unsafe diagnostic: %v", err)
189 }
190 })
191 }
192}
193func TestDirectJournalCommitBeforeDelivery(t *testing.T) {
194 j, l, _, p := directFixture(t, "claude")
195 p.out = io.NopCloser(strings.NewReader("{\"input_tokens\":9007199254740993,\"authorization\":\"Bearer secret\"}\n"))
196 cap, err := NewCaptureFactory(j).Open(context.Background(), p, l)
197 mustJournal(t, err)
198 for f := range cap.Frames {
199 var b []byte
200 mustJournal(t, j.db.QueryRow("SELECT body FROM direct_frames WHERE stream=? AND sequence=?", p.ID(), f.Sequence).Scan(&b))
201 if !bytes.Equal(b, f.Bytes) || strings.Contains(string(b), "secret") || !strings.Contains(string(b), "9007199254740993") {
202 t.Fatalf("frame not durably redacted with exact counters: %s", b)
203 }
204 }
205 mustJournal(t, <-cap.Done)
206}
207
208func TestDirectCrashProcess(t *testing.T) {
209 if path := os.Getenv("EQUIPO_TASK7_CRASH_PATH"); path != "" {
210 ctx := context.Background()
211 j, err := OpenJournal(ctx, path)
212 mustJournal(t, err)
213 l := provider.Launch{AttemptKey: "attempt", Selection: provider.Selection{Provider: "codex", AccountID: "account", Family: "gpt", Model: "model"}, Binding: provider.Binding{ID: "binding", Provider: "codex", AccountID: "account", Expected: provider.Identity{ProviderVersion: "0.165.0"}}, Policy: provider.Policy{Hash: "policy", ManifestHash: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", Manifest: json.RawMessage(`{}`)}}
214 s := provider.Session{ID: "session", AttemptKey: "attempt", Provider: "codex", AccountID: "account", Family: "gpt", Model: "model"}
215 r, w := io.Pipe()
216 defer w.Close()
217 input, err := os.OpenFile(path+".stdin", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
218 mustJournal(t, err)
219 p := &directProcess{record: containment.Record{ID: strings.Repeat("a", 32), AttemptKey: "attempt", ManifestHash: "manifest", PolicyHash: "policy"}, out: r, errout: io.NopCloser(strings.NewReader("")), writable: input}
220 mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
221 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
222 mustJournal(t, err)
223 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
224 stage := os.Getenv("EQUIPO_TASK7_CRASH_STAGE")
225 if stage == "intent" || stage == "before-stdin" {
226 os.Exit(0)
227 }
228 _, err = cap.Input.Write(directPrompt("codex"))
229 mustJournal(t, err)
230 mustJournal(t, input.Sync())
231 if stage == "after-stdin" {
232 os.Exit(0)
233 }
234 raw := []byte(`{"method":"turn/completed","params":{"threadId":"session","turn":{"id":"provider-turn","status":"completed"}}}`)
235 if stage == "before-frame" {
236 tx, err := j.db.BeginTx(ctx, nil)
237 mustJournal(t, err)
238 _, err = tx.Exec("INSERT INTO direct_frames(stream,sequence,body) VALUES(?,1,?)", p.ID(), raw)
239 mustJournal(t, err)
240 os.Exit(0)
241 }
242 mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, raw))
243 if stage == "after-frame" {
244 os.Exit(0)
245 }
246 _, err = j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
247 mustJournal(t, err)
248 template := journalEvent("ignored", 1)
249 template.ActionID = 1
250 pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
251 mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template))
252 if stage == "server-before-ack" {
253 pending, err := j.Pending(ctx, 1)
254 mustJournal(t, err)
255 raw, _ := json.Marshal(pending[0])
256 mustJournal(t, os.WriteFile(path+".server", raw, 0600))
257 }
258 os.Exit(0)
259 }
260 for _, stage := range []string{"intent", "before-stdin", "after-stdin", "before-frame", "after-frame", "before-upload", "server-before-ack"} {
261 t.Run(stage, func(t *testing.T) {
262 path := filepath.Join(t.TempDir(), "private", "journal.db")
263 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
264 defer cancel()
265 cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDirectCrashProcess$")
266 cmd.Env = append(os.Environ(), "EQUIPO_TASK7_CRASH_PATH="+path, "EQUIPO_TASK7_CRASH_STAGE="+stage)
267 if out, err := cmd.CombinedOutput(); err != nil {
268 t.Fatal(err, string(out))
269 }
270 j, err := OpenJournal(ctx, path)
271 mustJournal(t, err)
272 defer j.Close()
273 rows, err := j.RecoverDirect(ctx)
274 mustJournal(t, err)
275 if len(rows) != 1 {
276 t.Fatalf("missing recovery %+v", rows)
277 }
278 complete := stage == "before-upload" || stage == "server-before-ack"
279 if complete {
280 if rows[0].State != "completed_needs_containment" || rows[0].Usage == nil || rows[0].Usage.InputTokens != 28254 {
281 t.Fatalf("durable completion lost: %+v", rows)
282 }
283 } else if rows[0].State != "waiting_for_person" || rows[0].Usage != nil {
284 t.Fatalf("invented completion: %+v", rows)
285 }
286 var frames int
287 mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&frames))
288 want := 0
289 if stage == "after-frame" || complete {
290 want = 1
291 }
292 if frames != want {
293 t.Fatal("torn transaction persisted", frames, want)
294 }
295 input, err := os.ReadFile(path + ".stdin")
296 mustJournal(t, err)
297 writes := bytes.Count(input, []byte{'\n'})
298 expected := 1
299 if stage == "intent" || stage == "before-stdin" {
300 expected = 0
301 }
302 if writes != expected {
303 t.Fatal("prompt repeated", writes)
304 }
305 if stage == "server-before-ack" {
306 server, err := os.ReadFile(path + ".server")
307 mustJournal(t, err)
308 pending, err := j.Pending(ctx, 10)
309 mustJournal(t, err)
310 if len(pending) != 1 {
311 t.Fatal("lost upload")
312 }
313 replay, _ := json.Marshal(pending[0])
314 if !bytes.Equal(server, replay) {
315 t.Fatal("replay changed delivery identity")
316 }
317 }
318 })
319 }
320}
321
322func TestDirectCrashSingleUseInput(t *testing.T) {
323 j, l, s, p := directFixture(t, "codex")
324 ctx, cancel := context.WithCancel(context.Background())
325 defer cancel()
326 r, w := io.Pipe()
327 defer w.Close()
328 p.out = r
329 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
330 mustJournal(t, err)
331 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
332 _, err = cap.Input.Write(directPrompt("codex"))
333 mustJournal(t, err)
334 if _, err = cap.Input.Write(directPrompt("codex")); err == nil {
335 t.Fatal("same prompt sent twice")
336 }
337 if bytes.Count(p.input.Bytes(), []byte{'\n'}) != 1 {
338 t.Fatal("single-use intent reused")
339 }
340 if j.BeginTurn(ctx, s, provider.Turn{ID: "other", AdmissionID: "other-admission", Prompt: "hello"}) == nil {
341 t.Fatal("active turn replaced")
342 }
343 cancel()
344 <-cap.Done
345}
346func TestDirectJournalFrameSequence(t *testing.T) {
347 j, l, _, p := directFixture(t, "codex")
348 ctx := context.Background()
349 mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 2, []byte(`{"n":2}`)))
350 if j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"n":1}`)) == nil {
351 t.Fatal("frame order regressed")
352 }
353 if j.AppendFrame(ctx, l.AttemptKey, "other", 3, []byte(`{"n":3}`)) == nil {
354 t.Fatal("stream detached from attempt")
355 }
356}
357
358type shortDirectInput struct{}
359
360func (shortDirectInput) Write(b []byte) (int, error) { return len(b) / 2, nil }
361func (shortDirectInput) Close() error { return nil }
362func TestDirectJournalShortInput(t *testing.T) {
363 j, l, s, p := directFixture(t, "codex")
364 ctx, cancel := context.WithCancel(context.Background())
365 defer cancel()
366 r, w := io.Pipe()
367 defer w.Close()
368 p.out = r
369 p.writable = shortDirectInput{}
370 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
371 mustJournal(t, err)
372 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
373 if _, err = cap.Input.Write(directPrompt("codex")); err == nil {
374 t.Fatal("short stdin write reported success")
375 }
376 if err = <-cap.Done; err == nil || !p.stopped.Load() {
377 t.Fatal("short stdin write was not contained")
378 }
379 rows, err := j.RecoverDirect(context.Background())
380 mustJournal(t, err)
381 if rows[0].State != "waiting_for_person" {
382 t.Fatal("short write invented outcome")
383 }
384}
385func TestDirectJournalInputProtocol(t *testing.T) {
386 j, l, s, p := directFixture(t, "codex")
387 ctx, cancel := context.WithCancel(context.Background())
388 defer cancel()
389 r, w := io.Pipe()
390 defer w.Close()
391 p.out = r
392 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
393 mustJournal(t, err)
394 for _, raw := range []string{"{\"method\":\"command/exec\",\"params\":{}}\n", "{}\n{}\n", "{\"method\":\"turn/start\",\"params\":{\"threadId\":\"session\",\"input\":[]}}\n"} {
395 if _, err = cap.Input.Write([]byte(raw)); err == nil {
396 t.Fatal("invalid input admitted")
397 }
398 }
399 if p.input.Len() != 0 {
400 t.Fatal("invalid input transmitted")
401 }
402 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
403 wrong := bytes.ReplaceAll(directPrompt("codex"), []byte("hello"), []byte("different"))
404 if _, err = cap.Input.Write(wrong); err == nil {
405 t.Fatal("prompt differs from admitted intent")
406 }
407 if p.input.Len() != 0 {
408 t.Fatal("unadmitted prompt transmitted")
409 }
410 cancel()
411 <-cap.Done
412}
413
414func TestDirectCrashFullOutbox(t *testing.T) {
415 j, l, s, p := directFixture(t, "codex")
416 ctx, cancel := context.WithCancel(context.Background())
417 defer cancel()
418 r, w := io.Pipe()
419 defer w.Close()
420 p.out = r
421 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
422 mustJournal(t, err)
423 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
424 _, err = j.db.Exec("INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES('full','full','full','{}',?)", MaxJournalBytes)
425 mustJournal(t, err)
426 if _, err = cap.Input.Write(directPrompt("codex")); err == nil || p.input.Len() != 0 {
427 t.Fatal("full outbox admitted stdin")
428 }
429 cancel()
430 <-cap.Done
431}
432
433func TestDirectInterruptedLiveCapture(t *testing.T) {
434 j, l, s, p := directFixture(t, "codex")
435 ctx, cancel := context.WithCancel(context.Background())
436 defer cancel()
437 r, w := io.Pipe()
438 defer w.Close()
439 p.out = r
440 cap, err := NewCaptureFactory(j).Open(ctx, p, l)
441 mustJournal(t, err)
442 mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
443 _, err = cap.Input.Write(directPrompt("codex"))
444 mustJournal(t, err)
445 _, err = j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')")
446 mustJournal(t, err)
447 _, err = j.db.Exec("INSERT INTO direct_answer_scopes VALUES('answer',?,?)", s.AttemptKey, "turn")
448 mustJournal(t, err)
449 cancel()
450 <-cap.Done
451 var state string
452 mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state))
453 if state != "waiting_for_person" {
454 t.Fatal("live cancellation left turn dispatchable", state)
455 }
456 mustJournal(t, j.db.QueryRow("SELECT state FROM journal_answers").Scan(&state))
457 if state != "invalid" {
458 t.Fatal("live cancellation retained pending answers")
459 }
460 late, err := j.ObserveDirect(context.Background(), s, directComplete("turn"))
461 mustJournal(t, err)
462 if late != nil {
463 t.Fatal("late completion erased live cancellation")
464 }
465}
466