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 "sync/atomic"
8 "testing"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/runner/metered"
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15// askRig is a step engine whose questions' kept session is on a metered
16// connection, and a fake harness answering them (S2's Pi stands here).
17type askRig struct {
18 t *testing.T
19 ctx context.Context
20 s *State
21 m *metered.Meter
22 e *StepEngine
23 calls atomic.Int64
24}
25
26const meteredLocal = "tensorx-1"
27
28func newAskRig(t *testing.T, harness bool) *askRig {
29 ctx, cancel := context.WithCancel(context.Background())
30 t.Cleanup(cancel)
31 s, err := OpenState(ctx, t.TempDir())
32 if err != nil {
33 t.Fatal(err)
34 }
35 t.Cleanup(func() { s.Close() })
36 r := &askRig{t: t, ctx: ctx, s: s, m: &metered.Meter{DB: s.db}}
37 err = s.tx(ctx, func(tx *sql.Tx) error {
38 if err := metered.Add(ctx, tx, metered.Conn{Connection: "cn_q", LocalID: meteredLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/nowhere", Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1}}, time.Now()); err != nil {
39 return err
40 }
41 if err := metered.Checked(ctx, tx, meteredLocal, true); err != nil {
42 return err
43 }
44 return provenModels(ctx, tx, meteredLocal, "z-ai/glm-5.3")
45 })
46 if err != nil {
47 t.Fatal(err)
48 }
49 r.e = &StepEngine{State: s, Meter: r.m, Notify: func() {}, Exec: func(context.Context, stepRow, func(wire.StepReport)) wire.StepReport {
50 t.Error("a step ran")
51 return wire.StepReport{}
52 }, Ask: func(context.Context, askRow, func(wire.AnswerReport)) askResult {
53 t.Error("a metered question went to the Claude path")
54 return askResult{}
55 }}
56 if harness {
57 r.e.MeteredAsk = func(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) {
58 r.calls.Add(1)
59 if err := l.Namespace("ns-" + a.QuestionID); err != nil {
60 t.Error(err)
61 }
62 if l.Conn.LocalID != meteredLocal || l.Holder.Role != metered.RoleAsk {
63 t.Errorf("launch %+v", l)
64 }
65 in, out := int64(1000), int64(100)
66 return wire.AnswerReport{State: wire.QuestionAnswered, Text: "It reads the config.", Usage: []wire.Usage{{Provider: wire.ProviderTensorX, Connection: meteredLocal, Model: "z-ai/glm-5.3", Attempt: a.Attempt, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, OutputTokens: &out}}}, metered.Ending{Proven: true}
67 }
68 }
69 // The step the question asks about kept its session on the metered
70 // connection.
71 if err := s.keepSession(ctx, stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)}, wire.SpecialistEngineering, meteredLocal, "z-ai/glm-5.3", "glm", "00000000-0000-4000-8000-000000000001", "/nowhere", "", 1); err != nil {
72 t.Fatal(err)
73 }
74 return r
75}
76
77func (r *askRig) ask(q string) {
78 r.t.Helper()
79 if err := r.s.AcceptAsk(r.ctx, "f-"+q, wire.AskCommand{Person: connPerson, TaskID: "tk1", StepID: "s1", QuestionID: q, Attempt: 1, Specialist: wire.SpecialistEngineering, Text: "What does it read?"}); err != nil {
80 r.t.Fatal(err)
81 }
82}
83
84func (r *askRig) answers(q string) []wire.AnswerReport {
85 frames, _, err := r.s.Unacked(context.Background(), 0)
86 if err != nil {
87 r.t.Fatal(err)
88 }
89 var out []wire.AnswerReport
90 for _, f := range frames {
91 var v wire.AnswerReport
92 if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == q {
93 out = append(out, v)
94 }
95 }
96 return out
97}
98
99func (r *askRig) waitAnswer(q, state string) wire.AnswerReport {
100 r.t.Helper()
101 deadline := time.Now().Add(10 * time.Second)
102 for time.Now().Before(deadline) {
103 for _, a := range r.answers(q) {
104 if a.State == state {
105 return a
106 }
107 }
108 time.Sleep(10 * time.Millisecond)
109 }
110 r.t.Fatalf("%s: no %s report: %+v", q, state, r.answers(q))
111 return wire.AnswerReport{}
112}
113
114func (r *askRig) spend() wire.Spend {
115 c, _, _ := metered.Get(r.ctx, r.s.db, meteredLocal)
116 s, err := metered.SpendOf(r.ctx, r.s.db, c, time.Now())
117 if err != nil {
118 r.t.Fatal(err)
119 }
120 return s
121}
122
123// TestMeteredGuardHoldsQuestions is §7's metered guard for questions:
124// a question on a metered connection is admitted through the same guard
125// as a step, with its start; held, it reports queued with the hold and
126// is never run or moved; it goes on its own once the facts change (the
127// slot released, the budget raised, the pause resumed), and its answer
128// is charged.
129func TestMeteredGuardHoldsQuestions(t *testing.T) {
130 r := newAskRig(t, true)
131 // A probe holds the slot: the question waits busy.
132 probe := metered.Holder{Step: "pr_1", Attempt: 1, Role: metered.RoleProbe}
133 if a, err := r.m.Admit(r.ctx, meteredLocal, probe, nil); err != nil || !a.Admitted {
134 t.Fatal(a, err)
135 }
136 if err := r.e.Start(r.ctx); err != nil {
137 t.Fatal(err)
138 }
139 r.ask("q1")
140 r.e.Wake()
141 if a := r.waitAnswer("q1", wire.QuestionQueued); a.Reason != wire.HoldBusy {
142 t.Fatalf("held %+v", a)
143 }
144 time.Sleep(50 * time.Millisecond)
145 if r.calls.Load() != 0 {
146 t.Fatal("a held question ran")
147 }
148 // The probe ends: the slot is released and the question runs.
149 if err := r.m.Finish(r.ctx, meteredLocal, probe, metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}}, nil); err != nil {
150 t.Fatal(err)
151 }
152 r.e.MeteredChanged()
153 got := r.waitAnswer("q1", wire.QuestionAnswered)
154 if r.calls.Load() != 1 || len(got.Usage) != 1 || got.Usage[0].CostMicros == nil || *got.Usage[0].CostMicros != 1750+450 {
155 t.Fatalf("answered %+v calls %d", got, r.calls.Load())
156 }
157 if s := r.spend(); s.Day != 2200 || s.Running || s.Unknown {
158 t.Fatalf("spend %+v", s)
159 }
160 // The budget is spent: the next question waits for the next day.
161 if err := r.s.tx(r.ctx, func(tx *sql.Tx) error {
162 _, err := metered.ApplyBudget(r.ctx, tx, meteredLocal, "cn_q", wire.Budget{Day: 2200, Month: 10_000_000, Revision: 2})
163 return err
164 }); err != nil {
165 t.Fatal(err)
166 }
167 r.ask("q2")
168 r.e.Wake()
169 if a := r.waitAnswer("q2", wire.QuestionQueued); a.Reason != wire.HoldBudget {
170 t.Fatalf("held %+v", a)
171 }
172 var notBefore string
173 _ = r.s.db.QueryRow("SELECT not_before FROM asks WHERE question_id='q2'").Scan(&notBefore)
174 if notBefore == heldUntilChange || notBefore == "" {
175 t.Fatalf("a budget hold waits for %q, not the next day", notBefore)
176 }
177 // Looked at again with nothing changed: still held, said once.
178 r.e.MeteredChanged()
179 time.Sleep(100 * time.Millisecond)
180 if n := len(r.answers("q2")); n != 1 || r.calls.Load() != 1 {
181 t.Fatalf("reports %d calls %d", n, r.calls.Load())
182 }
183 // Raised and applied: it runs.
184 if _, err := r.m.ApplyBudget(r.ctx, meteredLocal, "cn_q", wire.Budget{Day: 5_000_000, Month: 10_000_000, Revision: 3}, nil); err != nil {
185 t.Fatal(err)
186 }
187 r.e.MeteredChanged()
188 r.waitAnswer("q2", wire.QuestionAnswered)
189 // Spend unknown: the next question waits for Resume.
190 if err := r.s.tx(r.ctx, func(tx *sql.Tx) error {
191 _, err := tx.Exec("UPDATE metered_connections SET spend_unknown=1, pause_revision=7")
192 return err
193 }); err != nil {
194 t.Fatal(err)
195 }
196 r.ask("q3")
197 r.e.Wake()
198 if a := r.waitAnswer("q3", wire.QuestionQueued); a.Reason != wire.HoldSpendUnknown {
199 t.Fatalf("held %+v", a)
200 }
201 if ok, err := r.m.Resume(r.ctx, meteredLocal, "cn_q", 7, nil); err != nil || !ok {
202 t.Fatal(ok, err)
203 }
204 r.e.MeteredChanged()
205 r.waitAnswer("q3", wire.QuestionAnswered)
206 if r.calls.Load() != 3 {
207 t.Fatalf("calls %d", r.calls.Load())
208 }
209}
210
211// With no harness for its connection here, a question on a metered
212// connection fails without claiming the slot or charging anything.
213func TestMeteredQuestionWithNoHarness(t *testing.T) {
214 r := newAskRig(t, false)
215 if err := r.e.Start(r.ctx); err != nil {
216 t.Fatal(err)
217 }
218 r.ask("q1")
219 r.e.Wake()
220 if a := r.waitAnswer("q1", wire.QuestionFailed); a.Reason != "account_unavailable" {
221 t.Fatalf("%+v", a)
222 }
223 if s := r.spend(); s.Running || s.Unknown || s.Day != 0 {
224 t.Fatalf("spend %+v", s)
225 }
226}
227