| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 6 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "sync" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | func TestCoordinatorSingleWriter(t *testing.T) { |
| 15 | f, x, p, _ := coordinatorFixture(t) |
| 16 | first := queueCoordinator(t, f, "first", "first") |
| 17 | second := queueCoordinator(t, f, "second", "second") |
| 18 | if _, err := x.ClaimCoordinator(ctx, p, second.ID, second.Revision); err == nil { |
| 19 | t.Fatal("later message overtook first") |
| 20 | } |
| 21 | offers, err := x.PollCoordinator(ctx, p) |
| 22 | must(t, err) |
| 23 | if len(offers) != 1 || offers[0].ID != second.ID { |
| 24 | t.Fatal("pending messages not coalesced") |
| 25 | } |
| 26 | var wg sync.WaitGroup |
| 27 | results := make(chan error, 2) |
| 28 | for _, turn := range []equipo.CoordinatorTurn{first, second} { |
| 29 | wg.Add(1) |
| 30 | go func() { defer wg.Done(); _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); results <- err }() |
| 31 | } |
| 32 | wg.Wait() |
| 33 | close(results) |
| 34 | successes := 0 |
| 35 | for err := range results { |
| 36 | if err == nil { |
| 37 | successes++ |
| 38 | } |
| 39 | } |
| 40 | if successes != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='running' AND message_id=?", second.MessageID) != 1 { |
| 41 | t.Fatal("single writer or message ordering broken", successes) |
| 42 | } |
| 43 | if f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { |
| 44 | t.Fatal("turn not admitted exactly once") |
| 45 | } |
| 46 | other := p |
| 47 | other.RunnerID = "another-runner" |
| 48 | if _, err := x.ClaimCoordinator(ctx, other, first.ID, first.Revision); err == nil { |
| 49 | t.Fatal("other runner claimed binding") |
| 50 | } |
| 51 | } |
| 52 | func TestCoordinatorAuthorityRevoked(t *testing.T) { |
| 53 | for _, change := range []string{"membership", "role", "generation", "connection", "runner", "lookup"} { |
| 54 | t.Run(change, func(t *testing.T) { |
| 55 | f, x, p, _ := coordinatorFixture(t) |
| 56 | turn := queueCoordinator(t, f, "hello", "turn") |
| 57 | claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 58 | must(t, err) |
| 59 | switch change { |
| 60 | case "membership": |
| 61 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 62 | case "role": |
| 63 | f.exec(t, "UPDATE members SET revision=revision+1,role='member' WHERE address=?", owner.Address) |
| 64 | case "generation": |
| 65 | f.exec(t, "UPDATE coordinator_bindings SET generation=generation+1") |
| 66 | case "connection": |
| 67 | f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") |
| 68 | case "runner": |
| 69 | f.exec(t, "UPDATE runners SET revoked_at=?", time.Now().UTC()) |
| 70 | case "lookup": |
| 71 | f.exec(t, "ALTER TABLE members RENAME TO missing_members") |
| 72 | } |
| 73 | if err = x.ValidateCoordinator(ctx, p, claim); err == nil { |
| 74 | t.Fatal("tool use ignored revoked authority") |
| 75 | } |
| 76 | if _, err = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| 77 | t.Fatal("claim ignored revoked authority") |
| 78 | } |
| 79 | if _, err = x.RenewCoordinator(ctx, p, claim); err == nil { |
| 80 | t.Fatal("renew ignored revoked authority") |
| 81 | } |
| 82 | }) |
| 83 | } |
| 84 | } |
| 85 | func TestCoordinatorTurnReplay(t *testing.T) { |
| 86 | f, x, p, b := coordinatorFixture(t) |
| 87 | turn := queueCoordinator(t, f, "hello", "turn") |
| 88 | again, err := f.Store.QueueCoordinatorTurn(ctx, owner, turn.MessageID, 0, equipo.Mutation{RequestID: "turn"}) |
| 89 | must(t, err) |
| 90 | if again.ID != turn.ID { |
| 91 | t.Fatal("queue replay duplicated turn") |
| 92 | } |
| 93 | claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 94 | must(t, err) |
| 95 | if claim.Brief.AttemptDeadline.IsZero() || claim.Brief.AttemptDeadline != claim.AttemptDeadline { |
| 96 | t.Fatal("coordinator brief omitted attempt deadline") |
| 97 | } |
| 98 | againClaim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 99 | must(t, err) |
| 100 | if againClaim.Handle.Attempt != claim.Handle.Attempt || f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { |
| 101 | t.Fatal("claim replay duplicated admission") |
| 102 | } |
| 103 | msg, err := f.Store.SendMessage(ctx, owner, "", "different", equipo.Mutation{RequestID: "different"}) |
| 104 | must(t, err) |
| 105 | if _, err = f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: "turn"}); err == nil { |
| 106 | t.Fatal("changed message replay accepted") |
| 107 | } |
| 108 | event := runnerproto.Event{Kind: "turn_completed", Payload: json.RawMessage(`{}`)} |
| 109 | if err = x.CompleteCoordinator(ctx, p, claim, event); err == nil { |
| 110 | t.Fatal("process completion proved delivery") |
| 111 | } |
| 112 | if _, err = f.Store.RetryCoordinatorTurn(ctx, owner, turn.ID, equipo.Mutation{RequestID: "retry", Revision: turn.Revision}); err == nil { |
| 113 | t.Fatal("retry ignored containment") |
| 114 | } |
| 115 | _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 116 | if err == nil { |
| 117 | t.Fatal("reset advanced before containment") |
| 118 | } |
| 119 | if f.count(t, "SELECT count(*) FROM attempts WHERE state='stopping'") != 1 { |
| 120 | t.Fatal("reset did not fence active attempt") |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | func TestCoordinatorTurnDeliveryAtomic(t *testing.T) { |
| 125 | f, x, p, _ := coordinatorFixture(t) |
| 126 | turn := queueCoordinator(t, f, "hello", "delivery") |
| 127 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 128 | must(t, err) |
| 129 | event := runnerproto.Event{Version: 2, ID: "delivered", TaskID: turn.ID, AssignmentID: turn.ID, ServerID: "fixture", AgentID: "fixture", SessionID: "session", TurnID: turn.ID, Kind: "coordinator.delivery", Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action, Payload: json.RawMessage(`{"result":"committed"}`), SourceTime: time.Now().UTC()} |
| 130 | if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| 131 | t.Fatal("missing delivery validator accepted") |
| 132 | } |
| 133 | x.SetRunnerValidators(equipo.RunnerValidators{CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) { |
| 134 | return "Recorded answer", team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess}, nil |
| 135 | }, Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 136 | f.exec(t, "CREATE TRIGGER coordinator_delivery_failure BEFORE INSERT ON conversation_messages BEGIN SELECT RAISE(ABORT,'fixture delivery failure'); END") |
| 137 | if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| 138 | t.Fatal("delivery failure ignored") |
| 139 | } |
| 140 | if f.count(t, "SELECT count(*) FROM attempts WHERE state='succeeded'") != 0 || f.count(t, "SELECT count(*) FROM reservations WHERE state='settled'") != 0 { |
| 141 | t.Fatal("delivery failure partially committed") |
| 142 | } |
| 143 | f.exec(t, "DROP TRIGGER coordinator_delivery_failure") |
| 144 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 145 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 146 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 1 || f.count(t, "SELECT count(*) FROM jobs WHERE state='succeeded'") != 1 { |
| 147 | t.Fatal("turn delivery was not atomic and unique") |
| 148 | } |
| 149 | if f.count(t, "SELECT count(*) FROM audit_events WHERE actor=? AND delegating_person=? AND kind='coordinator.delivered'", "coordinator:"+c.Binding.ID, owner.Address) != 1 { |
| 150 | t.Fatal("coordinator impersonated person") |
| 151 | } |
| 152 | event.Payload = json.RawMessage(`{"result":"changed"}`) |
| 153 | if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| 154 | t.Fatal("changed delivery replay accepted") |
| 155 | } |
| 156 | next := queueCoordinator(t, f, "next", "next") |
| 157 | if _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision); err == nil { |
| 158 | t.Fatal("delivery bypassed containment") |
| 159 | } |
| 160 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 161 | second, err := x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| 162 | must(t, err) |
| 163 | for _, message := range second.Context.Recent { |
| 164 | if message.AuthorKind != "person" { |
| 165 | t.Fatal("unclassified prior project material entered coordinator context") |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | func TestCoordinatorTurnResetRetry(t *testing.T) { |
| 170 | f, x, p, b := coordinatorFixture(t) |
| 171 | turn := queueCoordinator(t, f, "hello", "retry-test") |
| 172 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 173 | must(t, err) |
| 174 | x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 175 | _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 176 | if err == nil { |
| 177 | t.Fatal("reset skipped containment") |
| 178 | } |
| 179 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 180 | b2, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 181 | must(t, err) |
| 182 | if b2.Generation != b.Generation+1 { |
| 183 | t.Fatal("reset did not advance generation") |
| 184 | } |
| 185 | if _, err = f.Store.QueueCoordinatorTurn(ctx, owner, turn.MessageID, 0, equipo.Mutation{RequestID: "retry-test"}); err == nil { |
| 186 | t.Fatal("queue replay ignored changed binding") |
| 187 | } |
| 188 | retry, err := f.Store.RetryCoordinatorTurn(ctx, owner, turn.ID, equipo.Mutation{RequestID: "retry", Revision: 2}) |
| 189 | must(t, err) |
| 190 | c2, err := x.ClaimCoordinator(ctx, p, retry.ID, retry.Revision) |
| 191 | must(t, err) |
| 192 | if c2.Scope.Job == c.Scope.Job || c2.Handle.Attempt == c.Handle.Attempt || f.count(t, "SELECT count(*) FROM reservations") != 2 { |
| 193 | t.Fatal("retry reused admission") |
| 194 | } |
| 195 | if err = x.ValidateCoordinator(ctx, p, c); err == nil { |
| 196 | t.Fatal("old generation still works") |
| 197 | } |
| 198 | } |
| 199 | func TestCoordinatorBudgetAbsentLimit(t *testing.T) { |
| 200 | f, x, p, b := coordinatorFixture(t) |
| 201 | f.exec(t, "DELETE FROM coordinator_limits") |
| 202 | turn := queueCoordinator(t, f, "hello", "no-limits") |
| 203 | if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| 204 | t.Fatal("missing personal budget granted authority") |
| 205 | } |
| 206 | if f.count(t, "SELECT count(*) FROM jobs") != 0 { |
| 207 | t.Fatal("failed admission left a job") |
| 208 | } |
| 209 | f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| 210 | if err := f.Store.SetCoordinatorLimits(ctx, peer, owner.Address, team.Limits{Calls: 1, InputTokens: 100, OutputTokens: 50, Seconds: 1200}, equipo.Mutation{RequestID: "unauthorized"}); err == nil { |
| 211 | t.Fatal("non-owner set limits") |
| 212 | } |
| 213 | if _, err := f.Store.SaveCoordinatorBinding(ctx, peer, b.RunnerID, b.ConnectionID, equipo.Mutation{RequestID: "borrow"}); err == nil { |
| 214 | t.Fatal("borrowed another person's subscription") |
| 215 | } |
| 216 | } |
| 217 | func TestCoordinatorAuthorityProjectContext(t *testing.T) { |
| 218 | f, x, p, _ := coordinatorFixture(t) |
| 219 | var projectID int64 |
| 220 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&projectID)) |
| 221 | f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`) |
| 222 | msg, err := f.Store.SendMessage(ctx, owner, "", "project question", equipo.Mutation{RequestID: "project"}) |
| 223 | must(t, err) |
| 224 | turn, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, projectID, equipo.Mutation{RequestID: "project"}) |
| 225 | must(t, err) |
| 226 | if _, err = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| 227 | t.Fatal("restricted project material entered prompt") |
| 228 | } |
| 229 | f.exec(t, "UPDATE coordinator_turns SET state='superseded'") |
| 230 | general := queueCoordinator(t, f, "general question", "general") |
| 231 | c, err := x.ClaimCoordinator(ctx, p, general.ID, general.Revision) |
| 232 | must(t, err) |
| 233 | if len(c.Context.Retrieved) != 0 { |
| 234 | t.Fatal("general turn disclosed restricted project", c.Context) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | func TestCoordinatorSingleWriterStorageGuard(t *testing.T) { |
| 239 | f, _, _, b := coordinatorFixture(t) |
| 240 | a := queueCoordinator(t, f, "first", "first") |
| 241 | z := queueCoordinator(t, f, "second", "second") |
| 242 | f.exec(t, "UPDATE coordinator_turns SET state='running' WHERE id=?", a.ID) |
| 243 | if _, err := f.DB.Writer().Exec("UPDATE coordinator_turns SET state='running' WHERE id=?", z.ID); err == nil { |
| 244 | t.Fatal("storage permits two active coordinator turns", b.ID) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | func TestCoordinatorAuthorityClaimTampering(t *testing.T) { |
| 249 | f, x, p, _ := coordinatorFixture(t) |
| 250 | turn := queueCoordinator(t, f, "hello", "tamper") |
| 251 | claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 252 | must(t, err) |
| 253 | for _, change := range []func(*equipo.CoordinatorClaim){func(c *equipo.CoordinatorClaim) { c.Handle.Fence++ }, func(c *equipo.CoordinatorClaim) { c.Admission.Dispatch.Action++ }, func(c *equipo.CoordinatorClaim) { c.Brief.Selection.Person = peer.Address }, func(c *equipo.CoordinatorClaim) { |
| 254 | c.Context.Sources = []runnerproto.SourceSnapshot{{Payload: json.RawMessage(`{"forged":true}`)}} |
| 255 | }} { |
| 256 | changed := claim |
| 257 | change(&changed) |
| 258 | if err = x.ValidateCoordinator(ctx, p, changed); err == nil { |
| 259 | t.Fatal("changed claim authorized tool use") |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | func TestCoordinatorTurnResetPreservesQueuedMessages(t *testing.T) { |
| 265 | f, x, p, b := coordinatorFixture(t) |
| 266 | queueCoordinator(t, f, "first", "queued-first") |
| 267 | last := queueCoordinator(t, f, "second", "queued-second") |
| 268 | b, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset-queued", Revision: b.Revision}) |
| 269 | must(t, err) |
| 270 | turns, err := x.PollCoordinator(ctx, p) |
| 271 | must(t, err) |
| 272 | if len(turns) != 1 || turns[0].MessageID != last.MessageID || turns[0].Generation != b.Generation { |
| 273 | t.Fatal("reset lost queued messages", turns) |
| 274 | } |
| 275 | _, err = x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision) |
| 276 | must(t, err) |
| 277 | } |
| 278 | |