| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo" |
| 11 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 13 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 14 | ) |
| 15 | |
| 16 | func coordinatorEvent(c equipo.CoordinatorClaim, kind string) runnerproto.Event { |
| 17 | return runnerproto.Event{Version: 2, ID: kind, TaskID: c.Turn.ID, AssignmentID: c.Turn.ID, ServerID: "fixture", AgentID: "fixture", SessionID: "session", TurnID: c.Turn.ID, Kind: kind, Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action, Payload: json.RawMessage(`{}`), SourceTime: time.Now().UTC()} |
| 18 | } |
| 19 | |
| 20 | func TestCoordinatorFixResetNewMessage(t *testing.T) { |
| 21 | f, x, p, b := coordinatorFixture(t) |
| 22 | old := queueCoordinator(t, f, "uncertain prompt", "old") |
| 23 | c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision) |
| 24 | must(t, err) |
| 25 | x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 26 | if _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}); err == nil { |
| 27 | t.Fatal("reset skipped containment") |
| 28 | } |
| 29 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 30 | b2, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 31 | must(t, err) |
| 32 | msg, err := f.Store.SendMessage(ctx, owner, "", "new prompt", equipo.Mutation{RequestID: "new"}) |
| 33 | must(t, err) |
| 34 | turns, err := x.PollCoordinator(ctx, p) |
| 35 | must(t, err) |
| 36 | if len(turns) != 1 || turns[0].MessageID != msg.ID || turns[0].Generation != b2.Generation { |
| 37 | t.Fatalf("poll must offer only the new prompt: %+v", turns) |
| 38 | } |
| 39 | next, err := x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision) |
| 40 | if err != nil { |
| 41 | t.Fatalf("new generation claim blocked by old uncertainty: %v", err) |
| 42 | } |
| 43 | if next.Scope.Job == c.Scope.Job || len(next.Context.Recent) == 0 || next.Context.Recent[len(next.Context.Recent)-1].ID != msg.ID { |
| 44 | t.Fatal("new message reused the old admission or prompt") |
| 45 | } |
| 46 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='uncertain' AND generation=?", old.ID, b.Generation) != 1 { |
| 47 | t.Fatal("old uncertain turn changed") |
| 48 | } |
| 49 | if f.count(t, "SELECT count(*) FROM reservations WHERE job_id=? AND state='settled' AND settled_by='unknown' AND s_calls=r_calls AND s_calls=1 AND s_input=r_input AND s_output=r_output", c.Scope.Job) != 1 || f.count(t, "SELECT count(*) FROM admission_tickets") != 2 { |
| 50 | t.Fatal("old uncertainty lost its charge or new message was not admitted") |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | func TestCoordinatorFixUncertainWaitsForRetry(t *testing.T) { |
| 55 | f, x, p, _ := coordinatorFixture(t) |
| 56 | old := queueCoordinator(t, f, "uncertain prompt", "old") |
| 57 | c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision) |
| 58 | must(t, err) |
| 59 | x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 60 | must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "session.bound"))) |
| 61 | must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "turn.uncertain"))) |
| 62 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 63 | next := queueCoordinator(t, f, "later prompt", "next") |
| 64 | turns, err := x.PollCoordinator(ctx, p) |
| 65 | must(t, err) |
| 66 | if len(turns) != 0 { |
| 67 | t.Fatal("poll offered work behind current uncertainty", turns) |
| 68 | } |
| 69 | if _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision); err == nil { |
| 70 | t.Fatal("claim ignored current uncertainty") |
| 71 | } |
| 72 | // The next claim must rebuild context from current instance data. |
| 73 | f.exec(t, "UPDATE conversation_messages SET body='current context' WHERE id=?", old.MessageID) |
| 74 | retry, err := f.Store.RetryCoordinatorTurn(ctx, owner, old.ID, equipo.Mutation{RequestID: "retry", Revision: 2}) |
| 75 | must(t, err) |
| 76 | turns, err = x.PollCoordinator(ctx, p) |
| 77 | must(t, err) |
| 78 | if len(turns) != 1 || turns[0].ID == retry.ID { |
| 79 | t.Fatal("retry not combined with waiting message") |
| 80 | } |
| 81 | again, err := x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision) |
| 82 | must(t, err) |
| 83 | if again.Scope.Job == c.Scope.Job || again.Context.Recent[0].Body != "current context" || again.Turn.ContextHash == c.Turn.ContextHash { |
| 84 | t.Fatal("explicit retry reused admission or context") |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | func TestCoordinatorFixPollWaitsForContainment(t *testing.T) { |
| 89 | f, x, p, _ := coordinatorFixture(t) |
| 90 | old := queueCoordinator(t, f, "first", "first") |
| 91 | c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision) |
| 92 | must(t, err) |
| 93 | x.SetRunnerValidators(equipo.RunnerValidators{CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) { |
| 94 | return "answer", team.Receipt{ID: "delivered", Outcome: team.OutcomeSuccess}, nil |
| 95 | }}) |
| 96 | must(t, x.CompleteCoordinator(ctx, p, c, coordinatorEvent(c, "coordinator.delivery"))) |
| 97 | next := queueCoordinator(t, f, "next", "next") |
| 98 | turns, err := x.PollCoordinator(ctx, p) |
| 99 | must(t, err) |
| 100 | if len(turns) != 0 { |
| 101 | t.Fatal("poll offered a turn claim refuses while containment is pending", turns) |
| 102 | } |
| 103 | if _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision); err == nil { |
| 104 | t.Fatal("claim bypassed containment") |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | func TestCoordinatorFixCompletedThenDelivery(t *testing.T) { |
| 109 | for _, mismatch := range []string{"none", "usage", "unknown", "outcome"} { |
| 110 | t.Run(mismatch, func(t *testing.T) { |
| 111 | f, x, p, _ := coordinatorFixture(t) |
| 112 | turn := queueCoordinator(t, f, "hello", "turn") |
| 113 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 114 | must(t, err) |
| 115 | usage := team.Usage{Calls: 1, InputTokens: 12, OutputTokens: 4} |
| 116 | completed := team.Receipt{ID: "process-receipt", Outcome: team.OutcomeSuccess, Usage: &usage} |
| 117 | delivered := completed |
| 118 | delivered.ID = "delivery-receipt" |
| 119 | switch mismatch { |
| 120 | case "usage": |
| 121 | different := usage |
| 122 | different.InputTokens++ |
| 123 | delivered.Usage = &different |
| 124 | case "unknown": |
| 125 | delivered.Usage = nil |
| 126 | case "outcome": |
| 127 | completed.Outcome = team.OutcomeFailure |
| 128 | } |
| 129 | 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) { |
| 130 | return completed, nil |
| 131 | }, CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) { |
| 132 | return "answer", delivered, nil |
| 133 | }}) |
| 134 | must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "session.bound"))) |
| 135 | must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "turn.completed"))) |
| 136 | event := coordinatorEvent(c, "coordinator.delivery") |
| 137 | err = x.CompleteCoordinator(ctx, p, c, event) |
| 138 | if mismatch != "none" { |
| 139 | if err == nil { |
| 140 | t.Fatal("delivery accepted inconsistent receipt") |
| 141 | } |
| 142 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 0 { |
| 143 | t.Fatal("rejected delivery wrote an answer") |
| 144 | } |
| 145 | return |
| 146 | } |
| 147 | if err != nil { |
| 148 | t.Fatalf("completed then delivery with distinct receipts failed: %v", err) |
| 149 | } |
| 150 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 151 | action, err := x.Core.GetAction(ctx, c.Scope, event.ActionID) |
| 152 | must(t, err) |
| 153 | if action.Receipt == nil || action.Receipt.ID != completed.ID || action.Receipt.Usage == nil || *action.Receipt.Usage != usage { |
| 154 | t.Fatal("delivery replaced the settled receipt", action.Receipt) |
| 155 | } |
| 156 | if f.count(t, "SELECT count(*) FROM reservations WHERE state='settled'") != 1 || f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 1 || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.delivered'") != 1 || f.count(t, "SELECT count(*) FROM jobs WHERE state='succeeded'") != 1 { |
| 157 | t.Fatal("delivery was not settled exactly once") |
| 158 | } |
| 159 | }) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | func TestCoordinatorFixDeliverySession(t *testing.T) { |
| 164 | f, x, p, _ := coordinatorFixture(t) |
| 165 | turn := queueCoordinator(t, f, "hello", "turn") |
| 166 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 167 | must(t, err) |
| 168 | validations := 0 |
| 169 | x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) { |
| 170 | validations++ |
| 171 | return "answer", team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess}, nil |
| 172 | }}) |
| 173 | must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "session.bound"))) |
| 174 | event := coordinatorEvent(c, "coordinator.delivery") |
| 175 | event.SessionID = "other-session" |
| 176 | if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| 177 | t.Fatal("delivery overwrote the bound provider session") |
| 178 | } |
| 179 | if validations != 0 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND provider_session_id='session' AND state='running'", turn.ID) != 1 || f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 0 { |
| 180 | t.Fatal("mismatched session had effects") |
| 181 | } |
| 182 | event.SessionID = "session" |
| 183 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 184 | } |
| 185 | |
| 186 | func TestCoordinatorFixPollUnknownConnection(t *testing.T) { |
| 187 | f, x, p, _ := coordinatorFixture(t) |
| 188 | turn := queueCoordinator(t, f, "hello", "turn") |
| 189 | _, err := f.Store.SendMessage(ctx, owner, "", "not queued yet", equipo.Mutation{RequestID: "new"}) |
| 190 | must(t, err) |
| 191 | before := f.count(t, "SELECT count(*) FROM audit_events") |
| 192 | f.exec(t, "ALTER TABLE connections RENAME TO missing_connections") |
| 193 | turns, err := x.PollCoordinator(ctx, p) |
| 194 | if err == nil || len(turns) != 0 { |
| 195 | t.Fatal("unknown connection lookup became a definite waiting state", turns, err) |
| 196 | } |
| 197 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='queued'", turn.ID) != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns") != 1 || f.count(t, "SELECT count(*) FROM audit_events") != before { |
| 198 | t.Fatal("failed poll persisted changes") |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | func TestCoordinatorFixPollMissingConnection(t *testing.T) { |
| 203 | for _, change := range []string{"missing", "stale", "revision"} { |
| 204 | t.Run(change, func(t *testing.T) { |
| 205 | f, x, p, _ := coordinatorFixture(t) |
| 206 | turn := queueCoordinator(t, f, "hello", "turn") |
| 207 | switch change { |
| 208 | case "missing": |
| 209 | f.exec(t, "DELETE FROM connections WHERE id='claude'") |
| 210 | case "stale": |
| 211 | f.exec(t, "UPDATE connections SET last_seen=? WHERE id='claude'", time.Now().Add(-time.Hour).UTC()) |
| 212 | case "revision": |
| 213 | f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") |
| 214 | } |
| 215 | if change != "revision" { |
| 216 | f.exec(t, "CREATE TRIGGER waiting_audit_failure BEFORE INSERT ON audit_events WHEN NEW.kind='coordinator.waiting_connection' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END") |
| 217 | if _, err := x.PollCoordinator(ctx, p); err == nil { |
| 218 | t.Fatal("waiting state succeeded without its audit") |
| 219 | } |
| 220 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='queued'", turn.ID) != 1 { |
| 221 | t.Fatal("audit failure persisted waiting state") |
| 222 | } |
| 223 | f.exec(t, "DROP TRIGGER waiting_audit_failure") |
| 224 | } |
| 225 | turns, err := x.PollCoordinator(ctx, p) |
| 226 | if change == "revision" { |
| 227 | if !errors.Is(err, equipo.ErrForbidden) || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='admission_denied'", turn.ID) != 1 { |
| 228 | t.Fatal("authority mismatch must remain denied and visible") |
| 229 | } |
| 230 | return |
| 231 | } |
| 232 | must(t, err) |
| 233 | if len(turns) != 0 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='waiting_connection'", turn.ID) != 1 { |
| 234 | t.Fatal("known missing connection did not persist waiting") |
| 235 | } |
| 236 | _, err = x.PollCoordinator(ctx, p) |
| 237 | must(t, err) |
| 238 | if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.waiting_connection' AND record_id=?", turn.ID) != 1 { |
| 239 | t.Fatal("waiting state audit missing or duplicated") |
| 240 | } |
| 241 | }) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | func TestCoordinatorFixQueueAudit(t *testing.T) { |
| 246 | for _, via := range []string{"queue", "poll", "requeue"} { |
| 247 | t.Run(via, func(t *testing.T) { |
| 248 | f, x, p, b := coordinatorFixture(t) |
| 249 | msg, err := f.Store.SendMessage(ctx, owner, "", "hello", equipo.Mutation{RequestID: "message"}) |
| 250 | must(t, err) |
| 251 | if via == "requeue" { |
| 252 | _, err = f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: "initial"}) |
| 253 | must(t, err) |
| 254 | _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 255 | must(t, err) |
| 256 | } |
| 257 | before := f.count(t, "SELECT count(*) FROM coordinator_turns") |
| 258 | f.exec(t, "CREATE TRIGGER queue_audit_failure BEFORE INSERT ON audit_events WHEN NEW.kind='coordinator.queue' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END") |
| 259 | queue := func() error { |
| 260 | if via == "queue" { |
| 261 | _, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: "queue"}) |
| 262 | return err |
| 263 | } |
| 264 | _, err := x.PollCoordinator(ctx, p) |
| 265 | return err |
| 266 | } |
| 267 | if err = queue(); err == nil { |
| 268 | t.Fatal("queue succeeded without its audit") |
| 269 | } |
| 270 | if f.count(t, "SELECT count(*) FROM coordinator_turns") != before { |
| 271 | t.Fatal("failed audit did not roll back queued turn") |
| 272 | } |
| 273 | f.exec(t, "DROP TRIGGER queue_audit_failure") |
| 274 | must(t, queue()) |
| 275 | must(t, queue()) |
| 276 | expected := before + 1 |
| 277 | if f.count(t, "SELECT count(*) FROM coordinator_turns") != expected || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.queue' AND actor=? AND delegating_person=?", "coordinator:"+b.ID, owner.Address) != expected { |
| 278 | t.Fatal("queue audit missing, duplicated or misattributed") |
| 279 | } |
| 280 | }) |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | func TestCoordinatorFixRetryInputHash(t *testing.T) { |
| 285 | f, x, p, _ := coordinatorFixture(t) |
| 286 | old := queueCoordinator(t, f, "hello", "old") |
| 287 | c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision) |
| 288 | must(t, err) |
| 289 | x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 290 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 291 | retry, err := f.Store.RetryCoordinatorTurn(ctx, owner, old.ID, equipo.Mutation{RequestID: "retry", Revision: 2}) |
| 292 | must(t, err) |
| 293 | expected, err := kernel.InputHash(struct { |
| 294 | ID string |
| 295 | Revision int64 |
| 296 | }{old.ID, 2}) |
| 297 | must(t, err) |
| 298 | var hash string |
| 299 | must(t, f.DB.Writer().QueryRow("SELECT input_hash FROM coordinator_turns WHERE id=?", retry.ID).Scan(&hash)) |
| 300 | if hash != expected { |
| 301 | t.Fatalf("retry input hash = %q, want %q", hash, expected) |
| 302 | } |
| 303 | replay, err := f.Store.RetryCoordinatorTurn(ctx, owner, old.ID, equipo.Mutation{RequestID: "retry", Revision: 2}) |
| 304 | must(t, err) |
| 305 | if replay.ID != retry.ID { |
| 306 | t.Fatal("retry replay duplicated turn") |
| 307 | } |
| 308 | } |
| 309 | |