| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner" |
| 13 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 14 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // The controller's ruling #7: in production a stale Codex reading is |
| 19 | // refreshed by the app-server's account/rateLimits/read, run as the |
| 20 | // hourly refresh runs (the source home under its lock); Claude has no |
| 21 | // such read and stays as last reported. The reading is stamped with the |
| 22 | // time it was taken, and a reading that says the same again is no new |
| 23 | // reading for held steps. |
| 24 | func TestCodexReadingInProduction(t *testing.T) { |
| 25 | r := newConnectorRig(t) |
| 26 | r.cfg.ScratchRoot = filepath.Join(t.TempDir(), "scratch") |
| 27 | reads := 0 |
| 28 | limits := json.RawMessage(`{"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1762941600},"secondary":{"usedPercent":12,"windowDurationMins":10080,"resetsAt":1763287200},"planType":"pro","rateLimitReachedType":null}`) |
| 29 | read := func(_ context.Context, b provider.Binding) (provider.Identity, json.RawMessage, error) { |
| 30 | reads++ |
| 31 | if b.Home != r.home || b.Provider != wire.ProviderCodex { |
| 32 | t.Fatalf("read %+v", b) |
| 33 | } |
| 34 | return provider.Identity{AccountID: "a@example.com", ProviderVersion: "1"}, limits, nil |
| 35 | } |
| 36 | reading := CodexReading(r.cfg, read, time.Second) |
| 37 | b, ok := r.conns.Binding("codex-1") |
| 38 | if !ok { |
| 39 | t.Fatal("no binding") |
| 40 | } |
| 41 | // The home as a sign-in leaves it: its identity and its credential. |
| 42 | identity, _ := json.Marshal(b.ExpectedIdentity) |
| 43 | for name, body := range map[string][]byte{provider.IdentityFile: identity, "auth.json": []byte(`{"tokens":{}}`)} { |
| 44 | if err := os.WriteFile(filepath.Join(r.home, name), body, 0600); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | } |
| 48 | l, err := reading(context.Background(), b) |
| 49 | if err != nil || l == nil || reads != 1 || len(l.Headroom.Windows) != 2 || l.Headroom.Windows[0].UsedPercent != 61 { |
| 50 | t.Fatalf("codex: %+v %v (%d reads)", l, err, reads) |
| 51 | } |
| 52 | for _, other := range []runner.AccountBinding{{ID: "claude-1", Provider: wire.ProviderClaude}, {ID: "codex-t", Provider: wire.ProviderCodex, Kind: wire.KindToken}, {ID: "tensorx-1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey}} { |
| 53 | if l, err := reading(context.Background(), other); l != nil || err != nil { |
| 54 | t.Fatalf("%s read: %+v %v", other.ID, l, err) |
| 55 | } |
| 56 | } |
| 57 | if reads != 1 { |
| 58 | t.Fatalf("%d reads: only Codex subscriptions are read", reads) |
| 59 | } |
| 60 | |
| 61 | // Observe stamps the reading's time; the same figures again move the |
| 62 | // time only, and wake no held step. |
| 63 | woken := 0 |
| 64 | r.conns.Readings = func() { woken++ } |
| 65 | at := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) |
| 66 | r.conns.now = func() time.Time { return at } |
| 67 | r.conns.Observe("codex-1", *l, "") |
| 68 | held := func() *wire.Headroom { |
| 69 | for _, h := range r.conns.Held() { |
| 70 | if h.LocalID == "codex-1" { |
| 71 | return h.Headroom |
| 72 | } |
| 73 | } |
| 74 | return nil |
| 75 | } |
| 76 | if h := held(); h == nil || h.CheckedAt == nil || !h.CheckedAt.Equal(at) { |
| 77 | t.Fatalf("reading time %+v", h) |
| 78 | } |
| 79 | at = at.Add(20 * time.Minute) |
| 80 | r.conns.Observe("codex-1", *l, "") |
| 81 | if h := held(); h.CheckedAt == nil || !h.CheckedAt.Equal(at) || woken != 0 { |
| 82 | t.Fatalf("the same reading again: time %v, woke %d", h.CheckedAt, woken) |
| 83 | } |
| 84 | if l.Headroom.CheckedAt != nil { |
| 85 | t.Fatal("Observe changed the caller's reading") |
| 86 | } |
| 87 | l.Headroom.Windows[0].UsedPercent = 70 |
| 88 | r.conns.Observe("codex-1", *l, "") |
| 89 | if woken != 1 { |
| 90 | t.Fatalf("a new reading woke %d", woken) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | // A reading's age is its own time: a connection whose row was written |
| 95 | // just now (a state change) but whose reading is sixteen minutes old is |
| 96 | // refreshed before the scheduler decides. |
| 97 | func TestScheduleRefreshUsesReadingTime(t *testing.T) { |
| 98 | r := newSchedRig(t, "claude-a") |
| 99 | base := time.Now() |
| 100 | r.conns.now = func() time.Time { return base.Add(-16 * time.Minute) } |
| 101 | r.reading("claude-a", 0.9, base.Add(time.Hour)) |
| 102 | r.conns.now = func() time.Time { return base } |
| 103 | // The row is written again now, the reading unchanged. |
| 104 | r.conns.mu.Lock() |
| 105 | cs := r.conns.live["claude-a"] |
| 106 | r.conns.save("claude-a", cs) |
| 107 | r.conns.mu.Unlock() |
| 108 | probes := 0 |
| 109 | r.conns.Reading = func(context.Context, runner.AccountBinding) (*connect.Limit, error) { |
| 110 | probes++ |
| 111 | at := base.Add(time.Hour) |
| 112 | return &connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: 10, Minutes: 300, ResetsAt: &at}}}}, nil |
| 113 | } |
| 114 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| 115 | if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil); !d.d.Run || probes != 1 { |
| 116 | t.Fatalf("a sixteen-minute-old reading: %+v, %d probes", d.d, probes) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | // TestHandshakeHelloWithholdsReadingTimes: the first hello goes out |
| 121 | // before the instance says its protocol, so no headroom in it says when |
| 122 | // it was read; after a protocol 15 welcome the next hello, sent at once, |
| 123 | // does; at 14 none ever does. |
| 124 | func TestHandshakeHelloWithholdsReadingTimes(t *testing.T) { |
| 125 | at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC) |
| 126 | hello := func() wire.Hello { |
| 127 | return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}, |
| 128 | Connections: []wire.HeldConnection{{LocalID: "codex-1", Person: connPerson, Provider: wire.ProviderCodex, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: &wire.Headroom{Windows: []wire.Window{}, CheckedAt: &at}}}} |
| 129 | } |
| 130 | for _, protocol := range []int{wire.ProtocolScheduler, wire.ProtocolReadings} { |
| 131 | inst := newFakeInstance(t) |
| 132 | link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) |
| 133 | c := <-inst.conns |
| 134 | _, raw := read(t, c, wire.FrameHello) |
| 135 | if strings.Contains(string(raw), `"checked_at"`) || !strings.Contains(string(raw), `"codex-1"`) { |
| 136 | t.Fatalf("handshake hello: %s", raw) |
| 137 | } |
| 138 | welcome, _ := json.Marshal(wire.Frame{ID: "w-r", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":` + itoa(int64(protocol)) + `,"role":"primary"}`)}) |
| 139 | write(t, c, welcome) |
| 140 | read(t, c, wire.FrameSync) |
| 141 | if protocol < wire.ProtocolReadings { |
| 142 | link.HelloSoon() |
| 143 | } |
| 144 | _, raw = read(t, c, wire.FrameHello) |
| 145 | if got := strings.Contains(string(raw), `"checked_at":"2026-11-12T09:58:00Z"`); got != (protocol >= wire.ProtocolReadings) { |
| 146 | t.Fatalf("protocol %d hello: %s", protocol, raw) |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |