]> git.giacomolli.uk - onechat/blob - probe.go
Name package-level code for its feature
[onechat] / probe.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 "path/filepath"
14 "slices"
15 "strconv"
16 "strings"
17 "time"
18 )
19
20 const (
21 // probeName is the agent name of a probe run. The cache key comes from
22 // it.
23 probeName = "Probe"
24
25 // probeQuotaLimit is how many points the used percent of a quota window
26 // can grow in a probe run before the run stops.
27 probeQuotaLimit = 15.0
28
29 // probeCallLimit is the most model calls of a probe run.
30 probeCallLimit = 660
31
32 // probeLineBytes is the most bytes of one line of a probe log.
33 probeLineBytes = 1 << 20
34 )
35
36 // probe runs "onechat probe LOG COUNT [BUILDS]". It appends the first COUNT
37 // messages of LOG, one JSON object {kind, text} per line, to a new chat in
38 // probe/ in the data directory, and builds its tree with the real compactor.
39 // Before each user message it waits for the builds, as a turn does. It stops at
40 // the first failed call, after probeCallLimit calls, or when the used percent
41 // of a quota window grows by more than probeQuotaLimit points. At the end it
42 // reports the calls, the time per call, the calls at once, the cached share,
43 // the quota, the retries, and the line sizes. BUILDS, from 1 to maxBuilds,
44 // limits the builds that call the model at once in this run only. The core
45 // still queues up to maxBuilds builds. The run holds the lock of the token
46 // file, so it does not run while the daemon runs.
47 func probe(ctx context.Context, args []string, out io.Writer) (err error) {
48 if len(args) != 2 && len(args) != 3 {
49 return errors.New("usage: onechat probe LOG COUNT [BUILDS]")
50 }
51
52 count, err := strconv.Atoi(args[1])
53 if err != nil || count <= 0 {
54 return fmt.Errorf("COUNT %q is not a positive number", args[1])
55 }
56
57 builds := maxBuilds
58 if len(args) == 3 {
59 builds, err = strconv.Atoi(args[2])
60 if err != nil || builds < 1 || builds > maxBuilds {
61 return fmt.Errorf("BUILDS %q is not a number from 1 to %d", args[2], maxBuilds)
62 }
63 }
64
65 entries, err := readProbeLog(args[0], count)
66 if err != nil {
67 return err
68 }
69
70 dir, err := dataDir()
71 if err != nil {
72 return err
73 }
74
75 config, err := loadConfig(dir)
76 if err != nil {
77 return err
78 }
79
80 tokens, err := lockTokens(dir)
81 if err != nil {
82 return err
83 }
84
85 defer func() {
86 err = errors.Join(err, tokens.Close())
87 }()
88
89 address, auth, err := modelEndpoint(config, dir)
90 if err != nil {
91 return err
92 }
93
94 root := filepath.Join(dir, "probe", time.Now().Format("20060102-150405"))
95 err = os.MkdirAll(root, 0o700)
96 if err != nil {
97 return fmt.Errorf("create probe directory: %w", err)
98 }
99
100 usagePath := filepath.Join(root, "usage.jsonl")
101 client := newClient(address, auth, "onechat-"+probeName, usagePath)
102 client.LimitCalls(probeCallLimit)
103 summarizer := slotSummarizer{
104 inner: newCompactor(client, probePrompt, config.Compactor),
105 slots: make(chan struct{}, builds),
106 }
107
108 memory, err := openMemory(ctx, root, time.Now, summarizer)
109 if err != nil {
110 return err
111 }
112
113 _, err = fmt.Fprintf(out, "probe: %d messages into %s with %s at %s effort, %d builds at once\n", len(entries), root, config.Compactor.Model, config.Compactor.Effort, builds)
114 if err != nil {
115 return errors.Join(err, memory.Close())
116 }
117
118 run := probeRun{
119 memory: memory,
120 client: client,
121 usagePath: usagePath,
122 }
123
124 appended, stop := run.Run(ctx, entries)
125 sizes, err := modelLines(memory)
126 err = errors.Join(err, memory.Close())
127 if err != nil {
128 return err
129 }
130
131 records, err := readUsageFile(usagePath)
132 if err != nil {
133 return err
134 }
135
136 return writeProbeReport(out, appended, stop, records, sizes)
137 }
138
139 // probeRun appends the messages of a probe run to its chat and stops the run
140 // by the rules of probeStop.
141 type probeRun struct {
142 memory *Memory
143 client *Client
144 usagePath string
145 }
146
147 // Run appends the entries. It waits for the builds only before a user message,
148 // as a turn does, so up to maxBuilds builds run at once in between, and it
149 // waits for all builds at the end. It returns the number of messages appended
150 // and why the run stopped early, or "" when it did not. After a stop it waits
151 // for the calls in flight, so no sent call is cancelled.
152 func (r *probeRun) Run(ctx context.Context, entries []probeEntry) (int, string) {
153 appended, reason := r.append(ctx, entries)
154 if reason == "" {
155 return appended, ""
156 }
157
158 err := r.memory.Wait(ctx)
159 if err != nil {
160 reason += "; " + err.Error()
161 }
162
163 return appended, reason
164 }
165
166 // append appends the entries and stops at the first stop rule.
167 func (r *probeRun) append(ctx context.Context, entries []probeEntry) (int, string) {
168 for n, entry := range entries {
169 if entry.Kind == "user" {
170 reason := r.wait(ctx)
171 if reason != "" {
172 return n, reason
173 }
174 }
175
176 _, err := r.memory.Append(entry.Kind, entry.Text)
177 if err != nil {
178 return n, err.Error()
179 }
180
181 reason := r.check()
182 if reason != "" {
183 return n + 1, reason
184 }
185 }
186
187 return len(entries), r.wait(ctx)
188 }
189
190 // wait returns when no build runs, or when a stop rule ends the run. It checks
191 // the rules each second, so a run stops soon also during a long wait.
192 func (r *probeRun) wait(ctx context.Context) string {
193 for {
194 reason := r.check()
195 if reason != "" {
196 return reason
197 }
198
199 waitCtx, cancel := context.WithTimeout(ctx, time.Second)
200 err := r.memory.Wait(waitCtx)
201 cancel()
202 if err == nil {
203 return r.check()
204 }
205
206 if ctx.Err() != nil {
207 return ctx.Err().Error()
208 }
209 }
210 }
211
212 // check returns why the run must stop, or "" when it can go on.
213 func (r *probeRun) check() string {
214 if r.client.LimitReached() {
215 return fmt.Sprintf("call limit of %d reached", r.client.limit)
216 }
217
218 records, err := readUsageFile(r.usagePath)
219 if err != nil {
220 return err.Error()
221 }
222
223 return probeStop(records)
224 }
225
226 // slotSummarizer lets at most cap(slots) builds call inner at once. A build
227 // past the limit waits for a slot.
228 type slotSummarizer struct {
229 inner Summarizer
230 slots chan struct{}
231 }
232
233 // Summarize waits for a slot and builds the node with inner.
234 func (s slotSummarizer) Summarize(ctx context.Context, task Task) (string, error) {
235 select {
236 case s.slots <- struct{}{}:
237 case <-ctx.Done():
238 return "", ctx.Err()
239 }
240
241 defer func() {
242 <-s.slots
243 }()
244
245 return s.inner.Summarize(ctx, task)
246 }
247
248 // probePrompt returns the system prompt of a probe run: the prompt of the agent
249 // probeName, without instructions.
250 func probePrompt() (string, error) {
251 return prompt(probeName, ""), nil
252 }
253
254 // probeEntry is one message of a probe log.
255 type probeEntry struct {
256 Kind string `json:"kind"`
257 Text string `json:"text"`
258 }
259
260 // readProbeLog reads the first count messages of the probe log at path.
261 func readProbeLog(path string, count int) (entries []probeEntry, err error) {
262 file, err := os.Open(path)
263 if err != nil {
264 return nil, fmt.Errorf("open probe log: %w", err)
265 }
266
267 defer func() {
268 err = errors.Join(err, file.Close())
269 }()
270
271 scanner := bufio.NewScanner(file)
272 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
273 for len(entries) < count && scanner.Scan() {
274 var entry probeEntry
275 err = json.Unmarshal(scanner.Bytes(), &entry)
276 if err != nil {
277 return nil, fmt.Errorf("probe log line %d: %w", len(entries)+1, err)
278 }
279
280 entries = append(entries, entry)
281 }
282
283 err = scanner.Err()
284 if err != nil {
285 return nil, fmt.Errorf("read probe log: %w", err)
286 }
287
288 if len(entries) < count {
289 return nil, fmt.Errorf("probe log has %d messages, fewer than %d", len(entries), count)
290 }
291
292 return entries, nil
293 }
294
295 // probeStop returns why a probe run must stop: a failed call, or a quota window
296 // whose used percent grew by more than probeQuotaLimit points since the first
297 // call. It returns "" when the run can go on.
298 func probeStop(records []usageRecord) string {
299 for _, record := range records {
300 if record.Error != "" {
301 return "call failed: " + record.Error
302 }
303 }
304
305 if len(records) == 0 {
306 return ""
307 }
308
309 first := usedPercents(records[0])
310 for name, used := range usedPercents(records[len(records)-1]) {
311 start, found := first[name]
312 if found && used-start > probeQuotaLimit {
313 return fmt.Sprintf("%s grew from %g to %g", name, start, used)
314 }
315 }
316
317 return ""
318 }
319
320 // modelLines returns the sizes of the nodes that the model wrote, in tree
321 // order. A node that fits its source with no model call is not one of them.
322 func modelLines(memory *Memory) ([]int, error) {
323 memory.mutex.Lock()
324 defer memory.mutex.Unlock()
325
326 keys, err := memory.tree.Keys()
327 if err != nil {
328 return nil, err
329 }
330
331 var sizes []int
332 for _, key := range keys {
333 node, _, err := memory.tree.Node(key.level, key.index)
334 if err != nil {
335 return nil, err
336 }
337
338 model, err := builtByModel(memory, key)
339 if err != nil {
340 return nil, err
341 }
342
343 if model {
344 sizes = append(sizes, node.Size)
345 }
346 }
347
348 return sizes, nil
349 }
350
351 // builtByModel tells if the node key needed a model call: a leaf whose source
352 // is over nodeBytes, or a merge whose children do not fit in one node.
353 func builtByModel(memory *Memory, key nodeKey) (bool, error) {
354 if key.level == 0 {
355 message, err := memory.log.Message(key.index)
356 if err != nil {
357 return false, err
358 }
359
360 _, free := freeLeaf(message)
361
362 return !free, nil
363 }
364
365 left, right, err := memory.children(key)
366 if err != nil {
367 return false, err
368 }
369
370 _, free := freeMerge(left, right)
371
372 return !free, nil
373 }
374
375 // readUsageFile reads the records of usage.jsonl at path, in the order of the
376 // start of their calls. The file has them in the order of the end of their
377 // calls, which differs when calls run at once.
378 func readUsageFile(path string) (records []usageRecord, err error) {
379 file, err := os.Open(path)
380 if errors.Is(err, os.ErrNotExist) {
381 return nil, nil
382 }
383
384 if err != nil {
385 return nil, fmt.Errorf("open usage file: %w", err)
386 }
387
388 defer func() {
389 err = errors.Join(err, file.Close())
390 }()
391
392 scanner := bufio.NewScanner(file)
393 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
394 for scanner.Scan() {
395 var record usageRecord
396 err = json.Unmarshal(scanner.Bytes(), &record)
397 if err != nil {
398 return nil, fmt.Errorf("decode usage: %w", err)
399 }
400
401 records = append(records, record)
402 }
403
404 err = scanner.Err()
405 if err != nil {
406 return nil, fmt.Errorf("read usage file: %w", err)
407 }
408
409 slices.SortStableFunc(records, func(a, b usageRecord) int {
410 return callStart(a).Compare(callStart(b))
411 })
412
413 return records, nil
414 }
415
416 // callStart returns the start of the call of record, or the zero time when its
417 // date is not valid.
418 func callStart(record usageRecord) time.Time {
419 start, err := time.Parse(time.RFC3339Nano, record.Date)
420 if err != nil {
421 return time.Time{}
422 }
423
424 return start
425 }
426
427 // usedPercents returns the used percent of each quota window of record, by
428 // header name.
429 func usedPercents(record usageRecord) map[string]float64 {
430 used := make(map[string]float64)
431 for name, value := range record.Quota {
432 if !strings.HasSuffix(name, "-used-percent") {
433 continue
434 }
435
436 percent, err := strconv.ParseFloat(value, 64)
437 if err == nil {
438 used[name] = percent
439 }
440 }
441
442 return used
443 }
444
445 // writeProbeReport writes the result of a probe run.
446 func writeProbeReport(out io.Writer, appended int, stop string, records []usageRecord, sizes []int) error {
447 var input, cached, output, failed int
448 for _, record := range records {
449 input += record.InputTokens
450 cached += record.CachedTokens
451 output += record.OutputTokens
452 if record.Error != "" {
453 failed++
454 }
455 }
456
457 var lines []string
458 if stop != "" {
459 lines = append(lines, "stopped early: "+stop)
460 }
461
462 lines = append(lines,
463 fmt.Sprintf("messages: %d", appended),
464 fmt.Sprintf("calls: %d (%d failed), %.2f per message", len(records), failed, ratio(len(records), appended)),
465 fmt.Sprintf("model lines: %d, retries: %d, %.2f calls per model line", len(sizes), len(records)-failed-len(sizes), ratio(len(records), len(sizes))),
466 fmt.Sprintf("tokens: %d input, %d cached (%.1f%%), %d output", input, cached, 100*ratio(cached, input), output),
467 )
468
469 if len(sizes) > 0 {
470 lines = append(lines, sizeText(sizes))
471 }
472
473 if len(records) > 0 {
474 lines = append(lines, timeText(records))
475 }
476
477 if len(records) > 0 {
478 lines = append(lines,
479 "quota at the first call: "+quotaText(records[0]),
480 "quota at the last call: "+quotaText(records[len(records)-1]),
481 )
482 }
483
484 _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
485
486 return err
487 }
488
489 // sizeText describes the sizes of the model lines.
490 func sizeText(sizes []int) string {
491 sorted := slices.Sorted(slices.Values(sizes))
492 total, over := 0, 0
493 for _, size := range sorted {
494 total += size
495 if size > nodeBytes {
496 over++
497 }
498 }
499
500 return fmt.Sprintf("line bytes: min %d, median %d, mean %.0f, max %d, %d over %d", sorted[0], sorted[len(sorted)/2], ratio(total, len(sorted)), sorted[len(sorted)-1], over, nodeBytes)
501 }
502
503 // timeText describes the time per call and how many calls ran at once. A call
504 // runs from its date for its seconds.
505 func timeText(records []usageRecord) string {
506 type event struct {
507 at time.Time
508 delta int
509 }
510
511 var events []event
512 seconds := make([]float64, 0, len(records))
513 total := 0.0
514 for _, record := range records {
515 start, err := time.Parse(time.RFC3339Nano, record.Date)
516 if err != nil {
517 continue
518 }
519
520 length := time.Duration(record.Seconds * float64(time.Second))
521 events = append(events, event{
522 at: start,
523 delta: 1,
524 }, event{
525 at: start.Add(length),
526 delta: -1,
527 })
528 seconds = append(seconds, record.Seconds)
529 total += record.Seconds
530 }
531
532 if len(events) == 0 {
533 return "time: no dated calls"
534 }
535
536 slices.SortFunc(events, func(a, b event) int {
537 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
538 })
539
540 running, most := 0, 0
541 for _, e := range events {
542 running += e.delta
543 most = max(most, running)
544 }
545
546 wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
547 slices.Sort(seconds)
548
549 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))
550 }
551
552 // quotaText returns the quota headers of record, sorted by name.
553 func quotaText(record usageRecord) string {
554 names := slices.Sorted(maps.Keys(record.Quota))
555 parts := make([]string, len(names))
556 for n, name := range names {
557 parts[n] = strings.TrimPrefix(name, "x-codex-") + "=" + record.Quota[name]
558 }
559
560 return strings.Join(parts, " ")
561 }
562
563 // ratio returns a / b, or 0 when b is 0.
564 func ratio(a, b int) float64 {
565 if b == 0 {
566 return 0
567 }
568
569 return float64(a) / float64(b)
570 }