]> git.giacomolli.uk - onechat/blob - build_run.go
Show styled replies only on terminal output
[onechat] / build_run.go
1 package main
2
3 import (
4         "bufio"
5         "cmp"
6         "context"
7         "encoding/json"
8         "errors"
9         "fmt"
10         "io"
11         "maps"
12         "os"
13         "slices"
14         "strconv"
15         "strings"
16         "time"
17 )
18
19 // buildLineBytes is the most bytes of one line in a build input or usage log.
20 const buildLineBytes = 1 << 20
21
22 // buildQuotaLimit is the largest increase in used quota points of a run.
23 const buildQuotaLimit = 15.0
24
25 // BuildRun appends messages, builds their tree, and stops the run by the rules
26 // of buildStop.
27 type BuildRun struct {
28         memory    *Memory
29         client    *ModelClient
30         usagePath string
31 }
32
33 // Run appends the entries. It waits for the builds only before a user message,
34 // as a turn does, so up to buildMax builds run at once in between, and it waits
35 // for all builds at the end. It returns the number of messages appended and why
36 // the run stopped early, or "" when it did not. After a stop it waits for the
37 // calls in flight, so no sent call is cancelled.
38 func (r *BuildRun) Run(ctx context.Context, entries []DatedMessage) (int, string) {
39         appended, reason := r.append(ctx, entries)
40         if reason == "" {
41                 return appended, ""
42         }
43
44         err := r.memory.Wait(ctx)
45         if err != nil {
46                 reason += "; " + err.Error()
47         }
48
49         return appended, reason
50 }
51
52 // append appends the entries and stops at the first stop rule.
53 func (r *BuildRun) append(ctx context.Context, entries []DatedMessage) (int, string) {
54         for n, entry := range entries {
55                 if entry.Kind == "user" {
56                         reason := r.wait(ctx)
57                         if reason != "" {
58                                 return n, reason
59                         }
60                 }
61
62                 if ctx.Err() != nil {
63                         return n, ctx.Err().Error()
64                 }
65
66                 _, err := r.memory.AppendDated(entry.Kind, entry.Text, entry.Date)
67                 if err != nil {
68                         return n, err.Error()
69                 }
70
71                 reason := r.check()
72                 if reason != "" {
73                         return n + 1, reason
74                 }
75         }
76
77         return len(entries), r.wait(ctx)
78 }
79
80 // wait returns when no build runs, or when a stop rule ends the run. It checks
81 // the rules each second, so a run stops soon also during a long wait.
82 func (r *BuildRun) wait(ctx context.Context) string {
83         for {
84                 reason := r.check()
85                 if reason != "" {
86                         return reason
87                 }
88
89                 err := r.waitBuilds(ctx)
90                 if err == nil {
91                         return r.check()
92                 }
93
94                 if ctx.Err() != nil {
95                         return ctx.Err().Error()
96                 }
97         }
98 }
99
100 // check returns why the run must stop, or "" when it can go on.
101 func (r *BuildRun) check() string {
102         if r.client.LimitReached() {
103                 return fmt.Sprintf("call limit of %d reached", r.client.CallLimit())
104         }
105
106         records, err := buildReadUsage(r.usagePath)
107         if err != nil {
108                 return err.Error()
109         }
110
111         return buildStop(records)
112 }
113
114 // waitBuilds waits up to one second without leaving a child context open.
115 func (r *BuildRun) waitBuilds(ctx context.Context) error {
116         ctx, cancel := context.WithTimeout(ctx, time.Second)
117         defer cancel()
118
119         return r.memory.Wait(ctx)
120 }
121
122 // DatedMessage is one message with an optional RFC 3339 date.
123 type DatedMessage struct {
124         Kind string `json:"kind"`
125         Text string `json:"text"`
126         Date string `json:"date,omitempty"`
127 }
128
129 // buildReadUsage reads the records of usage.jsonl at path, in the order of the
130 // start of their calls. The file has them in the order of the end of their
131 // calls, which differs when calls run at once.
132 func buildReadUsage(path string) (records []ModelUsageRecord, err error) {
133         file, err := os.Open(path)
134         if errors.Is(err, os.ErrNotExist) {
135                 return nil, nil
136         }
137
138         if err != nil {
139                 return nil, fmt.Errorf("open usage file: %w", err)
140         }
141
142         defer func() {
143                 closeErr := file.Close()
144                 if closeErr != nil {
145                         err = errors.Join(err, fmt.Errorf("close build usage: %w", closeErr))
146                 }
147         }()
148
149         scanner := bufio.NewScanner(file)
150         scanner.Buffer(make([]byte, 64*1024), buildLineBytes)
151
152         for scanner.Scan() {
153                 var record ModelUsageRecord
154
155                 err = json.Unmarshal(scanner.Bytes(), &record)
156                 if err != nil {
157                         return nil, fmt.Errorf("decode usage: %w", err)
158                 }
159
160                 records = append(records, record)
161         }
162
163         err = scanner.Err()
164         if err != nil {
165                 return nil, fmt.Errorf("read usage file: %w", err)
166         }
167
168         slices.SortStableFunc(records, func(a, b ModelUsageRecord) int {
169                 return buildCallStart(a).Compare(buildCallStart(b))
170         })
171
172         return records, nil
173 }
174
175 // buildWriteReport writes the result of a build run.
176 func buildWriteReport(out io.Writer, appended int, stop string, records []ModelUsageRecord, sizes []int) error {
177         var input, cached, output, failed int
178
179         for _, record := range records {
180                 input += record.InputTokens
181                 cached += record.CachedTokens
182                 output += record.OutputTokens
183                 if record.Error != "" {
184                         failed++
185                 }
186         }
187
188         var lines []string
189
190         if stop != "" {
191                 lines = append(lines, "stopped early: "+stop)
192         }
193
194         lines = append(lines,
195                 fmt.Sprintf("messages: %d", appended),
196                 fmt.Sprintf("calls: %d (%d failed), %.2f per message", len(records), failed, buildRatio(len(records), appended)),
197                 fmt.Sprintf("model lines: %d, retries: %d, %.2f calls per model line", len(sizes), len(records)-failed-len(sizes), buildRatio(len(records), len(sizes))),
198                 fmt.Sprintf("tokens: %d input, %d cached (%.1f%%), %d output", input, cached, 100*buildRatio(cached, input), output),
199         )
200
201         if len(sizes) > 0 {
202                 lines = append(lines, buildSizeText(sizes))
203         }
204
205         if len(records) > 0 {
206                 lines = append(lines, buildTimeText(records))
207         }
208
209         if len(records) > 0 {
210                 lines = append(lines,
211                         "quota at the first call: "+buildQuotaText(records[0]),
212                         "quota at the last call: "+buildQuotaText(records[len(records)-1]),
213                 )
214         }
215
216         _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
217         if err != nil {
218                 return fmt.Errorf("write build report: %w", err)
219         }
220
221         return nil
222 }
223
224 // buildStop returns why a build run must stop: a failed call, or a quota window
225 // whose used percent grew by more than buildQuotaLimit points since the first
226 // call. It returns "" when the run can go on.
227 func buildStop(records []ModelUsageRecord) string {
228         for _, record := range records {
229                 if record.Error != "" {
230                         return "call failed: " + record.Error
231                 }
232         }
233
234         if len(records) == 0 {
235                 return ""
236         }
237
238         first := buildUsedPercents(records[0])
239         for name, used := range buildUsedPercents(records[len(records)-1]) {
240                 start, found := first[name]
241                 if found && used-start > buildQuotaLimit {
242                         return fmt.Sprintf("%s grew from %g to %g", name, start, used)
243                 }
244         }
245
246         return ""
247 }
248
249 // buildCallStart returns the start of the call of record, or the zero time when
250 // its date is not valid.
251 func buildCallStart(record ModelUsageRecord) time.Time {
252         start, err := time.Parse(time.RFC3339Nano, record.Date)
253         if err != nil {
254                 return time.Time{}
255         }
256
257         return start
258 }
259
260 // buildRatio returns a / b, or 0 when b is 0.
261 func buildRatio(a, b int) float64 {
262         if b == 0 {
263                 return 0
264         }
265
266         return float64(a) / float64(b)
267 }
268
269 // buildSizeText describes the sizes of the model lines.
270 func buildSizeText(sizes []int) string {
271         sorted := slices.Sorted(slices.Values(sizes))
272         total, over := 0, 0
273         for _, size := range sorted {
274                 total += size
275                 if size > nodeBytes {
276                         over++
277                 }
278         }
279
280         return fmt.Sprintf("line bytes: min %d, median %d, mean %.0f, max %d, %d over %d", sorted[0], sorted[len(sorted)/2], buildRatio(total, len(sorted)), sorted[len(sorted)-1], over, nodeBytes)
281 }
282
283 // buildTimeText describes the time per call and how many calls ran at once. A
284 // call runs from its date for its seconds.
285 func buildTimeText(records []ModelUsageRecord) string {
286         type event struct {
287                 at    time.Time
288                 delta int
289         }
290
291         var events []event
292
293         seconds := make([]float64, 0, len(records))
294         total := 0.0
295         for _, record := range records {
296                 start, err := time.Parse(time.RFC3339Nano, record.Date)
297                 if err != nil {
298                         continue
299                 }
300
301                 length := time.Duration(record.Seconds * float64(time.Second))
302                 events = append(events, event{
303                         at:    start,
304                         delta: 1,
305                 }, event{
306                         at:    start.Add(length),
307                         delta: -1,
308                 })
309
310                 seconds = append(seconds, record.Seconds)
311                 total += record.Seconds
312         }
313
314         if len(events) == 0 {
315                 return "time: no dated calls"
316         }
317
318         slices.SortFunc(events, func(a, b event) int {
319                 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
320         })
321
322         running, most := 0, 0
323         for _, e := range events {
324                 running += e.delta
325                 most = max(most, running)
326         }
327
328         wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
329
330         slices.Sort(seconds)
331
332         return fmt.Sprintf("time: %.0f s in all, %.1f calls per minute, %.1f s per call (median %.1f, max %.1f), calls at once: at most %d, %.1f on average", wall, 60*float64(len(seconds))/max(wall, 1e-9), total/float64(len(seconds)), seconds[len(seconds)/2], seconds[len(seconds)-1], most, total/max(wall, 1e-9))
333 }
334
335 // buildQuotaText returns the quota headers of record, sorted by name.
336 func buildQuotaText(record ModelUsageRecord) string {
337         names := slices.Sorted(maps.Keys(record.Quota))
338         parts := make([]string, len(names))
339         for n, name := range names {
340                 parts[n] = strings.TrimPrefix(name, "x-codex-") + "=" + record.Quota[name]
341         }
342
343         return strings.Join(parts, " ")
344 }
345
346 // buildUsedPercents returns the used percent of each quota window of record, by
347 // header name.
348 func buildUsedPercents(record ModelUsageRecord) map[string]float64 {
349         used := make(map[string]float64)
350         for name, value := range record.Quota {
351                 if !strings.HasSuffix(name, "-used-percent") {
352                         continue
353                 }
354
355                 percent, err := strconv.ParseFloat(value, 64)
356                 if err == nil {
357                         used[name] = percent
358                 }
359         }
360
361         return used
362 }