oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "testing"
5 "time"
6
7 "amadan.net/oficina/equipo/internal/wire"
8)
9
10// Task 11, fix round 1 (Astra round 1): a worker's reconnect never lets
11// the credential hold lapse (#1), a sync that reports a connection holds
12// in its own transaction (#2), nothing of a worker's connections moves
13// below 37 in either direction (#3), and usage keeps its legacy form
14// below 37 (#4).
15
16// heldNow is the instance's hold on runner, read from the store as it
17// is now.
18func (r *runnersRig) heldNow(runner string) bool {
19 r.t.Helper()
20 held, err := r.inst.Store.Chat().MacCredentialHeld(r.ctx, runner)
21 if err != nil {
22 r.t.Fatal(err)
23 }
24 return held
25}
26
27// inventoryHello is a worker's hello after the welcome, which says its
28// connections and hold in full: change sets the hold's fields.
29func inventoryHello(key string, change func(*wire.Capabilities), conns ...wire.HeldConnection) wire.Hello {
30 h := workerConnHello(key, conns...)
31 h.Inventory = true
32 if change != nil {
33 caps := *h.Capabilities
34 change(&caps)
35 h.Capabilities = &caps
36 }
37 return h
38}
39
40// handshakeHello is what a real worker says before the welcome: no
41// connections, no seal key, no hold and none of the protocol 37
42// capability fields (WithoutMacEngineering), though it offers 37.
43func handshakeHello() wire.Hello {
44 h := workerConnHello("")
45 wire.WithoutMacEngineering(&h)
46 return h
47}
48
49// syncNow sends a sync and waits until the instance has applied it. A
50// sync is not durable, so nothing acks it; the instance applies one
51// connection's frames in order, so the answer to a lease sent after it
52// means the sync is in the store.
53func (p *peer) syncNow(s wire.Sync) {
54 p.t.Helper()
55 p.send(wire.FrameSync, s)
56 p.lease("", 0)
57}
58
59// workerSync is a worker's sync after the welcome, saying conns.
60func workerSync(conns ...wire.HeldConnection) wire.Sync {
61 return wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}, Connections: append([]wire.HeldConnection{}, conns...)}
62}
63
64// TestContractWorkerReconnectKeepsHold (#1): the real reconnect sequence
65// (the hello before the welcome, the sync, the full hello after it)
66// never releases the hold nor signs a connection out: with a token on
67// disk, and with only a Keychain item left. Only a full report saying
68// nothing is left releases it; a later hello that does not say it is
69// full never does.
70func TestContractWorkerReconnectKeepsHold(t *testing.T) {
71 claude1 := wire.HeldConnection{LocalID: "claude-1", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, Label: "w@example.com", State: wire.ConnHealthy}
72 holds := func(c *wire.Capabilities) { c.ModelHold = true }
73 residue := func(c *wire.Capabilities) {
74 c.ModelHold, c.HoldingItems = true, []string{"Claude Code-credentials-1a2b3c4d"}
75 }
76 t.Run("a token on disk", func(t *testing.T) {
77 r := newMacRig(t)
78 key := sealKeys(t).PublicString()
79 w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection)
80 wid := w.fr.Welcome.RunnerID
81 w.heartbeat(inventoryHello(key, holds, claude1))
82 if c, ok := r.connRow(wid, "claude-1"); !ok || c.State != wire.ConnHealthy || !r.heldNow(wid) {
83 t.Fatalf("setup: %+v %v held=%v", c, ok, r.heldNow(wid))
84 }
85 stillThere := func(when string) {
86 t.Helper()
87 if c, _ := r.connRow(wid, "claude-1"); c.State != wire.ConnHealthy || !r.heldNow(wid) {
88 t.Fatalf("%s: row %s, held=%v", when, c.State, r.heldNow(wid))
89 }
90 }
91 // A hello before the welcome is never the inventory, whatever it
92 // says.
93 claims := handshakeHello()
94 claims.Inventory = true
95 w = r.redialMac(w, claims)
96 w.lease("", 0)
97 stillThere("a hello before the welcome claiming to be the inventory")
98 w = r.redialMac(w, handshakeHello())
99 w.lease("", 0)
100 stillThere("the hello before the welcome")
101 w.syncNow(workerSync(claude1))
102 stillThere("the sync")
103 w.heartbeat(inventoryHello(key, holds, claude1))
104 stillThere("the full hello")
105 // A hello that does not say it is full says nothing is gone.
106 partial := workerConnHello(key)
107 partial.Inventory = false
108 w.heartbeat(partial)
109 stillThere("a hello without its inventory")
110 // Nor does a marked hello with no capability report, or one the
111 // instance refuses: nothing in it can be judged (fix round 2).
112 bare := workerConnHello(key)
113 bare.Capabilities = nil
114 w.heartbeat(bare)
115 stillThere("a marked hello with no capability report")
116 invalid := workerConnHello(key)
117 caps := *invalid.Capabilities
118 caps.Tags = append([]string{"not-a-tag"}, caps.Tags...)
119 invalid.Capabilities = &caps
120 if wire.ValidCapabilities(caps) == nil {
121 t.Fatal("the report meant to be refused is valid")
122 }
123 w.heartbeat(invalid)
124 stillThere("a marked hello with a refused capability report")
125 w.heartbeat(inventoryHello(key, nil))
126 if c, _ := r.connRow(wid, "claude-1"); c.State != wire.ConnSignedOut || r.heldNow(wid) {
127 t.Fatalf("a full report of nothing: row %s, held=%v", c.State, r.heldNow(wid))
128 }
129 })
130 t.Run("only a Keychain item", func(t *testing.T) {
131 r := newMacRig(t)
132 key := sealKeys(t).PublicString()
133 w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection)
134 wid := w.fr.Welcome.RunnerID
135 w.heartbeat(inventoryHello(key, nil))
136 a, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, RunnerID: wid})
137 if err != nil {
138 t.Fatal(err)
139 }
140 w.expect(wire.FrameConnect)
141 w.send(wire.FrameConnection, wire.ConnectionReport{Connection: a.ID, Person: Owner, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: "provider_refused"})
142 w.heartbeat(inventoryHello(key, residue))
143 if !r.heldNow(wid) {
144 t.Fatal("setup: not held with an item left")
145 }
146 w = r.redialMac(w, handshakeHello())
147 w.lease("", 0)
148 if !r.heldNow(wid) {
149 t.Fatal("the hello before the welcome released the hold")
150 }
151 w.syncNow(workerSync())
152 if !r.heldNow(wid) {
153 t.Fatal("an empty sync released the hold")
154 }
155 w.heartbeat(inventoryHello(key, residue))
156 if !r.heldNow(wid) {
157 t.Fatal("the full hello naming the item released the hold")
158 }
159 w.heartbeat(inventoryHello(key, nil))
160 if r.heldNow(wid) {
161 t.Fatal("still held once the Mac said in full that nothing is left")
162 }
163 })
164}
165
166// TestContractWorkerSyncHolds (#2): a worker's sync that reports a
167// connection records it and holds the Mac in the same transaction; an
168// empty sync neither releases the hold nor signs the connection out.
169func TestContractWorkerSyncHolds(t *testing.T) {
170 r := newMacRig(t)
171 key := sealKeys(t).PublicString()
172 w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection)
173 wid := w.fr.Welcome.RunnerID
174 w.heartbeat(inventoryHello(key, nil))
175 if r.heldNow(wid) {
176 t.Fatal("held with nothing there")
177 }
178 w.syncNow(workerSync(wire.HeldConnection{LocalID: "claude-2", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy}))
179 if c, ok := r.connRow(wid, "claude-2"); !ok || c.State != wire.ConnHealthy || !r.heldNow(wid) {
180 t.Fatalf("after the sync: %+v %v held=%v", c, ok, r.heldNow(wid))
181 }
182 w.syncNow(workerSync())
183 if c, _ := r.connRow(wid, "claude-2"); c.State != wire.ConnHealthy || !r.heldNow(wid) {
184 t.Fatalf("an empty sync: row %s, held=%v", c.State, r.heldNow(wid))
185 }
186}
187
188// TestContractWorkerConnectionCommandsBelow37 (#3): a Mac that comes
189// back below 37 is delivered none of the connection commands queued for
190// it, and what it replays of its connections (a report, a check's usage)
191// changes nothing; back at 37 the queued command goes.
192func TestContractWorkerConnectionCommandsBelow37(t *testing.T) {
193 r := newMacRig(t)
194 key := sealKeys(t).PublicString()
195 w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection)
196 wid := w.fr.Welcome.RunnerID
197 w.heartbeat(inventoryHello(key, nil))
198 a, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken, RunnerID: wid})
199 if err != nil {
200 t.Fatal(err)
201 }
202 old := r.redialMac(w, macEngineerHello("Tito Studio", wire.EngineeringNoConnection, wire.ProtocolChangeDiffs, false))
203 if old.fr.Welcome.Protocol != wire.ProtocolChangeDiffs {
204 t.Fatalf("welcome %+v", old.fr.Welcome)
205 }
206 old.lease("", 0)
207 time.Sleep(300 * time.Millisecond)
208 old.lease("", 0)
209 for _, h := range old.held {
210 switch h.f.Type {
211 case wire.FrameConnect, wire.FrameSecret, wire.FrameCancelConnect, wire.FrameDisconnect, wire.FrameCheck, wire.FramePreference:
212 t.Fatalf("delivered below 37: %s", h.raw)
213 }
214 }
215 if r.unacked(wid, wire.FrameConnect) != 1 {
216 t.Fatal("the queued connect did not wait")
217 }
218 // What it replays from before changes nothing.
219 old.send(wire.FrameConnection, wire.ConnectionReport{Connection: a.ID, Person: Owner, LocalID: "claude-1", Provider: wire.ProviderClaude, State: wire.ConnHealthy, Label: "w@example.com"})
220 if c, err := r.client.Connection(r.ctx, a.ID); err != nil || c.State != wire.ConnConnecting || c.LocalID != "" {
221 t.Fatalf("a report below 37 applied: %+v %v", c, err)
222 }
223 old.send(wire.FrameUsage, wire.UsageReport{CheckID: "chk_old", Rows: []wire.Usage{{Provider: wire.ProviderClaude, Connection: "claude-1", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true}}})
224 if n := r.count("SELECT count(*) FROM chat_usage WHERE step_id = 'chk_old'"); n != 0 {
225 t.Fatalf("%d usage rows from a worker below 37", n)
226 }
227 // Back at 37: the queued connect goes.
228 back := r.redialMac(old, inventoryHello(key, nil))
229 if _, body := back.expect(wire.FrameConnect); body.(*wire.ConnectCommand).Connection != a.ID {
230 t.Fatalf("connect %+v", body)
231 }
232}
233
234// TestContractUsageBelow37 (#4): below 37 a usage row keeps the legacy
235// form (no runner) and a worker's connection usage is refused; at 37 the
236// row names the runner that reported it.
237func TestContractUsageBelow37(t *testing.T) {
238 report := func(id string) wire.UsageReport {
239 return wire.UsageReport{CheckID: id, Rows: []wire.Usage{{Provider: wire.ProviderClaude, Connection: "claude-1", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: i64(10), OutputTokens: i64(5)}}}
240 }
241 runnerOf := func(r *runnersRig, check string) (string, int) {
242 t.Helper()
243 var n int
244 var runner *string
245 if err := r.inst.DB.Writer().QueryRow("SELECT count(*), max(runner_id) FROM chat_usage WHERE step_id = ?", check).Scan(&n, &runner); err != nil {
246 t.Fatal(err)
247 }
248 if runner == nil {
249 return "<null>", n
250 }
251 return *runner, n
252 }
253 t.Run("36", func(t *testing.T) {
254 r := newMacRigAt(t, 36)
255 w := r.newMacEngineerAt("Tito Studio", wire.EngineeringNoConnection, 36, false)
256 r.primary.send(wire.FrameUsage, report("chk_p36"))
257 if got, n := runnerOf(r, "chk_p36"); n != 1 || got != "<null>" {
258 t.Fatalf("the primary's row at 36: %d rows, runner %s", n, got)
259 }
260 w.send(wire.FrameUsage, report("chk_w36"))
261 if _, n := runnerOf(r, "chk_w36"); n != 0 {
262 t.Fatalf("%d rows of a worker's connection usage at 36", n)
263 }
264 })
265 t.Run("37", func(t *testing.T) {
266 r := newMacRig(t)
267 w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection)
268 r.primary.send(wire.FrameUsage, report("chk_p37"))
269 if got, n := runnerOf(r, "chk_p37"); n != 1 || got != r.primary.fr.Welcome.RunnerID {
270 t.Fatalf("the primary's row at 37: %d rows, runner %s", n, got)
271 }
272 w.send(wire.FrameUsage, report("chk_w37"))
273 if got, n := runnerOf(r, "chk_w37"); n != 1 || got != w.fr.Welcome.RunnerID {
274 t.Fatalf("the worker's row at 37: %d rows, runner %s", n, got)
275 }
276 })
277}
278