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.
46 func probe(ctx context.Context, args []string, out io.Writer) error {
47 if len(args) != 2 && len(args) != 3 {
48 return errors.New("usage: onechat probe LOG COUNT [BUILDS]")
51 count, err := strconv.Atoi(args[1])
52 if err != nil || count <= 0 {
53 return fmt.Errorf("COUNT %q is not a positive number", args[1])
58 builds, err = strconv.Atoi(args[2])
59 if err != nil || builds < 1 || builds > maxBuilds {
60 return fmt.Errorf("BUILDS %q is not a number from 1 to %d", args[2], maxBuilds)
64 entries, err := readProbeLog(args[0], count)
74 config, err := loadConfig(dir)
79 address, auth, err := modelEndpoint(config, dir)
84 root := filepath.Join(dir, "probe", time.Now().Format("20060102-150405"))
85 err = os.MkdirAll(root, 0o700)
87 return fmt.Errorf("create probe directory: %w", err)
90 usagePath := filepath.Join(root, "usage.jsonl")
91 client := newClient(address, auth, "onechat-"+probeName, usagePath)
92 client.LimitCalls(probeCallLimit)
93 summarizer := slotSummarizer{
94 inner: newCompactor(client, probePrompt, config.Compactor),
95 slots: make(chan struct{}, builds),
98 memory, err := openMemory(ctx, root, time.Now, summarizer)
103 _, 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)
105 return errors.Join(err, memory.Close())
111 usagePath: usagePath,
114 appended, stop := run.Run(ctx, entries)
115 sizes, err := modelLines(memory)
116 err = errors.Join(err, memory.Close())
121 records, err := readUsageFile(usagePath)
126 return writeProbeReport(out, appended, stop, records, sizes)
129 // probeRun appends the messages of a probe run to its chat and stops the run
130 // by the rules of probeStop.
131 type probeRun struct {
137 // Run appends the entries. It waits for the builds only before a user message,
138 // as a turn does, so up to maxBuilds builds run at once in between, and it
139 // waits for all builds at the end. It returns the number of messages appended
140 // and why the run stopped early, or "" when it did not. After a stop it waits
141 // for the calls in flight, so no sent call is cancelled.
142 func (r *probeRun) Run(ctx context.Context, entries []probeEntry) (int, string) {
143 appended, reason := r.append(ctx, entries)
148 err := r.memory.Wait(ctx)
150 reason += "; " + err.Error()
153 return appended, reason
156 // append appends the entries and stops at the first stop rule.
157 func (r *probeRun) append(ctx context.Context, entries []probeEntry) (int, string) {
158 for n, entry := range entries {
159 if entry.Kind == "user" {
160 reason := r.wait(ctx)
166 _, err := r.memory.Append(entry.Kind, entry.Text)
168 return n, err.Error()
177 return len(entries), r.wait(ctx)
180 // wait returns when no build runs, or when a stop rule ends the run. It checks
181 // the rules each second, so a run stops soon also during a long wait.
182 func (r *probeRun) wait(ctx context.Context) string {
189 waitCtx, cancel := context.WithTimeout(ctx, time.Second)
190 err := r.memory.Wait(waitCtx)
196 if ctx.Err() != nil {
197 return ctx.Err().Error()
202 // check returns why the run must stop, or "" when it can go on.
203 func (r *probeRun) check() string {
204 if r.client.LimitReached() {
205 return fmt.Sprintf("call limit of %d reached", r.client.limit)
208 records, err := readUsageFile(r.usagePath)
213 return probeStop(records)
216 // slotSummarizer lets at most cap(slots) builds call inner at once. A build
217 // past the limit waits for a slot.
218 type slotSummarizer struct {
223 // Summarize waits for a slot and builds the node with inner.
224 func (s slotSummarizer) Summarize(ctx context.Context, task Task) (string, error) {
226 case s.slots <- struct{}{}:
235 return s.inner.Summarize(ctx, task)
238 // probePrompt returns the system prompt of a probe run: the prompt of the agent
239 // probeName, without instructions.
240 func probePrompt() (string, error) {
241 return prompt(probeName, ""), nil
244 // probeEntry is one message of a probe log.
245 type probeEntry struct {
246 Kind string `json:"kind"`
247 Text string `json:"text"`
250 // readProbeLog reads the first count messages of the probe log at path.
251 func readProbeLog(path string, count int) (entries []probeEntry, err error) {
252 file, err := os.Open(path)
254 return nil, fmt.Errorf("open probe log: %w", err)
258 err = errors.Join(err, file.Close())
261 scanner := bufio.NewScanner(file)
262 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
263 for len(entries) < count && scanner.Scan() {
265 err = json.Unmarshal(scanner.Bytes(), &entry)
267 return nil, fmt.Errorf("probe log line %d: %w", len(entries)+1, err)
270 entries = append(entries, entry)
275 return nil, fmt.Errorf("read probe log: %w", err)
278 if len(entries) < count {
279 return nil, fmt.Errorf("probe log has %d messages, fewer than %d", len(entries), count)
285 // probeStop returns why a probe run must stop: a failed call, or a quota window
286 // whose used percent grew by more than probeQuotaLimit points since the first
287 // call. It returns "" when the run can go on.
288 func probeStop(records []usageRecord) string {
289 for _, record := range records {
290 if record.Error != "" {
291 return "call failed: " + record.Error
295 if len(records) == 0 {
299 first := usedPercents(records[0])
300 for name, used := range usedPercents(records[len(records)-1]) {
301 start, found := first[name]
302 if found && used-start > probeQuotaLimit {
303 return fmt.Sprintf("%s grew from %g to %g", name, start, used)
310 // modelLines returns the sizes of the nodes that the model wrote, in tree
311 // order. A node that fits its source with no model call is not one of them.
312 func modelLines(memory *Memory) ([]int, error) {
314 defer memory.mutex.Unlock()
316 keys, err := memory.tree.Keys()
322 for _, key := range keys {
323 node, _, err := memory.tree.Node(key.level, key.index)
328 model, err := builtByModel(memory, key)
334 sizes = append(sizes, node.Size)
341 // builtByModel tells if the node key needed a model call: a leaf whose source
342 // is over nodeBytes, or a merge whose children do not fit in one node.
343 func builtByModel(memory *Memory, key nodeKey) (bool, error) {
345 message, err := memory.log.Message(key.index)
350 _, free := freeLeaf(message)
355 left, right, err := memory.children(key)
360 _, free := freeMerge(left, right)
365 // readUsageFile reads the records of usage.jsonl at path, in the order of the
366 // start of their calls. The file has them in the order of the end of their
367 // calls, which differs when calls run at once.
368 func readUsageFile(path string) (records []usageRecord, err error) {
369 file, err := os.Open(path)
370 if errors.Is(err, os.ErrNotExist) {
375 return nil, fmt.Errorf("open usage file: %w", err)
379 err = errors.Join(err, file.Close())
382 scanner := bufio.NewScanner(file)
383 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
385 var record usageRecord
386 err = json.Unmarshal(scanner.Bytes(), &record)
388 return nil, fmt.Errorf("decode usage: %w", err)
391 records = append(records, record)
396 return nil, fmt.Errorf("read usage file: %w", err)
399 slices.SortStableFunc(records, func(a, b usageRecord) int {
400 return callStart(a).Compare(callStart(b))
406 // callStart returns the start of the call of record, or the zero time when its
407 // date is not valid.
408 func callStart(record usageRecord) time.Time {
409 start, err := time.Parse(time.RFC3339Nano, record.Date)
417 // usedPercents returns the used percent of each quota window of record, by
419 func usedPercents(record usageRecord) map[string]float64 {
420 used := make(map[string]float64)
421 for name, value := range record.Quota {
422 if !strings.HasSuffix(name, "-used-percent") {
426 percent, err := strconv.ParseFloat(value, 64)
435 // writeProbeReport writes the result of a probe run.
436 func writeProbeReport(out io.Writer, appended int, stop string, records []usageRecord, sizes []int) error {
437 var input, cached, output, failed int
438 for _, record := range records {
439 input += record.InputTokens
440 cached += record.CachedTokens
441 output += record.OutputTokens
442 if record.Error != "" {
449 lines = append(lines, "stopped early: "+stop)
452 lines = append(lines,
453 fmt.Sprintf("messages: %d", appended),
454 fmt.Sprintf("calls: %d (%d failed), %.2f per message", len(records), failed, ratio(len(records), appended)),
455 fmt.Sprintf("model lines: %d, retries: %d, %.2f calls per model line", len(sizes), len(records)-failed-len(sizes), ratio(len(records), len(sizes))),
456 fmt.Sprintf("tokens: %d input, %d cached (%.1f%%), %d output", input, cached, 100*ratio(cached, input), output),
460 lines = append(lines, sizeText(sizes))
463 if len(records) > 0 {
464 lines = append(lines, timeText(records))
467 if len(records) > 0 {
468 lines = append(lines,
469 "quota at the first call: "+quotaText(records[0]),
470 "quota at the last call: "+quotaText(records[len(records)-1]),
474 _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
479 // sizeText describes the sizes of the model lines.
480 func sizeText(sizes []int) string {
481 sorted := slices.Sorted(slices.Values(sizes))
483 for _, size := range sorted {
485 if size > nodeBytes {
490 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)
493 // timeText describes the time per call and how many calls ran at once. A call
494 // runs from its date for its seconds.
495 func timeText(records []usageRecord) string {
502 seconds := make([]float64, 0, len(records))
504 for _, record := range records {
505 start, err := time.Parse(time.RFC3339Nano, record.Date)
510 length := time.Duration(record.Seconds * float64(time.Second))
511 events = append(events, event{
515 at: start.Add(length),
518 seconds = append(seconds, record.Seconds)
519 total += record.Seconds
522 if len(events) == 0 {
523 return "time: no dated calls"
526 slices.SortFunc(events, func(a, b event) int {
527 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
530 running, most := 0, 0
531 for _, e := range events {
533 most = max(most, running)
536 wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
539 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))
542 // quotaText returns the quota headers of record, sorted by name.
543 func quotaText(record usageRecord) string {
544 names := slices.Sorted(maps.Keys(record.Quota))
545 parts := make([]string, len(names))
546 for n, name := range names {
547 parts[n] = strings.TrimPrefix(name, "x-codex-") + "=" + record.Quota[name]
550 return strings.Join(parts, " ")
553 // ratio returns a / b, or 0 when b is 0.
554 func ratio(a, b int) float64 {
559 return float64(a) / float64(b)