oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "maps"
8 "net/netip"
9 "path/filepath"
10 "slices"
11 "strings"
12 "sync"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/fakepi"
17 "amadan.net/oficina/equipo/internal/runner/connect"
18 "amadan.net/oficina/equipo/internal/runner/metered"
19 "amadan.net/oficina/equipo/internal/wire"
20)
21
22// The S5b finish line (connectors spec rev 3.3 §16.7), with fakes: Pi is
23// fakepi in the real containment, TensorX a fake on 127.0.0.1 answering
24// the first-use probes.
25
26// The finish line's allowed set: GLM's strong and cheap models, Kimi's
27// strong one and DeepSeek's standard one.
28var finishSet = []string{"z-ai/glm-5.3", "z-ai/glm-5.3-flash", "moonshotai/kimi-k3.1-pro", "deepseek/deepseek-v4.1-flash"}
29
30// modelsRig is a Pi rig whose TensorX connection allows models (its key
31// proven on the cheapest at connect, the rest unprobed) and whose
32// first-use probes go to a fake TensorX.
33func modelsRig(t *testing.T, allowed ...string) (*piRig, *fakeTensorX) {
34 t.Helper()
35 r := newPiRig(t, fakePiInstall(t), bigBudget)
36 r.urgent()
37 fake := newFakeTensorX(t, fakepi.TestKey)
38 c := &Connector{State: r.state, Conns: r.conns}
39 c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL }
40 r.conns.Prober = c.probeModel
41 // A fresh set, every model unprobed but the connect-time proof's: the
42 // cheapest allowed.
43 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
44 // The key lists every TensorX model (read at connect).
45 if err := metered.SetListed(r.ctx, tx, piLocal, slices.Sorted(maps.Keys(metered.Tables[metered.Current[wire.ProviderTensorX]].Models))); err != nil {
46 return err
47 }
48 return metered.InitModels(r.ctx, tx, piLocal, allowed, 2)
49 }); err != nil {
50 t.Fatal(err)
51 }
52 cheapest := metered.Cheapest(wire.ProviderTensorX, metered.Current[wire.ProviderTensorX], allowed)
53 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
54 return metered.MarkModel(r.ctx, tx, piLocal, cheapest, wire.ModelHealthy, "", time.Now())
55 }); err != nil {
56 t.Fatal(err)
57 }
58 return r, fake
59}
60
61// setModels applies the person's set at revision, as the models frame does.
62func (r *piRig) setModels(revision int64, allowed ...string) {
63 r.t.Helper()
64 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
65 ok, err := metered.SetModels(r.ctx, tx, piLocal, "cn_tx", allowed, revision)
66 if err == nil && !ok {
67 r.t.Fatalf("set %v at %d not applied", allowed, revision)
68 }
69 return err
70 }); err != nil {
71 r.t.Fatal(err)
72 }
73}
74
75func (r *piRig) modelState(model string) metered.Model {
76 r.t.Helper()
77 ms, err := metered.Models(r.ctx, r.state.db, piLocal)
78 if err != nil {
79 r.t.Fatal(err)
80 }
81 for _, m := range ms {
82 if m.ID == model {
83 return m
84 }
85 }
86 return metered.Model{}
87}
88
89// ran reports whether an Engineering step ran its harness to the end
90// (the rig's forge cannot take the push, so it ends push_failed).
91func ran(rep wire.StepReport) bool {
92 return rep.Termination && (rep.State == wire.StepDone || rep.Reason == "push_failed") && len(rep.Usage) == 1 && rep.Usage[0].Complete
93}
94
95// engineering runs one Engineering step through the whole step path.
96func (r *piRig) engineering(task, step, brief string) wire.StepReport {
97 r.t.Helper()
98 base := r.review.BaseSHA
99 row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: task, StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/" + task + "-fix", BaseSHA: base, Title: "Fix the typo", Brief: brief, Findings: []wire.Finding{}, Priority: wire.PriorityUrgent}, Base: base}
100 if err := r.state.AcceptDispatch(r.ctx, "f-"+step, row.DispatchCommand); err != nil {
101 r.t.Fatal(err)
102 }
103 return r.e.Exec(r.ctx, row, func(wire.StepReport) {})
104}
105
106// admission is what an attempt's admission recorded (§16.5).
107func (r *piRig) admission(step string) (model, family, tier, priceVersion, tierVersion string) {
108 r.t.Helper()
109 if err := r.state.db.QueryRow("SELECT model, family, tier, price_version, tier_version FROM admissions WHERE step_id=? AND attempt=1", step).Scan(&model, &family, &tier, &priceVersion, &tierVersion); err != nil {
110 r.t.Fatal(err)
111 }
112 return
113}
114
115func (r *piRig) probeFrames() []wire.UsageReport {
116 r.t.Helper()
117 frames, _, err := r.state.Unacked(r.ctx, 0)
118 if err != nil {
119 r.t.Fatal(err)
120 }
121 var out []wire.UsageReport
122 for _, f := range frames {
123 var v wire.UsageReport
124 if f.Type == wire.FrameUsage && json.Unmarshal(f.Data, &v) == nil && v.ProbeID != "" {
125 out = append(out, v)
126 }
127 }
128 return out
129}
130
131// spendTo charges the connection up to day micro-units today.
132func (r *piRig) spendTo(day int64) {
133 r.t.Helper()
134 now := time.Now().UTC()
135 if _, err := r.state.db.Exec("INSERT INTO budget_charge(turn, step, attempt, connection, model, holder, cost_micros, reported_micros, currency, price_version, day, month, recorded_at) VALUES('', 'earlier', 1, ?, 'z-ai/glm-5.3', 'x', ?, NULL, 'USD', ?, ?, ?, ?)", piLocal, day, metered.Current[wire.ProviderTensorX], now.Format("2006-01-02"), now.Format("2006-01"), now.Format(time.RFC3339Nano)); err != nil {
136 r.t.Fatal(err)
137 }
138}
139
140// §16.7: a first Engineering pass probes the strongest allowed model
141// inside its own admission, then runs it; its admission, its usage row
142// and its family name that model (§16.6 (f): the harness ran the chosen
143// model). At 0.8 fill the next pass runs a cheap model with no probe.
144func TestModelsEngineeringProbesThenRunsTheStrongest(t *testing.T) {
145 r, fake := modelsRig(t, finishSet...)
146 rep := r.engineering("tk1", "e1", "edit:README.md|teh|the")
147 if !ran(rep) || rep.Family != "glm" {
148 t.Fatalf("first pass: %+v", rep)
149 }
150 if fake.probeCount() != 1 || fake.probes[0] != "z-ai/glm-5.3" {
151 t.Fatalf("probes %v", fake.probes)
152 }
153 probes := r.probeFrames()
154 if len(probes) != 1 || probes[0].ProbeID != "probe:e1:1:z-ai/glm-5.3" || len(probes[0].Rows) != 1 || probes[0].Rows[0].CostMicros == nil {
155 t.Fatalf("probe usage %+v", probes)
156 }
157 if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelHealthy {
158 t.Fatalf("probed model %+v", m)
159 }
160 if len(rep.Usage) != 1 || rep.Usage[0].Model != "z-ai/glm-5.3" || rep.Usage[0].Tier != "strong" || rep.Usage[0].TierVersion != metered.CurrentTiers || rep.Usage[0].ModelMismatch {
161 t.Fatalf("step usage %+v", rep.Usage)
162 }
163 if model, family, tier, pv, tv := r.admission("e1"); model != "z-ai/glm-5.3" || family != "glm" || tier != "strong" || pv != metered.Current[wire.ProviderTensorX] || tv != metered.CurrentTiers {
164 t.Fatalf("admission %s %s %s %s %s", model, family, tier, pv, tv)
165 }
166 // Two charges: the probe's and the step's; the slot free.
167 if n := r.charges(); n != 2 || !r.slotFree() {
168 t.Fatalf("charges %d, slot free %v", n, r.slotFree())
169 }
170 // At 0.8 fill: a cheap model, already proven at connect.
171 r.spendTo(800_000)
172 rep = r.engineering("tk2", "e2", "edit:README.md|teh|the")
173 if !ran(rep) || rep.Usage[0].Model != "z-ai/glm-5.3-flash" || rep.Usage[0].Tier != "cheap" {
174 t.Fatalf("at 0.8: %+v", rep)
175 }
176 if fake.probeCount() != 1 {
177 t.Fatalf("a proven model probed again: %v", fake.probes)
178 }
179}
180
181// §16.7: Review of a GLM step runs Kimi (another family first); with
182// Kimi and DeepSeek unticked it runs GLM, the same family, labelled
183// same_family when Engineering ran on another connection (and
184// same_account on its own, as built). Engineering's family is the one
185// its attempt recorded (the dispatch's avoid_family), never the
186// connection's.
187func TestModelsReviewAcrossFamilies(t *testing.T) {
188 r, _ := modelsRig(t, finishSet...)
189 r.review.AvoidAccount, r.review.AvoidFamily = piLocal, "glm"
190 rep := r.runReview("", 1)
191 if rep.State != wire.StepDone || rep.Family != "kimi" || rep.ReviewLabel != wire.ReviewOtherFamily || len(rep.Usage) != 1 || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" {
192 t.Fatalf("review of glm: %+v", rep)
193 }
194 // Engineering's family is read from its record: a kimi Engineering
195 // step on this same connection sends Review to GLM or DeepSeek.
196 r.review.AvoidFamily = "kimi"
197 if rep := r.runReview("", 2); rep.Family == "kimi" || rep.ReviewLabel != wire.ReviewOtherFamily {
198 t.Fatalf("review of kimi: %+v", rep)
199 }
200 // Kimi and DeepSeek unticked: GLM, on another account than
201 // Engineering's.
202 r.setModels(3, "z-ai/glm-5.3", "z-ai/glm-5.3-flash")
203 const second = "tensorx-second000000"
204 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
205 if err := metered.Add(r.ctx, tx, metered.Conn{Connection: "cn_tx2", LocalID: second, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.2", Home: t.TempDir(), Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: wire.Budget{Day: 1, Month: 1, Revision: 1}}, time.Now()); err != nil {
206 return err
207 }
208 if err := metered.Checked(r.ctx, tx, second, true); err != nil {
209 return err
210 }
211 return provenModels(r.ctx, tx, second, "z-ai/glm-5.2")
212 }); err != nil {
213 t.Fatal(err)
214 }
215 // The second key (Engineering's) is at its budget; this one reviews
216 // (another connection at the same rule would anyway).
217 now := time.Now().UTC()
218 if _, err := r.state.db.Exec("INSERT INTO budget_charge(turn, step, attempt, connection, model, holder, cost_micros, reported_micros, currency, price_version, day, month, recorded_at) VALUES('', 'earlier', 1, ?, 'z-ai/glm-5.2', 'x', 1, NULL, 'USD', ?, ?, ?, ?)", second, metered.Current[wire.ProviderTensorX], now.Format("2006-01-02"), now.Format("2006-01"), now.Format(time.RFC3339Nano)); err != nil {
219 t.Fatal(err)
220 }
221 r.review.AvoidAccount, r.review.AvoidFamily = second, "glm"
222 if rep := r.runReview("", 3); rep.State != wire.StepDone || rep.Family != "glm" || rep.ReviewLabel != wire.ReviewSameFamily || rep.Account != piLocal {
223 t.Fatalf("only glm, engineering elsewhere: %+v", rep)
224 }
225 // Engineering on this connection, and no other: its own, same_account.
226 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.Retire(r.ctx, tx, second) }); err != nil {
227 t.Fatal(err)
228 }
229 r.review.AvoidAccount = piLocal
230 if rep := r.runReview("", 4); rep.Family != "glm" || rep.ReviewLabel != wire.ReviewSameAccount {
231 t.Fatalf("only glm, engineering here: %+v", rep)
232 }
233}
234
235// §16.7, §16.6 (d): a question whose session's model was unticked fails
236// model_unavailable; it never runs on another model or connection, and
237// nothing is admitted or charged for it.
238func TestModelsQuestionOnAnUntickedModel(t *testing.T) {
239 r, _ := modelsRig(t, finishSet...)
240 r.review.AvoidAccount, r.review.AvoidFamily = piLocal, "glm"
241 rep := r.runReview("", 1)
242 if rep.Family != "kimi" || !rep.Askable {
243 t.Fatalf("review %+v", rep)
244 }
245 kept, ok, err := r.state.keptSessionFor(r.ctx, rep.StepID)
246 if err != nil || !ok || kept.Model != "moonshotai/kimi-k3.1-pro" || kept.Family != "kimi" {
247 t.Fatalf("kept session %+v %v %v", kept, ok, err)
248 }
249 r.setModels(3, "z-ai/glm-5.3", "z-ai/glm-5.3-flash", "deepseek/deepseek-v4.1-flash")
250 charges := r.charges()
251 answer := r.ask(rep, "q1")
252 if answer.State != wire.QuestionFailed || answer.Reason != wire.ReasonModelUnavailable || len(answer.Usage) != 0 {
253 t.Fatalf("answer %+v", answer)
254 }
255 if r.charges() != charges || !r.slotFree() {
256 t.Fatalf("charged %d -> %d, slot free %v", charges, r.charges(), r.slotFree())
257 }
258 // Ticked again but unhealthy: the same.
259 r.setModels(4, finishSet...)
260 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
261 return metered.MarkModel(r.ctx, tx, piLocal, "moonshotai/kimi-k3.1-pro", wire.ModelUnhealthy, wire.ModelNotFound, time.Now())
262 }); err != nil {
263 t.Fatal(err)
264 }
265 if answer := r.ask(rep, "q2"); answer.Reason != wire.ReasonModelUnavailable {
266 t.Fatalf("unhealthy: %+v", answer)
267 }
268 // Healthy again: it answers, on that model.
269 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
270 return metered.MarkModel(r.ctx, tx, piLocal, "moonshotai/kimi-k3.1-pro", wire.ModelHealthy, "", time.Now())
271 }); err != nil {
272 t.Fatal(err)
273 }
274 if answer := r.ask(rep, "q3"); answer.State != wire.QuestionAnswered || len(answer.Usage) != 1 || answer.Usage[0].Model != "moonshotai/kimi-k3.1-pro" {
275 t.Fatalf("healthy: %+v", answer)
276 }
277}
278
279// ask asks a step's kept session a question and returns its final report.
280func (r *piRig) ask(rep wire.StepReport, id string) wire.AnswerReport {
281 r.t.Helper()
282 a := askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: id, Attempt: 1, Specialist: wire.SpecialistReview, Repo: r.review.Repo, Branch: r.review.Branch, BaseSHA: r.review.BaseSHA, CandidateSHA: r.review.CandidateSHA, Title: "Fix the typo", Text: "Why approve?"}}
283 if err := r.state.AcceptAsk(r.ctx, "f-"+id, a.AskCommand); err != nil {
284 r.t.Fatal(err)
285 }
286 se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}}
287 local, model, ok := se.meteredAsk(r.ctx, a)
288 if !ok || local != piLocal {
289 r.t.Fatalf("the question is not on its metered connection: %q %v", local, ok)
290 }
291 se.askMetered(r.ctx, r.ctx, a, local, model, func(wire.AnswerReport) {})
292 frames, _, err := r.state.Unacked(r.ctx, 0)
293 if err != nil {
294 r.t.Fatal(err)
295 }
296 var out wire.AnswerReport
297 for _, f := range frames {
298 var v wire.AnswerReport
299 if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == id && wire.QuestionTerminal(v.State) {
300 out = v
301 }
302 }
303 return out
304}
305
306// §16.7, §16.4: a probe answered by another model marks that model
307// unhealthy (other_model, with its time) and the step runs on the next
308// pick; a model the provider does not have is unhealthy too (not_found)
309// and nothing is charged for it.
310func TestModelsProbeAnsweredByAnotherModel(t *testing.T) {
311 r, fake := modelsRig(t, finishSet...)
312 // The answering model is priced: its usage is charged as its own, so
313 // the spend stays known.
314 fake.swap = map[string]string{"z-ai/glm-5.3": "z-ai/glm-5.2"}
315 rep := r.engineering("tk1", "e1", "edit:README.md|teh|the")
316 if !ran(rep) || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" {
317 t.Fatalf("step %+v", rep)
318 }
319 if strings.Join(fake.probes, ",") != "z-ai/glm-5.3,moonshotai/kimi-k3.1-pro" {
320 t.Fatalf("probes %v", fake.probes)
321 }
322 if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelOtherAnswered || m.FailedAt.IsZero() {
323 t.Fatalf("swapped model %+v", m)
324 }
325 if r.conn().SpendUnknown {
326 t.Fatal("the answering model's usage was not priced as its own")
327 }
328 r2, fake2 := modelsRig(t, finishSet...)
329 fake2.gone = map[string]bool{"z-ai/glm-5.3": true}
330 before := r2.charges()
331 rep = r2.engineering("tk1", "e1", "edit:README.md|teh|the")
332 if !ran(rep) || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" {
333 t.Fatalf("after not found: %+v", rep)
334 }
335 if m := r2.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelNotFound {
336 t.Fatalf("missing model %+v", m)
337 }
338 // Charged: kimi's probe and the step; nothing for the missing model.
339 if n := r2.charges(); n != before+2 {
340 t.Fatalf("charges %d -> %d", before, n)
341 }
342}
343
344// §16.4: a probe whose answer carries no usable usage leaves the spend
345// unknown: the connection pauses and nothing else is probed or run until
346// Resume. A refused key is connection-wide: no model is marked.
347func TestModelsProbeFailures(t *testing.T) {
348 r, fake := modelsRig(t, finishSet...)
349 fake.mu.Lock()
350 fake.usage = `null`
351 fake.mu.Unlock()
352 rep := r.engineering("tk1", "e1", "edit:README.md|teh|the")
353 if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldSpendUnknown {
354 t.Fatalf("spend unknown: %+v hold %+v", rep.Usage, rep.Hold)
355 }
356 if fake.probeCount() != 1 || !r.conn().SpendUnknown {
357 t.Fatalf("probes %v, paused %v", fake.probes, r.conn().SpendUnknown)
358 }
359 // Nothing else is probed, or run, until Resume.
360 if rep := r.engineering("tk2", "e2", "edit:README.md|teh|the"); rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldSpendUnknown || fake.probeCount() != 1 {
361 t.Fatalf("after the pause: %+v, probes %v", rep.Hold, fake.probes)
362 }
363 r2, fake2 := modelsRig(t, finishSet...)
364 fake2.mu.Lock()
365 fake2.key = "another-key"
366 fake2.mu.Unlock()
367 rep = r2.engineering("tk1", "e1", "edit:README.md|teh|the")
368 if ran(rep) {
369 t.Fatalf("ran on a refused key: %+v", rep)
370 }
371 if !r2.conn().Refused || r2.modelState("z-ai/glm-5.3").State != wire.ModelUnprobed {
372 t.Fatalf("refused %v, model %+v", r2.conn().Refused, r2.modelState("z-ai/glm-5.3"))
373 }
374}
375
376// §16.4: an unhealthy model is eligible again only on demand: never
377// before a day has passed since it failed, then probed as on first use
378// when a step would pick it.
379func TestModelsUnhealthyRetriedOnDemand(t *testing.T) {
380 r, fake := modelsRig(t, finishSet...)
381 failed := time.Now().Add(-23 * time.Hour)
382 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
383 return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelUnhealthy, wire.ModelNotFound, failed)
384 }); err != nil {
385 t.Fatal(err)
386 }
387 fake.swap = map[string]string{}
388 if rep := r.engineering("tk1", "e1", "edit:README.md|teh|the"); !ran(rep) || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" {
389 t.Fatalf("within a day: %+v", rep)
390 }
391 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
392 return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelUnhealthy, wire.ModelNotFound, time.Now().Add(-25*time.Hour))
393 }); err != nil {
394 t.Fatal(err)
395 }
396 if rep := r.engineering("tk2", "e2", "edit:README.md|teh|the"); !ran(rep) || rep.Usage[0].Model != "z-ai/glm-5.3" {
397 t.Fatalf("after a day: %+v", rep)
398 }
399 if !slices.Contains(fake.probes, "z-ai/glm-5.3") || r.modelState("z-ai/glm-5.3").State != wire.ModelHealthy {
400 t.Fatalf("probes %v, model %+v", fake.probes, r.modelState("z-ai/glm-5.3"))
401 }
402}
403
404// §16.5: a step whose usage names another model than the one chosen is
405// charged at that model's price, marked model_mismatch, and the chosen
406// model is unhealthy until Check again.
407func TestModelsStepMismatch(t *testing.T) {
408 r, _ := modelsRig(t, "z-ai/glm-5.3", "z-ai/glm-5.3-flash")
409 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
410 return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelHealthy, "", time.Now())
411 }); err != nil {
412 t.Fatal(err)
413 }
414 rep := r.runReview("answeredby:z-ai/glm-5.3-flash", 1)
415 if len(rep.Usage) != 1 || rep.Usage[0].Model != "z-ai/glm-5.3-flash" || !rep.Usage[0].ModelMismatch || rep.Usage[0].CostMicros == nil {
416 t.Fatalf("usage %+v", rep.Usage)
417 }
418 if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelMismatch {
419 t.Fatalf("chosen model %+v", m)
420 }
421}
422
423// §16.7: a connection S1 made (one model, no allowed set, an admission
424// and a kept session with no model) behaves exactly as before once the
425// runner migrates its thin.db: the set is its one model, healthy; its
426// steps and questions run on it; hello names it as before.
427func TestModelsMigratedConnectionAsBefore(t *testing.T) {
428 r := newPiRig(t, fakePiInstall(t), bigBudget)
429 r.urgent()
430 // Back to S1's shape: no set, no models revision, and an admission and
431 // a kept session with no model.
432 if _, err := r.state.db.Exec("DELETE FROM metered_models"); err != nil {
433 t.Fatal(err)
434 }
435 if _, err := r.state.db.Exec("UPDATE metered_connections SET models_revision=0"); err != nil {
436 t.Fatal(err)
437 }
438 if _, err := r.state.db.Exec("INSERT INTO admissions(step_id, attempt, step_revision, connection, reason, at) VALUES('old', 1, 1, ?, 'metered_urgent', '1')", piLocal); err != nil {
439 t.Fatal(err)
440 }
441 if _, err := r.state.db.Exec("INSERT INTO kept_sessions(step_id, attempt, task_id, person, specialist, account, session_id, dir, created_at, used_at) VALUES('old', 1, 'tk0', ?, 'review', ?, 's', '/nowhere', '1', '1')", connPerson, piLocal); err != nil {
442 t.Fatal(err)
443 }
444 if err := migrateModels(r.ctx, r.state.db); err != nil {
445 t.Fatal(err)
446 }
447 if ms, _ := metered.Models(r.ctx, r.state.db, piLocal); len(ms) != 1 || ms[0].ID != "z-ai/glm-5.3" || ms[0].State != wire.ModelHealthy {
448 t.Fatalf("set %+v", ms)
449 }
450 var model, family string
451 r.state.db.QueryRow("SELECT model, family FROM admissions WHERE step_id='old'").Scan(&model, &family)
452 if model != "z-ai/glm-5.3" || family != "glm" {
453 t.Fatalf("admission backfilled %q %q", model, family)
454 }
455 if k, _, _ := r.state.keptSessionFor(r.ctx, "old"); k.Model != "z-ai/glm-5.3" || k.Family != "glm" {
456 t.Fatalf("kept session backfilled %+v", k)
457 }
458 rep := r.runReview("", 1)
459 if rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || rep.Usage[0].Model != "z-ai/glm-5.3" {
460 t.Fatalf("review %+v", rep)
461 }
462 if a := r.ask(rep, "q1"); a.State != wire.QuestionAnswered {
463 t.Fatalf("question %+v", a)
464 }
465 held, ok := heldOf(r.conns, piLocal)
466 if !ok || held.Model != "z-ai/glm-5.3" || held.ModelsRevision != 1 || len(held.Models) != 1 {
467 t.Fatalf("hello %+v", held)
468 }
469}
470
471func heldOf(c *Conns, local string) (wire.HeldConnection, bool) {
472 for _, h := range c.Held() {
473 if h.LocalID == local {
474 return h, true
475 }
476 }
477 return wire.HeldConnection{}, false
478}
479
480// §16.1: the models frame applies a set once, only above the revision
481// held and only for the connection, person and runner name it names;
482// hello then carries the applied revision and states. A connecting
483// attempt takes the frame as its card's answer and proves the key on the
484// cheapest allowed model only.
485func TestModelsFrame(t *testing.T) {
486 const key = "tx-fake-key-fake-key"
487 r := newTokenRig(t)
488 fake := newFakeTensorX(t, key)
489 fake.list = `{"data":[{"id":"z-ai/glm-5.3"},{"id":"z-ai/glm-5.3-flash"},{"id":"moonshotai/kimi-k3"},{"id":"vendor/unpriced"}]}`
490 c := r.meteredConnector(fake)
491 home := r.startAPIKey(c, "cn_tx")
492 local := filepath.Base(home)
493 if !r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) {
494 t.Fatalf("secret refused: %v", r.errs)
495 }
496 p := r.card("cn_tx", wire.PromptModels)
497 if strings.Join(eligibleChoices(p), ",") != "moonshotai/kimi-k3,z-ai/glm-5.3,z-ai/glm-5.3-flash" || len(p.Choices) != 4 {
498 t.Fatalf("card %+v", p.Choices)
499 }
500 // A set with a model that cannot be allowed is not taken.
501 if err := c.Models(r.ctx, "f-models-0", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, Allowed: []string{"vendor/unpriced"}, Revision: 1}); err != nil {
502 t.Fatal(err)
503 }
504 if err := c.Models(r.ctx, "f-models-1", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, Allowed: []string{"z-ai/glm-5.3", "z-ai/glm-5.3-flash", "moonshotai/kimi-k3"}, Revision: 1}); err != nil {
505 t.Fatal(err)
506 }
507 if end := r.ended("cn_tx"); end.State != wire.ConnHealthy {
508 t.Fatalf("end %+v", end)
509 }
510 if strings.Join(fake.probes, ",") != "z-ai/glm-5.3-flash" {
511 t.Fatalf("connect probes %v", fake.probes)
512 }
513 held, ok := r.held(local)
514 if !ok || held.ModelsRevision != 1 || held.Model != "z-ai/glm-5.3-flash" || len(held.Models) != 3 {
515 t.Fatalf("hello %+v", held)
516 }
517 // The key's list, for the page: every listed model, the unpriced one
518 // not eligible.
519 if len(held.Choices) != 4 || held.Choices[3].ID != "z-ai/glm-5.3-flash" || held.Choices[1].ID != "vendor/unpriced" || held.Choices[1].Eligible || !held.Choices[0].Eligible {
520 t.Fatalf("choices %+v", held.Choices)
521 }
522 states := map[string]string{}
523 for _, m := range held.Models {
524 states[m.ID] = m.State
525 }
526 if states["z-ai/glm-5.3-flash"] != wire.ModelHealthy || states["z-ai/glm-5.3"] != wire.ModelUnprobed || states["moonshotai/kimi-k3"] != wire.ModelUnprobed {
527 t.Fatalf("states %v", states)
528 }
529 apply := func(id string, cmd wire.ModelsCommand) {
530 t.Helper()
531 if err := c.Models(r.ctx, id, cmd); err != nil {
532 t.Fatal(err)
533 }
534 }
535 revision := func() int64 {
536 h, _ := r.held(local)
537 return h.ModelsRevision
538 }
539 // Not above the revision held; another connection id; another person;
540 // another runner name: nothing applied.
541 apply("f-m-a", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 1})
542 apply("f-m-b", wire.ModelsCommand{Connection: "cn_other", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 2})
543 apply("f-m-c", wire.ModelsCommand{Connection: "cn_tx", Person: "someone@example.com", LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 2})
544 apply("f-m-d", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: "tensorx-other", Allowed: []string{"z-ai/glm-5.3"}, Revision: 2})
545 if revision() != 1 {
546 t.Fatalf("a set that does not bind was applied: revision %d", revision())
547 }
548 // A set it refuses (a model the key does not list) is acked, not
549 // applied: hello stays at the revision held (security round #4).
550 apply("f-m-r", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3", "z-ai/glm-5.2"}, Revision: 2})
551 if revision() != 1 {
552 t.Fatalf("a refused set shows applied: revision %d", revision())
553 }
554 apply("f-m-e", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 2})
555 if h, _ := r.held(local); h.ModelsRevision != 2 || len(h.Models) != 1 || h.Models[0].ID != "z-ai/glm-5.3" {
556 t.Fatalf("applied %+v", h)
557 }
558 // The same frame again changes nothing (consumed once).
559 apply("f-m-e", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3-flash"}, Revision: 3})
560 if revision() != 2 {
561 t.Fatal("a consumed frame applied again")
562 }
563 // Check again: the key on the cheapest allowed, then every unhealthy
564 // allowed model.
565 apply("f-m-f", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3", "moonshotai/kimi-k3", "z-ai/glm-5.3-flash"}, Revision: 3})
566 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
567 return metered.MarkModel(r.ctx, tx, local, "moonshotai/kimi-k3", wire.ModelUnhealthy, wire.ModelMismatch, time.Now())
568 }); err != nil {
569 t.Fatal(err)
570 }
571 fake.mu.Lock()
572 fake.probes = nil
573 fake.mu.Unlock()
574 conn, _, _ := metered.Get(r.ctx, r.state.db, local)
575 c.checkMetered(conn)
576 r.waitFor(func() bool { return fake.probeCount() == 2 && r.slotOf(local) }, "Check again's probes")
577 if strings.Join(fake.probes, ",") != "z-ai/glm-5.3-flash,moonshotai/kimi-k3" {
578 t.Fatalf("Check again probed %v", fake.probes)
579 }
580 if ms, _ := metered.Models(r.ctx, r.state.db, local); ms[0].ID != "moonshotai/kimi-k3" || ms[0].State != wire.ModelHealthy {
581 t.Fatalf("after Check again %+v", ms)
582 }
583}
584
585// slotOf reports whether a metered connection's slot is free.
586func (r *tokenRig) slotOf(local string) bool {
587 var holder string
588 r.state.db.QueryRow("SELECT holder FROM metered_slot WHERE local_id=?", local).Scan(&holder)
589 return holder == ""
590}
591
592// Security round #1: a request later in a step answered by another,
593// unpriced model is its own usage row: the mismatch is seen (the chosen
594// model unhealthy) and its spend is unknown (the connection paused),
595// never folded into the first model's row.
596func TestModelsLaterRequestOnAnotherModel(t *testing.T) {
597 r, _ := modelsRig(t, "z-ai/glm-5.3", "z-ai/glm-5.3-flash")
598 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
599 return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelHealthy, "", time.Now())
600 }); err != nil {
601 t.Fatal(err)
602 }
603 rep := r.runReview("thenby:vendor/other", 1)
604 if len(rep.Usage) != 2 || rep.Usage[0].Model != "z-ai/glm-5.3" || rep.Usage[0].ModelMismatch || rep.Usage[1].Model != "vendor/other" || !rep.Usage[1].ModelMismatch || rep.Usage[1].CostMicros != nil {
605 t.Fatalf("usage %+v", rep.Usage)
606 }
607 if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelMismatch {
608 t.Fatalf("chosen model %+v", m)
609 }
610 if !r.conn().SpendUnknown {
611 t.Fatal("an unpriced model's request left the spend known")
612 }
613}
614
615// §16.4, "After a step fails": a healthy model whose step fails with
616// model-not-found becomes unhealthy, and the next choice runs without it.
617func TestModelsStepModelGone(t *testing.T) {
618 r, _ := modelsRig(t, "z-ai/glm-5.3", "z-ai/glm-5.3-flash")
619 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
620 return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelHealthy, "", time.Now())
621 }); err != nil {
622 t.Fatal(err)
623 }
624 rep := r.runReview("modelgone", 1)
625 if rep.State != wire.StepFailed || len(rep.Usage) != 1 || rep.Usage[0].Model != "z-ai/glm-5.3" {
626 t.Fatalf("report %+v", rep)
627 }
628 if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelNotFound || m.FailedAt.IsZero() {
629 t.Fatalf("model %+v", m)
630 }
631 if rep := r.runReview("", 2); rep.State != wire.StepDone || rep.Usage[0].Model != "z-ai/glm-5.3-flash" {
632 t.Fatalf("next: %+v", rep)
633 }
634}
635
636// §16.3 rule 1: a fix round resumes its kept metered session only on the
637// model the session was created on; once that model leaves the set the
638// round starts afresh on the choice's model.
639func TestModelsFixRoundOnlyOnItsModel(t *testing.T) {
640 r, _ := modelsRig(t, finishSet...)
641 for _, m := range finishSet {
642 if err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
643 return metered.MarkModel(r.ctx, tx, piLocal, m, wire.ModelHealthy, "", time.Now())
644 }); err != nil {
645 t.Fatal(err)
646 }
647 }
648 base := r.review.CandidateSHA
649 round0 := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e0", Attempt: 1, Specialist: wire.SpecialistEngineering}}
650 dir := filepath.Join(t.TempDir(), "kept")
651 if err := r.state.keepSession(r.ctx, round0, wire.SpecialistEngineering, piLocal, "moonshotai/kimi-k3.1-pro", "kimi", "sess", dir, base, 10); err != nil {
652 t.Fatal(err)
653 }
654 kept, _, _ := r.state.keptCommit(r.ctx, "tk7", connPerson, wire.SpecialistEngineering, base)
655 row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e1", Attempt: 1, Specialist: wire.SpecialistEngineering, Round: 1, Feedback: "Fix round 1.", Priority: wire.PriorityUrgent}}
656 b, resume, hold, _, err := r.e.fixPlan(r.ctx, row, nil, kept, true)
657 if err != nil || hold != nil || !resume || b.Model != "moonshotai/kimi-k3.1-pro" || b.Family != "kimi" {
658 t.Fatalf("kept on its model: %+v resume %v hold %+v %v", b, resume, hold, err)
659 }
660 r.setModels(3, "z-ai/glm-5.3", "z-ai/glm-5.3-flash")
661 b, resume, hold, _, err = r.e.fixPlan(r.ctx, row, nil, kept, true)
662 if err != nil || hold != nil || resume || b.Model != "z-ai/glm-5.3" {
663 t.Fatalf("its model removed: %+v resume %v hold %+v %v", b, resume, hold, err)
664 }
665}
666
667// Security round #2: each execution of a probe, the same probe id
668// probing the same model again (a retry of a held attempt), is charged
669// and settled as its own: a durable sequence is its usage attempt and
670// its slot holder's, so a second spend is never dropped as a resend of
671// the first.
672func TestModelsReprobeChargedAgain(t *testing.T) {
673 r, fake := modelsRig(t, finishSet...)
674 fake.swap = map[string]string{"z-ai/glm-5.3": "z-ai/glm-5.2"}
675 conn := r.conn()
676 id := "probe:e1:1:z-ai/glm-5.3"
677 for range 2 {
678 if _, err := r.conns.Prober(r.ctx, conn, "z-ai/glm-5.3", id, nil); err == nil {
679 t.Fatal("a probe answered by another model passed")
680 }
681 }
682 var n, attempts int
683 if err := r.state.db.QueryRow("SELECT count(*), count(DISTINCT attempt) FROM budget_charge WHERE step=?", id).Scan(&n, &attempts); err != nil || n != 2 || attempts != 2 {
684 t.Fatalf("charges %d over %d attempts: %v", n, attempts, err)
685 }
686 var reported []int64
687 for _, u := range r.probeFrames() {
688 if u.ProbeID == id {
689 reported = append(reported, u.Rows[0].Attempt)
690 }
691 }
692 if len(reported) != 2 || reported[0] == reported[1] {
693 t.Fatalf("usage frames' attempts %v", reported)
694 }
695 if !r.slotFree() {
696 t.Fatal("the slot is held after the probes")
697 }
698}
699
700// Security round #8 (§16.6 (g)): the probe spends nothing before the
701// step's admission commits. When the fake provider receives the probe's
702// request, the admission row is committed with the probed model and the
703// slot is held by the probe's own holder.
704func TestModelsProbeRunsInsideTheAdmission(t *testing.T) {
705 r, fake := modelsRig(t, finishSet...)
706 hold, started := make(chan struct{}), make(chan struct{}, 4)
707 fake.mu.Lock()
708 fake.hold, fake.started = hold, started
709 fake.mu.Unlock()
710 var release sync.Once
711 t.Cleanup(func() { release.Do(func() { close(hold) }) })
712 done := make(chan wire.StepReport, 1)
713 go func() { done <- r.engineering("tk1", "e1", "edit:README.md|teh|the") }()
714 select {
715 case <-started:
716 case <-time.After(30 * time.Second):
717 t.Fatal("no probe reached the provider")
718 }
719 var model, holder string
720 if err := r.state.db.QueryRow("SELECT model FROM admissions WHERE step_id='e1' AND attempt=1").Scan(&model); err != nil || model != "z-ai/glm-5.3" {
721 t.Fatalf("admission at the probe's request: %q %v", model, err)
722 }
723 if err := r.state.db.QueryRow("SELECT holder FROM metered_slot WHERE local_id=?", piLocal).Scan(&holder); err != nil || !strings.HasPrefix(holder, metered.RoleProbe+"||probe:e1:1:z-ai/glm-5.3|") {
724 t.Fatalf("slot at the probe's request: %q %v", holder, err)
725 }
726 release.Do(func() { close(hold) })
727 if rep := <-done; !ran(rep) {
728 t.Fatalf("step %+v", rep)
729 }
730}
731
732// Security round #8: leave to spend withdrawn between the decision and
733// the admission's commit: the admission does not commit, so the probe
734// never reaches the provider and nothing is charged; the step is held.
735func TestModelsProbeNeedsTheAdmission(t *testing.T) {
736 r, fake := modelsRig(t, finishSet...)
737 real := r.conns.Prober
738 r.conns.Prober = func(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) {
739 if _, err := r.state.db.Exec("UPDATE steps SET priority='normal' WHERE step_id='e1'"); err != nil {
740 t.Fatal(err)
741 }
742 return real(ctx, conn, model, id, admit)
743 }
744 charges := r.charges()
745 rep := r.engineering("tk1", "e1", "edit:README.md|teh|the")
746 if rep.State != stepDeferred || fake.probeCount() != 0 || r.charges() != charges {
747 t.Fatalf("report %s %+v, probes %v, charges %d", rep.State, rep.Hold, fake.probes, r.charges())
748 }
749}
750
751// Security round #8: at most three first-use probes per look. Four
752// candidates the provider does not have: three are probed, then the
753// step is held briefly and looked at again.
754func TestModelsProbesBounded(t *testing.T) {
755 r, fake := modelsRig(t, "z-ai/glm-5.3", "moonshotai/kimi-k3.1-pro", "moonshotai/kimi-k3", "deepseek/deepseek-v4-pro-0813", "z-ai/glm-5.3-flash")
756 fake.gone = map[string]bool{"z-ai/glm-5.3": true, "moonshotai/kimi-k3.1-pro": true, "moonshotai/kimi-k3": true, "deepseek/deepseek-v4-pro-0813": true}
757 rep := r.engineering("tk1", "e1", "edit:README.md|teh|the")
758 if fake.probeCount() != 3 || rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldBusy {
759 t.Fatalf("probes %v, report %s %+v", fake.probes, rep.State, rep.Hold)
760 }
761}
762