package thin import ( "context" "database/sql" "encoding/json" "maps" "net/netip" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/fakepi" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/wire" ) // The S5b finish line (connectors spec rev 3.3 §16.7), with fakes: Pi is // fakepi in the real containment, TensorX a fake on 127.0.0.1 answering // the first-use probes. // The finish line's allowed set: GLM's strong and cheap models, Kimi's // strong one and DeepSeek's standard one. var finishSet = []string{"z-ai/glm-5.3", "z-ai/glm-5.3-flash", "moonshotai/kimi-k3.1-pro", "deepseek/deepseek-v4.1-flash"} // modelsRig is a Pi rig whose TensorX connection allows models (its key // proven on the cheapest at connect, the rest unprobed) and whose // first-use probes go to a fake TensorX. func modelsRig(t *testing.T, allowed ...string) (*piRig, *fakeTensorX) { t.Helper() r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() fake := newFakeTensorX(t, fakepi.TestKey) c := &Connector{State: r.state, Conns: r.conns} c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL } r.conns.Prober = c.probeModel // A fresh set, every model unprobed but the connect-time proof's: the // cheapest allowed. if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { // The key lists every TensorX model (read at connect). if err := metered.SetListed(r.ctx, tx, piLocal, slices.Sorted(maps.Keys(metered.Tables[metered.Current[wire.ProviderTensorX]].Models))); err != nil { return err } return metered.InitModels(r.ctx, tx, piLocal, allowed, 2) }); err != nil { t.Fatal(err) } cheapest := metered.Cheapest(wire.ProviderTensorX, metered.Current[wire.ProviderTensorX], allowed) if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, cheapest, wire.ModelHealthy, "", time.Now()) }); err != nil { t.Fatal(err) } return r, fake } // setModels applies the person's set at revision, as the models frame does. func (r *piRig) setModels(revision int64, allowed ...string) { r.t.Helper() if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { ok, err := metered.SetModels(r.ctx, tx, piLocal, "cn_tx", allowed, revision) if err == nil && !ok { r.t.Fatalf("set %v at %d not applied", allowed, revision) } return err }); err != nil { r.t.Fatal(err) } } func (r *piRig) modelState(model string) metered.Model { r.t.Helper() ms, err := metered.Models(r.ctx, r.state.db, piLocal) if err != nil { r.t.Fatal(err) } for _, m := range ms { if m.ID == model { return m } } return metered.Model{} } // ran reports whether an Engineering step ran its harness to the end // (the rig's forge cannot take the push, so it ends push_failed). func ran(rep wire.StepReport) bool { return rep.Termination && (rep.State == wire.StepDone || rep.Reason == "push_failed") && len(rep.Usage) == 1 && rep.Usage[0].Complete } // engineering runs one Engineering step through the whole step path. func (r *piRig) engineering(task, step, brief string) wire.StepReport { r.t.Helper() base := r.review.BaseSHA 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} if err := r.state.AcceptDispatch(r.ctx, "f-"+step, row.DispatchCommand); err != nil { r.t.Fatal(err) } return r.e.Exec(r.ctx, row, func(wire.StepReport) {}) } // admission is what an attempt's admission recorded (§16.5). func (r *piRig) admission(step string) (model, family, tier, priceVersion, tierVersion string) { r.t.Helper() 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 { r.t.Fatal(err) } return } func (r *piRig) probeFrames() []wire.UsageReport { r.t.Helper() frames, _, err := r.state.Unacked(r.ctx, 0) if err != nil { r.t.Fatal(err) } var out []wire.UsageReport for _, f := range frames { var v wire.UsageReport if f.Type == wire.FrameUsage && json.Unmarshal(f.Data, &v) == nil && v.ProbeID != "" { out = append(out, v) } } return out } // spendTo charges the connection up to day micro-units today. func (r *piRig) spendTo(day int64) { r.t.Helper() now := time.Now().UTC() 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 { r.t.Fatal(err) } } // §16.7: a first Engineering pass probes the strongest allowed model // inside its own admission, then runs it; its admission, its usage row // and its family name that model (§16.6 (f): the harness ran the chosen // model). At 0.8 fill the next pass runs a cheap model with no probe. func TestModelsEngineeringProbesThenRunsTheStrongest(t *testing.T) { r, fake := modelsRig(t, finishSet...) rep := r.engineering("tk1", "e1", "edit:README.md|teh|the") if !ran(rep) || rep.Family != "glm" { t.Fatalf("first pass: %+v", rep) } if fake.probeCount() != 1 || fake.probes[0] != "z-ai/glm-5.3" { t.Fatalf("probes %v", fake.probes) } probes := r.probeFrames() 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 { t.Fatalf("probe usage %+v", probes) } if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelHealthy { t.Fatalf("probed model %+v", m) } 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 { t.Fatalf("step usage %+v", rep.Usage) } 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 { t.Fatalf("admission %s %s %s %s %s", model, family, tier, pv, tv) } // Two charges: the probe's and the step's; the slot free. if n := r.charges(); n != 2 || !r.slotFree() { t.Fatalf("charges %d, slot free %v", n, r.slotFree()) } // At 0.8 fill: a cheap model, already proven at connect. r.spendTo(800_000) rep = r.engineering("tk2", "e2", "edit:README.md|teh|the") if !ran(rep) || rep.Usage[0].Model != "z-ai/glm-5.3-flash" || rep.Usage[0].Tier != "cheap" { t.Fatalf("at 0.8: %+v", rep) } if fake.probeCount() != 1 { t.Fatalf("a proven model probed again: %v", fake.probes) } } // §16.7: Review of a GLM step runs Kimi (another family first); with // Kimi and DeepSeek unticked it runs GLM, the same family, labelled // same_family when Engineering ran on another connection (and // same_account on its own, as built). Engineering's family is the one // its attempt recorded (the dispatch's avoid_family), never the // connection's. func TestModelsReviewAcrossFamilies(t *testing.T) { r, _ := modelsRig(t, finishSet...) r.review.AvoidAccount, r.review.AvoidFamily = piLocal, "glm" rep := r.runReview("", 1) 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" { t.Fatalf("review of glm: %+v", rep) } // Engineering's family is read from its record: a kimi Engineering // step on this same connection sends Review to GLM or DeepSeek. r.review.AvoidFamily = "kimi" if rep := r.runReview("", 2); rep.Family == "kimi" || rep.ReviewLabel != wire.ReviewOtherFamily { t.Fatalf("review of kimi: %+v", rep) } // Kimi and DeepSeek unticked: GLM, on another account than // Engineering's. r.setModels(3, "z-ai/glm-5.3", "z-ai/glm-5.3-flash") const second = "tensorx-second000000" if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { 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 { return err } if err := metered.Checked(r.ctx, tx, second, true); err != nil { return err } return provenModels(r.ctx, tx, second, "z-ai/glm-5.2") }); err != nil { t.Fatal(err) } // The second key (Engineering's) is at its budget; this one reviews // (another connection at the same rule would anyway). now := time.Now().UTC() 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 { t.Fatal(err) } r.review.AvoidAccount, r.review.AvoidFamily = second, "glm" if rep := r.runReview("", 3); rep.State != wire.StepDone || rep.Family != "glm" || rep.ReviewLabel != wire.ReviewSameFamily || rep.Account != piLocal { t.Fatalf("only glm, engineering elsewhere: %+v", rep) } // Engineering on this connection, and no other: its own, same_account. if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.Retire(r.ctx, tx, second) }); err != nil { t.Fatal(err) } r.review.AvoidAccount = piLocal if rep := r.runReview("", 4); rep.Family != "glm" || rep.ReviewLabel != wire.ReviewSameAccount { t.Fatalf("only glm, engineering here: %+v", rep) } } // §16.7, §16.6 (d): a question whose session's model was unticked fails // model_unavailable; it never runs on another model or connection, and // nothing is admitted or charged for it. func TestModelsQuestionOnAnUntickedModel(t *testing.T) { r, _ := modelsRig(t, finishSet...) r.review.AvoidAccount, r.review.AvoidFamily = piLocal, "glm" rep := r.runReview("", 1) if rep.Family != "kimi" || !rep.Askable { t.Fatalf("review %+v", rep) } kept, ok, err := r.state.keptSessionFor(r.ctx, rep.StepID) if err != nil || !ok || kept.Model != "moonshotai/kimi-k3.1-pro" || kept.Family != "kimi" { t.Fatalf("kept session %+v %v %v", kept, ok, err) } r.setModels(3, "z-ai/glm-5.3", "z-ai/glm-5.3-flash", "deepseek/deepseek-v4.1-flash") charges := r.charges() answer := r.ask(rep, "q1") if answer.State != wire.QuestionFailed || answer.Reason != wire.ReasonModelUnavailable || len(answer.Usage) != 0 { t.Fatalf("answer %+v", answer) } if r.charges() != charges || !r.slotFree() { t.Fatalf("charged %d -> %d, slot free %v", charges, r.charges(), r.slotFree()) } // Ticked again but unhealthy: the same. r.setModels(4, finishSet...) if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "moonshotai/kimi-k3.1-pro", wire.ModelUnhealthy, wire.ModelNotFound, time.Now()) }); err != nil { t.Fatal(err) } if answer := r.ask(rep, "q2"); answer.Reason != wire.ReasonModelUnavailable { t.Fatalf("unhealthy: %+v", answer) } // Healthy again: it answers, on that model. if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "moonshotai/kimi-k3.1-pro", wire.ModelHealthy, "", time.Now()) }); err != nil { t.Fatal(err) } if answer := r.ask(rep, "q3"); answer.State != wire.QuestionAnswered || len(answer.Usage) != 1 || answer.Usage[0].Model != "moonshotai/kimi-k3.1-pro" { t.Fatalf("healthy: %+v", answer) } } // ask asks a step's kept session a question and returns its final report. func (r *piRig) ask(rep wire.StepReport, id string) wire.AnswerReport { r.t.Helper() 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?"}} if err := r.state.AcceptAsk(r.ctx, "f-"+id, a.AskCommand); err != nil { r.t.Fatal(err) } se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} local, model, ok := se.meteredAsk(r.ctx, a) if !ok || local != piLocal { r.t.Fatalf("the question is not on its metered connection: %q %v", local, ok) } se.askMetered(r.ctx, r.ctx, a, local, model, func(wire.AnswerReport) {}) frames, _, err := r.state.Unacked(r.ctx, 0) if err != nil { r.t.Fatal(err) } var out wire.AnswerReport for _, f := range frames { var v wire.AnswerReport if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == id && wire.QuestionTerminal(v.State) { out = v } } return out } // §16.7, §16.4: a probe answered by another model marks that model // unhealthy (other_model, with its time) and the step runs on the next // pick; a model the provider does not have is unhealthy too (not_found) // and nothing is charged for it. func TestModelsProbeAnsweredByAnotherModel(t *testing.T) { r, fake := modelsRig(t, finishSet...) // The answering model is priced: its usage is charged as its own, so // the spend stays known. fake.swap = map[string]string{"z-ai/glm-5.3": "z-ai/glm-5.2"} rep := r.engineering("tk1", "e1", "edit:README.md|teh|the") if !ran(rep) || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" { t.Fatalf("step %+v", rep) } if strings.Join(fake.probes, ",") != "z-ai/glm-5.3,moonshotai/kimi-k3.1-pro" { t.Fatalf("probes %v", fake.probes) } if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelOtherAnswered || m.FailedAt.IsZero() { t.Fatalf("swapped model %+v", m) } if r.conn().SpendUnknown { t.Fatal("the answering model's usage was not priced as its own") } r2, fake2 := modelsRig(t, finishSet...) fake2.gone = map[string]bool{"z-ai/glm-5.3": true} before := r2.charges() rep = r2.engineering("tk1", "e1", "edit:README.md|teh|the") if !ran(rep) || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" { t.Fatalf("after not found: %+v", rep) } if m := r2.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelNotFound { t.Fatalf("missing model %+v", m) } // Charged: kimi's probe and the step; nothing for the missing model. if n := r2.charges(); n != before+2 { t.Fatalf("charges %d -> %d", before, n) } } // §16.4: a probe whose answer carries no usable usage leaves the spend // unknown: the connection pauses and nothing else is probed or run until // Resume. A refused key is connection-wide: no model is marked. func TestModelsProbeFailures(t *testing.T) { r, fake := modelsRig(t, finishSet...) fake.mu.Lock() fake.usage = `null` fake.mu.Unlock() rep := r.engineering("tk1", "e1", "edit:README.md|teh|the") if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldSpendUnknown { t.Fatalf("spend unknown: %+v hold %+v", rep.Usage, rep.Hold) } if fake.probeCount() != 1 || !r.conn().SpendUnknown { t.Fatalf("probes %v, paused %v", fake.probes, r.conn().SpendUnknown) } // Nothing else is probed, or run, until Resume. 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 { t.Fatalf("after the pause: %+v, probes %v", rep.Hold, fake.probes) } r2, fake2 := modelsRig(t, finishSet...) fake2.mu.Lock() fake2.key = "another-key" fake2.mu.Unlock() rep = r2.engineering("tk1", "e1", "edit:README.md|teh|the") if ran(rep) { t.Fatalf("ran on a refused key: %+v", rep) } if !r2.conn().Refused || r2.modelState("z-ai/glm-5.3").State != wire.ModelUnprobed { t.Fatalf("refused %v, model %+v", r2.conn().Refused, r2.modelState("z-ai/glm-5.3")) } } // §16.4: an unhealthy model is eligible again only on demand: never // before a day has passed since it failed, then probed as on first use // when a step would pick it. func TestModelsUnhealthyRetriedOnDemand(t *testing.T) { r, fake := modelsRig(t, finishSet...) failed := time.Now().Add(-23 * time.Hour) if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelUnhealthy, wire.ModelNotFound, failed) }); err != nil { t.Fatal(err) } fake.swap = map[string]string{} if rep := r.engineering("tk1", "e1", "edit:README.md|teh|the"); !ran(rep) || rep.Usage[0].Model != "moonshotai/kimi-k3.1-pro" { t.Fatalf("within a day: %+v", rep) } if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelUnhealthy, wire.ModelNotFound, time.Now().Add(-25*time.Hour)) }); err != nil { t.Fatal(err) } if rep := r.engineering("tk2", "e2", "edit:README.md|teh|the"); !ran(rep) || rep.Usage[0].Model != "z-ai/glm-5.3" { t.Fatalf("after a day: %+v", rep) } if !slices.Contains(fake.probes, "z-ai/glm-5.3") || r.modelState("z-ai/glm-5.3").State != wire.ModelHealthy { t.Fatalf("probes %v, model %+v", fake.probes, r.modelState("z-ai/glm-5.3")) } } // §16.5: a step whose usage names another model than the one chosen is // charged at that model's price, marked model_mismatch, and the chosen // model is unhealthy until Check again. func TestModelsStepMismatch(t *testing.T) { r, _ := modelsRig(t, "z-ai/glm-5.3", "z-ai/glm-5.3-flash") if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelHealthy, "", time.Now()) }); err != nil { t.Fatal(err) } rep := r.runReview("answeredby:z-ai/glm-5.3-flash", 1) if len(rep.Usage) != 1 || rep.Usage[0].Model != "z-ai/glm-5.3-flash" || !rep.Usage[0].ModelMismatch || rep.Usage[0].CostMicros == nil { t.Fatalf("usage %+v", rep.Usage) } if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelMismatch { t.Fatalf("chosen model %+v", m) } } // §16.7: a connection S1 made (one model, no allowed set, an admission // and a kept session with no model) behaves exactly as before once the // runner migrates its thin.db: the set is its one model, healthy; its // steps and questions run on it; hello names it as before. func TestModelsMigratedConnectionAsBefore(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() // Back to S1's shape: no set, no models revision, and an admission and // a kept session with no model. if _, err := r.state.db.Exec("DELETE FROM metered_models"); err != nil { t.Fatal(err) } if _, err := r.state.db.Exec("UPDATE metered_connections SET models_revision=0"); err != nil { t.Fatal(err) } 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 { t.Fatal(err) } 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 { t.Fatal(err) } if err := migrateModels(r.ctx, r.state.db); err != nil { t.Fatal(err) } 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 { t.Fatalf("set %+v", ms) } var model, family string r.state.db.QueryRow("SELECT model, family FROM admissions WHERE step_id='old'").Scan(&model, &family) if model != "z-ai/glm-5.3" || family != "glm" { t.Fatalf("admission backfilled %q %q", model, family) } if k, _, _ := r.state.keptSessionFor(r.ctx, "old"); k.Model != "z-ai/glm-5.3" || k.Family != "glm" { t.Fatalf("kept session backfilled %+v", k) } rep := r.runReview("", 1) if rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || rep.Usage[0].Model != "z-ai/glm-5.3" { t.Fatalf("review %+v", rep) } if a := r.ask(rep, "q1"); a.State != wire.QuestionAnswered { t.Fatalf("question %+v", a) } held, ok := heldOf(r.conns, piLocal) if !ok || held.Model != "z-ai/glm-5.3" || held.ModelsRevision != 1 || len(held.Models) != 1 { t.Fatalf("hello %+v", held) } } func heldOf(c *Conns, local string) (wire.HeldConnection, bool) { for _, h := range c.Held() { if h.LocalID == local { return h, true } } return wire.HeldConnection{}, false } // §16.1: the models frame applies a set once, only above the revision // held and only for the connection, person and runner name it names; // hello then carries the applied revision and states. A connecting // attempt takes the frame as its card's answer and proves the key on the // cheapest allowed model only. func TestModelsFrame(t *testing.T) { const key = "tx-fake-key-fake-key" r := newTokenRig(t) fake := newFakeTensorX(t, key) fake.list = `{"data":[{"id":"z-ai/glm-5.3"},{"id":"z-ai/glm-5.3-flash"},{"id":"moonshotai/kimi-k3"},{"id":"vendor/unpriced"}]}` c := r.meteredConnector(fake) home := r.startAPIKey(c, "cn_tx") local := filepath.Base(home) if !r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) { t.Fatalf("secret refused: %v", r.errs) } p := r.card("cn_tx", wire.PromptModels) if strings.Join(eligibleChoices(p), ",") != "moonshotai/kimi-k3,z-ai/glm-5.3,z-ai/glm-5.3-flash" || len(p.Choices) != 4 { t.Fatalf("card %+v", p.Choices) } // A set with a model that cannot be allowed is not taken. if err := c.Models(r.ctx, "f-models-0", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, Allowed: []string{"vendor/unpriced"}, Revision: 1}); err != nil { t.Fatal(err) } 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 { t.Fatal(err) } if end := r.ended("cn_tx"); end.State != wire.ConnHealthy { t.Fatalf("end %+v", end) } if strings.Join(fake.probes, ",") != "z-ai/glm-5.3-flash" { t.Fatalf("connect probes %v", fake.probes) } held, ok := r.held(local) if !ok || held.ModelsRevision != 1 || held.Model != "z-ai/glm-5.3-flash" || len(held.Models) != 3 { t.Fatalf("hello %+v", held) } // The key's list, for the page: every listed model, the unpriced one // not eligible. 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 { t.Fatalf("choices %+v", held.Choices) } states := map[string]string{} for _, m := range held.Models { states[m.ID] = m.State } if states["z-ai/glm-5.3-flash"] != wire.ModelHealthy || states["z-ai/glm-5.3"] != wire.ModelUnprobed || states["moonshotai/kimi-k3"] != wire.ModelUnprobed { t.Fatalf("states %v", states) } apply := func(id string, cmd wire.ModelsCommand) { t.Helper() if err := c.Models(r.ctx, id, cmd); err != nil { t.Fatal(err) } } revision := func() int64 { h, _ := r.held(local) return h.ModelsRevision } // Not above the revision held; another connection id; another person; // another runner name: nothing applied. apply("f-m-a", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 1}) apply("f-m-b", wire.ModelsCommand{Connection: "cn_other", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 2}) apply("f-m-c", wire.ModelsCommand{Connection: "cn_tx", Person: "someone@example.com", LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 2}) apply("f-m-d", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: "tensorx-other", Allowed: []string{"z-ai/glm-5.3"}, Revision: 2}) if revision() != 1 { t.Fatalf("a set that does not bind was applied: revision %d", revision()) } // A set it refuses (a model the key does not list) is acked, not // applied: hello stays at the revision held (security round #4). 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}) if revision() != 1 { t.Fatalf("a refused set shows applied: revision %d", revision()) } apply("f-m-e", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3"}, Revision: 2}) if h, _ := r.held(local); h.ModelsRevision != 2 || len(h.Models) != 1 || h.Models[0].ID != "z-ai/glm-5.3" { t.Fatalf("applied %+v", h) } // The same frame again changes nothing (consumed once). apply("f-m-e", wire.ModelsCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Allowed: []string{"z-ai/glm-5.3-flash"}, Revision: 3}) if revision() != 2 { t.Fatal("a consumed frame applied again") } // Check again: the key on the cheapest allowed, then every unhealthy // allowed model. 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}) if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, local, "moonshotai/kimi-k3", wire.ModelUnhealthy, wire.ModelMismatch, time.Now()) }); err != nil { t.Fatal(err) } fake.mu.Lock() fake.probes = nil fake.mu.Unlock() conn, _, _ := metered.Get(r.ctx, r.state.db, local) c.checkMetered(conn) r.waitFor(func() bool { return fake.probeCount() == 2 && r.slotOf(local) }, "Check again's probes") if strings.Join(fake.probes, ",") != "z-ai/glm-5.3-flash,moonshotai/kimi-k3" { t.Fatalf("Check again probed %v", fake.probes) } if ms, _ := metered.Models(r.ctx, r.state.db, local); ms[0].ID != "moonshotai/kimi-k3" || ms[0].State != wire.ModelHealthy { t.Fatalf("after Check again %+v", ms) } } // slotOf reports whether a metered connection's slot is free. func (r *tokenRig) slotOf(local string) bool { var holder string r.state.db.QueryRow("SELECT holder FROM metered_slot WHERE local_id=?", local).Scan(&holder) return holder == "" } // Security round #1: a request later in a step answered by another, // unpriced model is its own usage row: the mismatch is seen (the chosen // model unhealthy) and its spend is unknown (the connection paused), // never folded into the first model's row. func TestModelsLaterRequestOnAnotherModel(t *testing.T) { r, _ := modelsRig(t, "z-ai/glm-5.3", "z-ai/glm-5.3-flash") if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelHealthy, "", time.Now()) }); err != nil { t.Fatal(err) } rep := r.runReview("thenby:vendor/other", 1) 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 { t.Fatalf("usage %+v", rep.Usage) } if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelMismatch { t.Fatalf("chosen model %+v", m) } if !r.conn().SpendUnknown { t.Fatal("an unpriced model's request left the spend known") } } // §16.4, "After a step fails": a healthy model whose step fails with // model-not-found becomes unhealthy, and the next choice runs without it. func TestModelsStepModelGone(t *testing.T) { r, _ := modelsRig(t, "z-ai/glm-5.3", "z-ai/glm-5.3-flash") if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, "z-ai/glm-5.3", wire.ModelHealthy, "", time.Now()) }); err != nil { t.Fatal(err) } rep := r.runReview("modelgone", 1) if rep.State != wire.StepFailed || len(rep.Usage) != 1 || rep.Usage[0].Model != "z-ai/glm-5.3" { t.Fatalf("report %+v", rep) } if m := r.modelState("z-ai/glm-5.3"); m.State != wire.ModelUnhealthy || m.Reason != wire.ModelNotFound || m.FailedAt.IsZero() { t.Fatalf("model %+v", m) } if rep := r.runReview("", 2); rep.State != wire.StepDone || rep.Usage[0].Model != "z-ai/glm-5.3-flash" { t.Fatalf("next: %+v", rep) } } // §16.3 rule 1: a fix round resumes its kept metered session only on the // model the session was created on; once that model leaves the set the // round starts afresh on the choice's model. func TestModelsFixRoundOnlyOnItsModel(t *testing.T) { r, _ := modelsRig(t, finishSet...) for _, m := range finishSet { if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return metered.MarkModel(r.ctx, tx, piLocal, m, wire.ModelHealthy, "", time.Now()) }); err != nil { t.Fatal(err) } } base := r.review.CandidateSHA round0 := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e0", Attempt: 1, Specialist: wire.SpecialistEngineering}} dir := filepath.Join(t.TempDir(), "kept") if err := r.state.keepSession(r.ctx, round0, wire.SpecialistEngineering, piLocal, "moonshotai/kimi-k3.1-pro", "kimi", "sess", dir, base, 10); err != nil { t.Fatal(err) } kept, _, _ := r.state.keptCommit(r.ctx, "tk7", connPerson, wire.SpecialistEngineering, base) 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}} b, resume, hold, _, err := r.e.fixPlan(r.ctx, row, nil, kept, true) if err != nil || hold != nil || !resume || b.Model != "moonshotai/kimi-k3.1-pro" || b.Family != "kimi" { t.Fatalf("kept on its model: %+v resume %v hold %+v %v", b, resume, hold, err) } r.setModels(3, "z-ai/glm-5.3", "z-ai/glm-5.3-flash") b, resume, hold, _, err = r.e.fixPlan(r.ctx, row, nil, kept, true) if err != nil || hold != nil || resume || b.Model != "z-ai/glm-5.3" { t.Fatalf("its model removed: %+v resume %v hold %+v %v", b, resume, hold, err) } } // Security round #2: each execution of a probe, the same probe id // probing the same model again (a retry of a held attempt), is charged // and settled as its own: a durable sequence is its usage attempt and // its slot holder's, so a second spend is never dropped as a resend of // the first. func TestModelsReprobeChargedAgain(t *testing.T) { r, fake := modelsRig(t, finishSet...) fake.swap = map[string]string{"z-ai/glm-5.3": "z-ai/glm-5.2"} conn := r.conn() id := "probe:e1:1:z-ai/glm-5.3" for range 2 { if _, err := r.conns.Prober(r.ctx, conn, "z-ai/glm-5.3", id, nil); err == nil { t.Fatal("a probe answered by another model passed") } } var n, attempts int 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 { t.Fatalf("charges %d over %d attempts: %v", n, attempts, err) } var reported []int64 for _, u := range r.probeFrames() { if u.ProbeID == id { reported = append(reported, u.Rows[0].Attempt) } } if len(reported) != 2 || reported[0] == reported[1] { t.Fatalf("usage frames' attempts %v", reported) } if !r.slotFree() { t.Fatal("the slot is held after the probes") } } // Security round #8 (§16.6 (g)): the probe spends nothing before the // step's admission commits. When the fake provider receives the probe's // request, the admission row is committed with the probed model and the // slot is held by the probe's own holder. func TestModelsProbeRunsInsideTheAdmission(t *testing.T) { r, fake := modelsRig(t, finishSet...) hold, started := make(chan struct{}), make(chan struct{}, 4) fake.mu.Lock() fake.hold, fake.started = hold, started fake.mu.Unlock() var release sync.Once t.Cleanup(func() { release.Do(func() { close(hold) }) }) done := make(chan wire.StepReport, 1) go func() { done <- r.engineering("tk1", "e1", "edit:README.md|teh|the") }() select { case <-started: case <-time.After(30 * time.Second): t.Fatal("no probe reached the provider") } var model, holder string 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" { t.Fatalf("admission at the probe's request: %q %v", model, err) } 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|") { t.Fatalf("slot at the probe's request: %q %v", holder, err) } release.Do(func() { close(hold) }) if rep := <-done; !ran(rep) { t.Fatalf("step %+v", rep) } } // Security round #8: leave to spend withdrawn between the decision and // the admission's commit: the admission does not commit, so the probe // never reaches the provider and nothing is charged; the step is held. func TestModelsProbeNeedsTheAdmission(t *testing.T) { r, fake := modelsRig(t, finishSet...) real := r.conns.Prober r.conns.Prober = func(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) { if _, err := r.state.db.Exec("UPDATE steps SET priority='normal' WHERE step_id='e1'"); err != nil { t.Fatal(err) } return real(ctx, conn, model, id, admit) } charges := r.charges() rep := r.engineering("tk1", "e1", "edit:README.md|teh|the") if rep.State != stepDeferred || fake.probeCount() != 0 || r.charges() != charges { t.Fatalf("report %s %+v, probes %v, charges %d", rep.State, rep.Hold, fake.probes, r.charges()) } } // Security round #8: at most three first-use probes per look. Four // candidates the provider does not have: three are probed, then the // step is held briefly and looked at again. func TestModelsProbesBounded(t *testing.T) { 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") 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} rep := r.engineering("tk1", "e1", "edit:README.md|teh|the") if fake.probeCount() != 3 || rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldBusy { t.Fatalf("probes %v, report %s %+v", fake.probes, rep.State, rep.Hold) } }