oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "errors"
6 "strconv"
7 "strings"
8 "testing"
9
10 "amadan.net/oficina/equipo/internal/wire"
11 "gorm.io/gorm"
12)
13
14// modelsRig is the metered rig with its made connection allowing a set,
15// the key's list known, its runner at protocol.
16func modelsRig(t *testing.T, protocol int) *meteredRig {
17 r := newMeteredRig(t)
18 for _, q := range []string{
19 "UPDATE chat_connections SET models = '[\"z-ai/glm-5.3\"]', models_revision = 1, models_applied = 1, models_listed = '[{\"id\":\"z-ai/glm-5.3\",\"eligible\":true},{\"id\":\"moonshotai/kimi-k3\",\"eligible\":true},{\"id\":\"vendor/unpriced\",\"eligible\":false}]', models_state = '[{\"id\":\"z-ai/glm-5.3\",\"state\":\"healthy\"}]' WHERE id = 'cn_made'",
20 "UPDATE chat_connections SET prompt = '{\"kind\":\"models\",\"url\":\"\",\"code\":\"\",\"choices\":[{\"id\":\"z-ai/glm-5.3\",\"eligible\":true},{\"id\":\"vendor/unpriced\",\"eligible\":false}]}' WHERE id = 'cn_new'",
21 // The chat store's template has no runners table; the app's is this.
22 "CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, machine_key_hash text, label text, revision integer, revoked_at datetime, instance_id text, role text, removing_at datetime, tainted_at datetime)",
23 "INSERT INTO runners(id, person, revision) VALUES('RUNNER1', 'owner@example.com', 1)",
24 } {
25 if err := r.s.db.G.Exec(q).Error; err != nil {
26 t.Fatal(err)
27 }
28 }
29 if err := r.s.db.G.Exec("INSERT INTO runner_sessions(runner_id, generation, connected, revision, seen_at, protocol) VALUES('RUNNER1', 1, 1, 1, ?, ?)", r.s.now(), protocol).Error; err != nil {
30 t.Fatal(err)
31 }
32 return r
33}
34
35// §16.1 (finding 8): a set change is the connection owner's alone, the
36// actor the session's, the roster checked in the write's transaction,
37// and audited; revision-checked; at least one model, each one the key
38// listed that can be allowed; a runner below ProtocolModels is refused
39// any change; the card's answer while connecting is revision 0 and
40// sends the set as revision 1.
41func TestModelsWritesCheckOwnerRosterAndRevision(t *testing.T) {
42 ctx := context.Background()
43 r := modelsRig(t, wire.ProtocolModels)
44 set := func(person, id string, allowed []string, rev int64) error {
45 _, err := r.s.SetModels(ctx, person, id, wire.SetModels{Allowed: allowed, Revision: rev})
46 return err
47 }
48 if err := set("member@example.com", "cn_made", []string{"z-ai/glm-5.3"}, 1); !errors.Is(err, ErrNotFound) {
49 t.Fatalf("another person's set: %v", err)
50 }
51 r.unchanged("another person's set")
52 r.removed = true
53 if err := set("owner@example.com", "cn_made", []string{"z-ai/glm-5.3"}, 1); !errors.Is(err, ErrForbidden) {
54 t.Fatalf("a removed person's set: %v", err)
55 }
56 r.unchanged("a removed person's set")
57 r.removed = false
58 for name, c := range map[string]struct {
59 allowed []string
60 rev int64
61 want error
62 }{
63 "a stale revision": {[]string{"z-ai/glm-5.3"}, 0, ErrConflict},
64 "none": {[]string{}, 1, ErrModelsNotAllowed},
65 "an unpriced model": {[]string{"z-ai/glm-5.3", "vendor/unpriced"}, 1, ErrModelsNotAllowed},
66 "a model the key does not list": {[]string{"z-ai/glm-5.2"}, 1, ErrModelsNotAllowed},
67 } {
68 if err := set("owner@example.com", "cn_made", c.allowed, c.rev); !errors.Is(err, c.want) {
69 t.Fatalf("%s: %v", name, err)
70 }
71 r.unchanged(name)
72 }
73 out, err := r.s.SetModels(ctx, "owner@example.com", "cn_made", wire.SetModels{Allowed: []string{"z-ai/glm-5.3", "moonshotai/kimi-k3"}, Revision: 1})
74 if err != nil || out.ModelsRevision != 2 || !out.ModelsPending {
75 t.Fatalf("set %+v %v", out, err)
76 }
77 var c commandRecord
78 if err := r.s.db.G.Where("kind = ?", wire.FrameModels).First(&c).Error; err != nil || !strings.Contains(c.Body, `"local_id":"tensorx-abc"`) || !strings.Contains(c.Body, `"revision":2`) {
79 t.Fatalf("frame %+v %v", c, err)
80 }
81 // Security round #4: the frame's ack is receipt, not application (a
82 // runner acks a set it refuses too): still pending. Only the set the
83 // runner reports applied (hello) shows as applied, and a hello behind
84 // the one before is believed, never maxed away.
85 ackLease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: "owner@example.com"}, Protocol: wire.ProtocolModels}
86 if err := r.s.tx(ctx, func(t *txn) error { return t.ack(ackLease, "c"+strconv.FormatInt(c.Seq, 10)) }); err != nil {
87 t.Fatal(err)
88 }
89 if got, _ := r.s.Connection(ctx, "owner@example.com", "cn_made"); !got.ModelsPending {
90 t.Fatalf("an ack showed the set applied %+v", got)
91 }
92 hello := func(rev int64) wire.Connection {
93 t.Helper()
94 h := wire.HeldConnection{LocalID: "tensorx-abc", Person: "owner@example.com", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1000000, Month: 10000000, Currency: "USD", Revision: 1}, Spend: &wire.Spend{Currency: "USD"}, Models: []wire.ModelState{{ID: "z-ai/glm-5.3", State: wire.ModelHealthy}}, ModelsRevision: rev}
95 l := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: "owner@example.com"}, Protocol: wire.ProtocolModels}
96 if err := r.s.tx(ctx, func(t *txn) error { return t.helloConnections(l, []wire.HeldConnection{h}, true) }); err != nil {
97 t.Fatal(err)
98 }
99 got, _ := r.s.Connection(ctx, "owner@example.com", "cn_made")
100 return got
101 }
102 if got := hello(1); !got.ModelsPending {
103 t.Fatalf("a hello still at revision 1 showed the set applied %+v", got)
104 }
105 if got := hello(2); got.ModelsPending || got.ModelsRevision != 2 {
106 t.Fatalf("applied at 2: %+v", got)
107 }
108 if got := hello(1); !got.ModelsPending {
109 t.Fatalf("a hello behind was maxed away %+v", got)
110 }
111 // The card's answer while connecting.
112 if err := set("owner@example.com", "cn_new", []string{"z-ai/glm-5.3"}, 1); !errors.Is(err, ErrConflict) {
113 t.Fatalf("a connecting set at revision 1: %v", err)
114 }
115 if err := set("owner@example.com", "cn_new", []string{"vendor/unpriced"}, 0); !errors.Is(err, ErrModelsNotAllowed) {
116 t.Fatalf("an unpriced connecting set: %v", err)
117 }
118 if err := set("owner@example.com", "cn_new", []string{"z-ai/glm-5.3"}, 0); err != nil {
119 t.Fatal(err)
120 }
121 want := []string{"owner@example.com connection.models cn_made@2", "owner@example.com connection.models cn_new@1"}
122 if strings.Join(r.audits, "|") != strings.Join(want, "|") {
123 t.Fatalf("audits %v", r.audits)
124 }
125 // An older runner: refused any change, nothing sent.
126 old := modelsRig(t, wire.ProtocolOpenCode)
127 if _, err := old.s.SetModels(ctx, "owner@example.com", "cn_made", wire.SetModels{Allowed: []string{"z-ai/glm-5.3", "moonshotai/kimi-k3"}, Revision: 1}); !errors.Is(err, ErrRunnerTooOld) {
128 t.Fatalf("a protocol 17 runner: %v", err)
129 }
130 old.unchanged("a protocol 17 runner's set")
131 if list, _ := old.s.Connections(ctx, "owner@example.com"); !list[0].ModelsTooOld {
132 t.Fatalf("too old not said: %+v", list[0])
133 }
134}
135
136// §16.7: a metered step's report records the model its newest attempt
137// ran on (its usage row's, priced), shown on the step; a subscription's
138// row changes nothing there.
139func TestStepRecordsItsModel(t *testing.T) {
140 r := newHKRig(t)
141 r.s.authority.RunnerRole = func(*gorm.DB, string) (string, error) { return wire.RolePrimary, nil }
142 k := r.task("tkm1", "Fix the typo", "owner@example.com")
143 start := r.now
144 s := stepRecord{ID: "s_rv", TaskID: k.ID, Idx: 2, Specialist: wire.SpecialistReview, Person: "owner@example.com", State: wire.StepRunning, Attempt: 1, CandidateSHA: strings.Repeat("2", 40), RunnerID: "RUNNER1", StartedAt: &start, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
145 r.must(r.tx(func(t *txn) error { return t.db.Create(&s).Error }))
146 l := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: "owner@example.com"}, Protocol: wire.ProtocolModels}
147 n := int64(10)
148 report := func(u wire.Usage) string {
149 rep := &wire.StepReport{TaskID: k.ID, StepID: s.ID, Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}, Usage: []wire.Usage{u}}
150 r.must(r.tx(func(t *txn) error { return t.stepReport(l, rep) }))
151 var got stepRecord
152 r.must(r.tx(func(t *txn) error { return t.db.Where("id = ?", s.ID).First(&got).Error }))
153 return got.Model
154 }
155 if got := report(wire.Usage{Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, InputTokens: &n, OutputTokens: &n}); got != "" {
156 t.Fatalf("a subscription's model recorded: %q", got)
157 }
158 if got := report(wire.Usage{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "moonshotai/kimi-k3", Attempt: 1, Outcome: wire.OutcomeReplied, InputTokens: &n, OutputTokens: &n, PriceVersion: "tensorx-2026-11-12", Currency: "USD"}); got != "moonshotai/kimi-k3" {
159 t.Fatalf("the metered model: %q", got)
160 }
161}
162
163// The key's list the runner reports is bounded before it is kept.
164func TestValidChoices(t *testing.T) {
165 ok := []wire.ModelChoice{{ID: "z-ai/glm-5.3", Eligible: true, Family: "glm", Tier: "strong"}, {ID: "vendor/unpriced"}}
166 if !validChoices(ok) {
167 t.Fatal("a good list refused")
168 }
169 many := make([]wire.ModelChoice, wire.MaxModels+1)
170 for i := range many {
171 many[i] = wire.ModelChoice{ID: "m"}
172 }
173 for name, bad := range map[string][]wire.ModelChoice{"too many": many, "an empty id": {{ID: ""}}, "a long id": {{ID: strings.Repeat("m", wire.MaxModelName+1)}}, "an unknown tier": {{ID: "m", Tier: "huge"}}, "a long family": {{ID: "m", Family: strings.Repeat("f", 65)}}} {
174 if validChoices(bad) {
175 t.Fatalf("%s accepted", name)
176 }
177 }
178}
179