oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "log/slog"
10 "math"
11 "net/http/httptest"
12 "path/filepath"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/equipo"
17 "amadan.net/oficina/equipo/internal/equipo/team"
18 "amadan.net/oficina/equipo/internal/runner"
19 "amadan.net/oficina/equipo/internal/runner/provider"
20 "amadan.net/oficina/equipo/internal/runnerproto"
21 "amadan.net/rastrillo/rastrillo/db"
22 "amadan.net/rastrillo/rastrillo/migrate"
23 "gorm.io/gorm"
24)
25
26func fixtureEvent(f runnerFixture, id string, seq int64) runnerproto.Event {
27 return runnerproto.Event{Version: 2, ID: id, TaskID: f.a.TaskID, AssignmentID: f.a.ID, Scope: f.claim.Scope, Handle: f.claim.Handle, ServerID: "server", AgentID: "agent", SessionID: "session", Epoch: "epoch", Sequence: &seq, Kind: "timeline", Payload: json.RawMessage(`{"text":"hello"}`), SourceTime: time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)}
28}
29func eventValidators(f runnerFixture) {
30 f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
31}
32func TestRunnerEventReplay(t *testing.T) {
33 f := runnerFixtureNew(t, true)
34 eventValidators(f)
35 e := fixtureEvent(f, "one", 1)
36 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
37 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
38 e.ID = "alias"
39 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
40 if n := scalar(t, f.d, "SELECT count(*) FROM runner_events"); n != 1 {
41 t.Fatal("replay duplicated effect", n)
42 }
43 if n := scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'"); n != 1 {
44 t.Fatal("replay duplicated audit", n)
45 }
46 e.Payload = json.RawMessage(`{"text":"changed"}`)
47 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
48 t.Fatal("changed duplicate accepted")
49 }
50 e = fixtureEvent(f, "other", 2)
51 e.Handle.Fence++
52 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
53 t.Fatal("wrong fence accepted")
54 }
55 e = fixtureEvent(f, "other", 2)
56 p := f.principal
57 p.Person = "other@example.com"
58 if f.s.IngestRunnerEvent(connectionContext, p, e) == nil {
59 t.Fatal("wrong principal accepted")
60 }
61}
62func TestTimelineEpochReplacement(t *testing.T) {
63 f := runnerFixtureNew(t, true)
64 seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID)
65 eventValidators(f)
66 e := fixtureEvent(f, "old", 1)
67 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
68 e = fixtureEvent(f, "replace", 0)
69 e.Kind = "timeline_replacement"
70 e.Sequence = nil
71 e.Epoch = "new"
72 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
73 q := f.request()
74 q.Intent = &team.IntentSpec{Key: "blocked", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`)}
75 if _, err := f.x.Mutate(connectionContext, f.principal, "intend", q); err == nil {
76 t.Fatal("gap admitted work")
77 }
78 e = fixtureEvent(f, "new", 1)
79 e.Epoch = "new"
80 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
81 if n := scalar(t, f.d, "SELECT count(*) FROM runner_events"); n != 3 {
82 t.Fatal("replacement deleted evidence", n)
83 }
84 var epoch, iso string
85 executionMust(t, f.d.Writer().QueryRow("SELECT epoch,isolation FROM runner_timelines").Scan(&epoch, &iso))
86 if epoch != "new" {
87 t.Fatal("projection retained old epoch", epoch)
88 }
89 var isolation team.IsolationSnapshot
90 executionMust(t, json.Unmarshal([]byte(iso), &isolation))
91 if !isolation.RunnerTainted {
92 t.Fatal("replacement stripped exposure")
93 }
94}
95
96func eventTurn(t *testing.T, f runnerFixture) team.ActionID {
97 t.Helper()
98 q := f.request()
99 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`), Reserve: team.Usage{InputTokens: 100, OutputTokens: 100}}
100 result, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
101 executionMust(t, err)
102 q.Intent = nil
103 q.ActionID = result.(team.ActionID)
104 q.RequestID = "admit"
105 _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
106 executionMust(t, err)
107 return q.ActionID
108}
109func completionEvent(f runnerFixture, id team.ActionID) runnerproto.Event {
110 e := fixtureEvent(f, "completed", 1)
111 e.Kind = "turn_completed"
112 e.Sequence = nil
113 e.TurnID = "turn"
114 e.ActionID = id
115 e.Payload = json.RawMessage(`{"event":{"type":"turn_completed","provider":"claude","turnId":"turn","usage":{"inputTokens":10,"cachedInputTokens":3,"outputTokens":2,"totalCostUsd":0.0673131}}}`)
116 return e
117}
118func completionValidators(f runnerFixture, usage *team.Usage) {
119 f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
120 return team.Receipt{ID: "turn-receipt", Outcome: team.OutcomeSuccess, Usage: usage}, nil
121 }})
122}
123func TestRunnerEventReplayAtomicSettlement(t *testing.T) {
124 f := runnerFixtureNew(t, true)
125 id := eventTurn(t, f)
126 e := completionEvent(f, id)
127 u := &team.Usage{Calls: 1, InputTokens: 13, CachedInputTokens: 3, OutputTokens: 2, CostUnavailable: true}
128 completionValidators(f, u)
129 executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task12_crash", func(tx *gorm.DB) {
130 if tx.Statement.Table == "audit_events" {
131 if ev, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && ev.Kind == "runner.event" {
132 tx.AddError(errors.New("injected task12 failure"))
133 }
134 }
135 }))
136 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
137 t.Fatal("audit failure accepted")
138 }
139 executionMust(t, f.d.G.Callback().Create().Remove("task12_crash"))
140 if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 0 || scalar(t, f.d, "SELECT count(*) FROM runner_timelines") != 0 || scalar(t, f.d, "SELECT count(*) FROM reservations WHERE state='settled'") != 0 {
141 t.Fatal("partial event transaction committed")
142 }
143 action, err := f.x.Core.GetAction(connectionContext, e.Scope, id)
144 executionMust(t, err)
145 if action.State != team.ActionDispatching {
146 t.Fatal("core receipt escaped rollback")
147 }
148 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
149 for i := 0; i < 3; i++ {
150 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
151 }
152 rows, err := f.x.Core.Reservations(connectionContext, e.Scope)
153 executionMust(t, err)
154 if len(rows) != 1 || rows[0].Settled != *u {
155 t.Fatal("replayed charge", rows)
156 }
157 if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 {
158 t.Fatal("duplicate acceptance")
159 }
160}
161func TestRunnerEventReplayMissingAndLateAfterCancel(t *testing.T) {
162 f := runnerFixtureNew(t, true)
163 id := eventTurn(t, f)
164 e := completionEvent(f, id)
165 completionValidators(f, nil)
166 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
167 rows, err := f.x.Core.Reservations(connectionContext, e.Scope)
168 executionMust(t, err)
169 if rows[0].State != team.ReservationSettled || rows[0].Settled != rows[0].Reserved {
170 t.Fatal("missing usage refunded")
171 }
172 q := f.request()
173 q.RequestID = "next"
174 q.Intent = &team.IntentSpec{Key: "next", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
175 if _, err = f.x.Mutate(connectionContext, f.principal, "intend", q); err != nil {
176 t.Fatal("completed unknown usage blocked remaining headroom", err)
177 }
178 _, err = f.x.Core.Cancel(connectionContext, e.Scope, ownerAddress, "cancel")
179 executionMust(t, err)
180 completionValidators(f, &team.Usage{Calls: 1, InputTokens: 13, CachedInputTokens: 3, OutputTokens: 2, CostUnavailable: true})
181 e.ID = "late"
182 e.RequestID = "late-observation"
183 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
184 job, err := f.x.Core.GetJob(connectionContext, e.Scope)
185 executionMust(t, err)
186 if job.State != team.JobCancelled {
187 t.Fatal("late usage changed cancellation", job.State)
188 }
189 rows, err = f.x.Core.Reservations(connectionContext, e.Scope)
190 executionMust(t, err)
191 if rows[0].State != team.ReservationSettled || rows[0].Settled.InputTokens != rows[0].Reserved.InputTokens {
192 t.Fatal("late usage did not settle", rows)
193 }
194}
195func TestRunnerEventReplayArtifactRequest(t *testing.T) {
196 f := runnerFixtureNew(t, true)
197 f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
198 q := f.request()
199 q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro")}
200 first, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q)
201 executionMust(t, err)
202 second, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q)
203 executionMust(t, err)
204 if first.(team.Artifact).ID != second.(team.Artifact).ID || scalar(t, f.d, "SELECT count(*) FROM artifacts") != 1 {
205 t.Fatal("artifact replay created semantic duplicate")
206 }
207 q.Artifact.Payload = []byte("changed")
208 if _, err = f.x.Mutate(connectionContext, f.principal, "artifacts", q); err == nil {
209 t.Fatal("artifact key reused for changed payload")
210 }
211}
212func TestRunnerEventReplayHTTP(t *testing.T) {
213 f := runnerFixtureNew(t, true)
214 eventValidators(f)
215 e := fixtureEvent(f, "wire", 1)
216 q := f.request()
217 q.RequestID = e.ID
218 raw, err := runnerproto.Marshal(e)
219 executionMust(t, err)
220 q.Event = raw
221 body, err := runnerproto.Marshal(q)
222 executionMust(t, err)
223 req := httptest.NewRequest("POST", "/events", bytes.NewReader(body))
224 req.Header.Set("Content-Type", "application/json")
225 req.Header.Set("Authorization", "Bearer "+runnerBearerFor(t, f))
226 w := httptest.NewRecorder()
227 f.s.RunnerHandler().ServeHTTP(w, req)
228 if w.Code != 200 {
229 t.Fatal("event endpoint", w.Code, w.Body.String())
230 }
231}
232
233func reopenEventFixture(t *testing.T, f *runnerFixture) {
234 t.Helper()
235 var path string
236 executionMust(t, f.d.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path))
237 executionMust(t, f.x.Core.Close())
238 executionMust(t, f.d.Close())
239 d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
240 executionMust(t, err)
241 t.Cleanup(func() { d.Close() })
242 f.d = d
243 _, err = migrate.Apply(connectionContext, d, equipo.BootSchema)
244 executionMust(t, err)
245 f.s = equipo.NewStore(d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples([]team.IsolationTuple{connectionTuple(f.reports[0]), connectionTuple(f.reports[1])}))
246 f.x, err = f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)})
247 executionMust(t, err)
248 x := f.x
249 t.Cleanup(func() { x.Core.Close() })
250}
251func TestRunnerJournalServerCommitBeforeACK(t *testing.T) {
252 f := runnerFixtureNew(t, true)
253 id := eventTurn(t, f)
254 e := completionEvent(f, id)
255 path := filepath.Join(t.TempDir(), "private", "journal.db")
256 j, err := runner.OpenJournal(connectionContext, path)
257 executionMust(t, err)
258 profile := runner.UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "exclusive", CostSemantics: "cumulative", Subscription: true}
259 agent := provider.Agent{ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID}
260 executionMust(t, j.Append(connectionContext, e))
261 acc, err := j.Usage(connectionContext, agent, profile)
262 executionMust(t, err)
263 u := acc.ObservePaseo(provider.RecordedEvent{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Payload: e.Payload})
264 if u == nil {
265 t.Fatal("journal did not restore usage")
266 }
267 completionValidators(f, u)
268 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
269 executionMust(t, j.Close())
270 for i := 0; i < 2; i++ {
271 reopenEventFixture(t, &f)
272 j, err = runner.OpenJournal(connectionContext, path)
273 executionMust(t, err)
274 acc, err = j.Usage(connectionContext, agent, profile)
275 executionMust(t, err)
276 if math.Abs(acc.EstimatedCostUSD()-0.0673131) > 1e-10 {
277 t.Fatal("reopen lost usage baseline")
278 }
279 completionValidators(f, u)
280 rows, err := j.Pending(connectionContext, 10)
281 executionMust(t, err)
282 if len(rows) != 1 {
283 t.Fatal("commit before ACK lost retry")
284 }
285 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, rows[0]))
286 executionMust(t, j.Close())
287 }
288 j, err = runner.OpenJournal(connectionContext, path)
289 executionMust(t, err)
290 defer j.Close()
291 pump := runner.EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(ctx context.Context, e runner.Event) error { return f.s.IngestRunnerEvent(ctx, f.principal, e) }}
292 executionMust(t, pump.Flush(connectionContext, 10))
293 if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 || scalar(t, f.d, "SELECT count(*) FROM reservations WHERE state='settled'") != 1 {
294 t.Fatal("reopen duplicated effects")
295 }
296 pending, err := j.Pending(connectionContext, 10)
297 executionMust(t, err)
298 if len(pending) != 0 {
299 t.Fatal("accepted event not ACKed")
300 }
301}
302func TestRunnerEventReplayValidationAndRollback(t *testing.T) {
303 f := runnerFixtureNew(t, true)
304 e := fixtureEvent(f, "one", 1)
305 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
306 t.Fatal("missing event validator accepted")
307 }
308 eventValidators(f)
309 for _, field := range []string{"scope", "task", "assignment", "runner", "session", "sequence", "payload", "time"} {
310 t.Run(field, func(t *testing.T) {
311 bad := e
312 switch field {
313 case "scope":
314 bad.Scope.Account = "other"
315 case "task":
316 bad.TaskID = "other"
317 case "assignment":
318 bad.AssignmentID = "other"
319 case "runner":
320 bad.Handle.Runner = "other"
321 case "session":
322 bad.SessionID = ""
323 case "sequence":
324 n := int64(-1)
325 bad.Sequence = &n
326 case "payload":
327 bad.Payload = []byte(`invalid`)
328 case "time":
329 bad.SourceTime = time.Time{}
330 }
331 if f.s.IngestRunnerEvent(connectionContext, f.principal, bad) == nil {
332 t.Fatal("invalid event accepted", field)
333 }
334 })
335 }
336 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
337 e.ID = "alias"
338 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
339 n := int64(2)
340 e.Sequence = &n
341 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
342 t.Fatal("event alias reused for new sequence")
343 }
344 executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
345 e = fixtureEvent(f, "one", 1)
346 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
347 t.Fatal("revoked principal replay accepted")
348 }
349}
350
351func TestRunnerEventReplayProviderWire(t *testing.T) {
352 f := runnerFixtureNew(t, true)
353 id := eventTurn(t, f)
354 e := completionEvent(f, id)
355 completionValidators(f, nil)
356 q := f.request()
357 q.RequestID = e.ID
358 q.ActionID = id
359 raw, err := runnerproto.Marshal(e)
360 executionMust(t, err)
361 q.Event = raw
362 if status := runnerHTTP(t, f, "events", runnerBearerFor(t, f), q); status != 200 {
363 t.Fatal("provider payload rejected by wire codec", status)
364 }
365}
366func TestRunnerEventReplayControlEpoch(t *testing.T) {
367 f := runnerFixtureNew(t, true)
368 id := eventTurn(t, f)
369 e := completionEvent(f, id)
370 completionValidators(f, nil)
371 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
372 e.Epoch = "replacement"
373 e.ID = "history-control"
374 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
375 if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 {
376 t.Fatal("control duplicated across epochs")
377 }
378}
379
380func TestTimelineEpochHistoricalExposure(t *testing.T) {
381 f := runnerFixtureNew(t, true)
382 seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID)
383 eventValidators(f)
384 e := fixtureEvent(f, "exposure", 1)
385 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
386 mustSQL(t, f.d, `UPDATE runner_events SET isolation='{"status":"confined"}',body=json_set(body,'$.isolation',json('{"status":"confined"}'))`)
387 mustSQL(t, f.d, `UPDATE runner_timelines SET isolation='{"status":"confined"}'`)
388 executionMust(t, f.x.Sync(connectionContext))
389 var raw, body, projection string
390 executionMust(t, f.d.Writer().QueryRow("SELECT isolation,body FROM runner_events").Scan(&raw, &body))
391 executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_timelines").Scan(&projection))
392 for _, value := range []string{raw, projection} {
393 var iso team.IsolationSnapshot
394 executionMust(t, json.Unmarshal([]byte(value), &iso))
395 if !iso.RunnerTainted {
396 t.Fatal("running event lost newly observed exposure")
397 }
398 }
399 var restored runnerproto.Event
400 executionMust(t, json.Unmarshal([]byte(body), &restored))
401 if !restored.Isolation.RunnerTainted {
402 t.Fatal("event body lost exposure")
403 }
404}
405
406func TestTimelineEpochUnknownOutcome(t *testing.T) {
407 f := runnerFixtureNew(t, true)
408 id := eventTurn(t, f)
409 eventValidators(f)
410 e := fixtureEvent(f, "gap", 0)
411 e.Sequence = nil
412 e.Kind = "timeline_gap"
413 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
414 e.ID = "ready"
415 e.Kind = "timeline_ready"
416 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
417 q := f.request()
418 q.RequestID = "next"
419 q.Intent = &team.IntentSpec{Key: "next", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
420 if _, err := f.x.Mutate(connectionContext, f.principal, "intend", q); err == nil {
421 t.Fatal("refetch invented completion for unknown action")
422 }
423 e = completionEvent(f, id)
424 completionValidators(f, nil)
425 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
426 if _, err := f.x.Mutate(connectionContext, f.principal, "intend", q); err != nil {
427 t.Fatal("known completion cannot use remaining headroom", err)
428 }
429}
430func TestRunnerEventReplayCompletionNeedsReceipt(t *testing.T) {
431 f := runnerFixtureNew(t, true)
432 id := eventTurn(t, f)
433 eventValidators(f)
434 e := completionEvent(f, id)
435 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
436 t.Fatal("uncorroborated completion accepted")
437 }
438 if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 0 {
439 t.Fatal("uncorroborated event committed")
440 }
441}
442
443func TestRunnerEventReplayAssignedIsolation(t *testing.T) {
444 f := runnerFixtureNew(t, true)
445 seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID)
446 eventValidators(f)
447 e := fixtureEvent(f, "assigned", 1)
448 e.Isolation = team.IsolationSnapshot{Status: "confined"}
449 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
450 var raw string
451 executionMust(t, f.d.Writer().QueryRow("SELECT body FROM runner_events").Scan(&raw))
452 var saved runnerproto.Event
453 executionMust(t, json.Unmarshal([]byte(raw), &saved))
454 if !saved.Isolation.RunnerTainted || len(saved.Isolation.AcknowledgementIDs) == 0 {
455 t.Fatal("event did not retain assigned isolation at commit")
456 }
457}
458
459func fixtureEventRequest(t *testing.T, f runnerFixture, q equipo.RunnerRequest) json.RawMessage {
460 t.Helper()
461 event := fixtureEvent(f, q.RequestID, 1)
462 event.Scope = q.Scope
463 event.Handle = q.Handle
464 event.AssignmentID = q.AssignmentID
465 event.ActionID = q.ActionID
466 raw, err := runnerproto.Marshal(event)
467 executionMust(t, err)
468 return raw
469}
470
471func TestTimelineEpochChangedReset(t *testing.T) {
472 f := runnerFixtureNew(t, true)
473 eventValidators(f)
474 e := fixtureEvent(f, "reset", 0)
475 e.Kind = "timeline_replacement"
476 e.Sequence = nil
477 executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
478 e.Epoch = "different"
479 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
480 t.Fatal("replacement ID accepted a different target epoch")
481 }
482}
483
484func TestDirectCompletionServerCommitBeforeACK(t *testing.T) {
485 for _, mode := range []string{"completed-known", "completed-unknown", "failed-unknown", "chunked-known"} {
486 t.Run(mode, func(t *testing.T) {
487 f := runnerFixtureNew(t, true, true)
488 id := eventTurn(t, f)
489 e := completionEvent(f, id)
490 e.Kind = "turn.completed"
491 u := &team.Usage{Calls: 1, InputTokens: 28254, OutputTokens: 142, CostUnavailable: true}
492 if mode == "failed-unknown" {
493 e.Kind = "turn.failed"
494 }
495 if mode == "completed-unknown" || mode == "failed-unknown" {
496 u = nil
497 }
498 var payloadErr error
499 e.Payload, payloadErr = json.Marshal(struct {
500 Usage *team.Usage `json:"usage"`
501 }{u})
502 executionMust(t, payloadErr)
503 if mode == "chunked-known" {
504 e.Payload = []byte(`{"chunks":"durable-envelope","count":2,"kind":"turn.completed","usage":{"calls":1,"input_tokens":28254,"output_tokens":142,"cost_unavailable":true}}`)
505 }
506 for _, field := range []string{"fence", "attempt", "action", "runner", "scope", "usage"} {
507 bad := e
508 switch field {
509 case "fence":
510 bad.Handle.Fence++
511 case "attempt":
512 bad.Handle.Attempt++
513 case "action":
514 bad.ActionID++
515 case "runner":
516 bad.Handle.Runner = "foreign"
517 case "scope":
518 bad.Scope.Account = "foreign"
519 case "usage":
520 bad.Payload = []byte(`{"usage":"unknown"}`)
521 }
522 if f.s.IngestRunnerEvent(connectionContext, f.principal, bad) == nil {
523 t.Fatal("foreign completion accepted", field)
524 }
525 }
526 path := filepath.Join(t.TempDir(), "private", "journal.db")
527 j, err := runner.OpenJournal(connectionContext, path)
528 executionMust(t, err)
529 pump := runner.EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(ctx context.Context, event runnerproto.Event) error {
530 if err := f.s.IngestRunnerEvent(ctx, f.principal, event); err != nil {
531 return err
532 }
533 return errors.New("lost ACK after server commit")
534 }}
535 executionMust(t, pump.Append(connectionContext, e, nil))
536 if pump.Flush(connectionContext, 10) == nil {
537 t.Fatal("lost acknowledgement ignored")
538 }
539 executionMust(t, j.Close())
540 j, err = runner.OpenJournal(connectionContext, path)
541 executionMust(t, err)
542 defer j.Close()
543 pump.Journal = j
544 pump.Upload = func(ctx context.Context, event runnerproto.Event) error {
545 return f.s.IngestRunnerEvent(ctx, f.principal, event)
546 }
547 executionMust(t, pump.Flush(connectionContext, 10))
548 rows, err := f.x.Core.Reservations(connectionContext, e.Scope)
549 executionMust(t, err)
550 if len(rows) != 1 {
551 t.Fatal("reservation count", len(rows))
552 }
553 expected := rows[0].Reserved
554 if u != nil {
555 expected = *u
556 }
557 if rows[0].State != team.ReservationSettled || rows[0].Settled != expected {
558 t.Fatalf("direct receipt lost or duplicated: %+v", rows)
559 }
560 if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 {
561 t.Fatal("replay repeated event effects")
562 }
563 action, err := f.x.Core.GetAction(connectionContext, e.Scope, id)
564 executionMust(t, err)
565 wantOutcome := team.OutcomeSuccess
566 if mode == "failed-unknown" {
567 wantOutcome = team.OutcomeFailure
568 }
569 if action.Receipt == nil || action.Receipt.Outcome != wantOutcome || (action.Receipt.Usage == nil) != (u == nil) {
570 t.Fatalf("receipt changed outcome or usage certainty: %+v", action.Receipt)
571 }
572 e.ID = "bad-direct"
573 e.TurnID = ""
574 e.ActionID = 0
575 if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
576 t.Fatal("direct completion lacks turn authority")
577 }
578 })
579 }
580}
581