21 // probeName is the agent name of a probe run. The cache key comes from
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
29 // probeCallLimit is the most model calls of a probe run.
32 // probeLineBytes is the most bytes of one line of a probe log.
33 probeLineBytes = 1 << 20
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]")
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])
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)
65 entries, err := readProbeLog(args[0], count)
75 config, err := loadConfig(dir)
80 tokens, err := lockTokens(dir)
86 err = errors.Join(err, tokens.Close())
89 address, auth, err := modelEndpoint(config, dir)
94 root := filepath.Join(dir, "probe", time.Now().Format("20060102-150405"))
95 err = os.MkdirAll(root, 0o700)
97 return fmt.Errorf("create probe directory: %w", err)
100 usagePath := filepath.Join(root, "usage.jsonl")
101 client := newModelClient(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),
108 memory, err := openMemory(ctx, root, time.Now, summarizer)
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)
115 return errors.Join(err, memory.Close())
121 usagePath: usagePath,
124 appended, stop := run.Run(ctx, entries)
125 sizes, err := modelLines(memory)
126 err = errors.Join(err, memory.Close())
131 records, err := readUsageFile(usagePath)
136 return writeProbeReport(out, appended, stop, records, sizes)
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 {
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)
158 err := r.memory.Wait(ctx)
160 reason += "; " + err.Error()
163 return appended, reason
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)
176 _, err := r.memory.Append(entry.Kind, entry.Text)
178 return n, err.Error()
187 return len(entries), r.wait(ctx)
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 {
199 waitCtx, cancel := context.WithTimeout(ctx, time.Second)
200 err := r.memory.Wait(waitCtx)
206 if ctx.Err() != nil {
207 return ctx.Err().Error()
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)
218 records, err := readUsageFile(r.usagePath)
223 return probeStop(records)
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 {
233 // Summarize waits for a slot and builds the node with inner.
234 func (s slotSummarizer) Summarize(ctx context.Context, task Task) (string, error) {
236 case s.slots <- struct{}{}:
245 return s.inner.Summarize(ctx, task)
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
254 // probeEntry is one message of a probe log.
255 type probeEntry struct {
256 Kind string `json:"kind"`
257 Text string `json:"text"`
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)
264 return nil, fmt.Errorf("open probe log: %w", err)
268 err = errors.Join(err, file.Close())
271 scanner := bufio.NewScanner(file)
272 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
273 for len(entries) < count && scanner.Scan() {
275 err = json.Unmarshal(scanner.Bytes(), &entry)
277 return nil, fmt.Errorf("probe log line %d: %w", len(entries)+1, err)
280 entries = append(entries, entry)
285 return nil, fmt.Errorf("read probe log: %w", err)
288 if len(entries) < count {
289 return nil, fmt.Errorf("probe log has %d messages, fewer than %d", len(entries), count)
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 []ModelUsageRecord) string {
299 for _, record := range records {
300 if record.Error != "" {
301 return "call failed: " + record.Error
305 if len(records) == 0 {
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)
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) {
324 defer memory.mutex.Unlock()
326 keys, err := memory.tree.Keys()
332 for _, key := range keys {
333 node, _, err := memory.tree.Node(key.level, key.index)
338 model, err := builtByModel(memory, key)
344 sizes = append(sizes, node.Size)
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) {
355 message, err := memory.log.Message(key.index)
360 _, free := freeLeaf(message)
365 left, right, err := memory.children(key)
370 _, free := freeMerge(left, right)
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 []ModelUsageRecord, err error) {
379 file, err := os.Open(path)
380 if errors.Is(err, os.ErrNotExist) {
385 return nil, fmt.Errorf("open usage file: %w", err)
389 err = errors.Join(err, file.Close())
392 scanner := bufio.NewScanner(file)
393 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
395 var record ModelUsageRecord
396 err = json.Unmarshal(scanner.Bytes(), &record)
398 return nil, fmt.Errorf("decode usage: %w", err)
401 records = append(records, record)
406 return nil, fmt.Errorf("read usage file: %w", err)
409 slices.SortStableFunc(records, func(a, b ModelUsageRecord) int {
410 return callStart(a).Compare(callStart(b))
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 ModelUsageRecord) time.Time {
419 start, err := time.Parse(time.RFC3339Nano, record.Date)
427 // usedPercents returns the used percent of each quota window of record, by
429 func usedPercents(record ModelUsageRecord) map[string]float64 {
430 used := make(map[string]float64)
431 for name, value := range record.Quota {
432 if !strings.HasSuffix(name, "-used-percent") {
436 percent, err := strconv.ParseFloat(value, 64)
445 // writeProbeReport writes the result of a probe run.
446 func writeProbeReport(out io.Writer, appended int, stop string, records []ModelUsageRecord, 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 != "" {
459 lines = append(lines, "stopped early: "+stop)
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),
470 lines = append(lines, sizeText(sizes))
473 if len(records) > 0 {
474 lines = append(lines, timeText(records))
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]),
484 _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
489 // sizeText describes the sizes of the model lines.
490 func sizeText(sizes []int) string {
491 sorted := slices.Sorted(slices.Values(sizes))
493 for _, size := range sorted {
495 if size > nodeBytes {
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)
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 []ModelUsageRecord) string {
512 seconds := make([]float64, 0, len(records))
514 for _, record := range records {
515 start, err := time.Parse(time.RFC3339Nano, record.Date)
520 length := time.Duration(record.Seconds * float64(time.Second))
521 events = append(events, event{
525 at: start.Add(length),
528 seconds = append(seconds, record.Seconds)
529 total += record.Seconds
532 if len(events) == 0 {
533 return "time: no dated calls"
536 slices.SortFunc(events, func(a, b event) int {
537 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
540 running, most := 0, 0
541 for _, e := range events {
543 most = max(most, running)
546 wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
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))
552 // quotaText returns the quota headers of record, sorted by name.
553 func quotaText(record ModelUsageRecord) 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]
560 return strings.Join(parts, " ")
563 // ratio returns a / b, or 0 when b is 0.
564 func ratio(a, b int) float64 {
569 return float64(a) / float64(b)