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, probeName, 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 // probeEntry is one message of a probe log.
239 type probeEntry struct {
240 Kind string `json:"kind"`
241 Text string `json:"text"`
244 // readProbeLog reads the first count messages of the probe log at path.
245 func readProbeLog(path string, count int) (entries []probeEntry, err error) {
246 file, err := os.Open(path)
248 return nil, fmt.Errorf("open probe log: %w", err)
252 err = errors.Join(err, file.Close())
255 scanner := bufio.NewScanner(file)
256 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
257 for len(entries) < count && scanner.Scan() {
259 err = json.Unmarshal(scanner.Bytes(), &entry)
261 return nil, fmt.Errorf("probe log line %d: %w", len(entries)+1, err)
264 entries = append(entries, entry)
269 return nil, fmt.Errorf("read probe log: %w", err)
272 if len(entries) < count {
273 return nil, fmt.Errorf("probe log has %d messages, fewer than %d", len(entries), count)
279 // probeStop returns why a probe run must stop: a failed call, or a quota window
280 // whose used percent grew by more than probeQuotaLimit points since the first
281 // call. It returns "" when the run can go on.
282 func probeStop(records []usageRecord) string {
283 for _, record := range records {
284 if record.Error != "" {
285 return "call failed: " + record.Error
289 if len(records) == 0 {
293 first := usedPercents(records[0])
294 for name, used := range usedPercents(records[len(records)-1]) {
295 start, found := first[name]
296 if found && used-start > probeQuotaLimit {
297 return fmt.Sprintf("%s grew from %g to %g", name, start, used)
304 // modelLines returns the sizes of the nodes that the model wrote, in tree
305 // order. A node that fits its source with no model call is not one of them.
306 func modelLines(memory *Memory) ([]int, error) {
308 defer memory.mutex.Unlock()
310 keys, err := memory.tree.Keys()
316 for _, key := range keys {
317 node, _, err := memory.tree.Node(key.level, key.index)
322 model, err := builtByModel(memory, key)
328 sizes = append(sizes, node.Size)
335 // builtByModel tells if the node key needed a model call: a leaf whose source
336 // is over nodeBytes, or a merge whose children do not fit in one node.
337 func builtByModel(memory *Memory, key nodeKey) (bool, error) {
339 message, err := memory.log.Message(key.index)
344 _, free := freeLeaf(message)
349 left, right, err := memory.children(key)
354 _, free := freeMerge(left, right)
359 // readUsageFile reads the records of usage.jsonl at path, in the order of the
360 // start of their calls. The file has them in the order of the end of their
361 // calls, which differs when calls run at once.
362 func readUsageFile(path string) (records []usageRecord, err error) {
363 file, err := os.Open(path)
364 if errors.Is(err, os.ErrNotExist) {
369 return nil, fmt.Errorf("open usage file: %w", err)
373 err = errors.Join(err, file.Close())
376 scanner := bufio.NewScanner(file)
377 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
379 var record usageRecord
380 err = json.Unmarshal(scanner.Bytes(), &record)
382 return nil, fmt.Errorf("decode usage: %w", err)
385 records = append(records, record)
390 return nil, fmt.Errorf("read usage file: %w", err)
393 slices.SortStableFunc(records, func(a, b usageRecord) int {
394 return callStart(a).Compare(callStart(b))
400 // callStart returns the start of the call of record, or the zero time when its
401 // date is not valid.
402 func callStart(record usageRecord) time.Time {
403 start, err := time.Parse(time.RFC3339Nano, record.Date)
411 // usedPercents returns the used percent of each quota window of record, by
413 func usedPercents(record usageRecord) map[string]float64 {
414 used := make(map[string]float64)
415 for name, value := range record.Quota {
416 if !strings.HasSuffix(name, "-used-percent") {
420 percent, err := strconv.ParseFloat(value, 64)
429 // writeProbeReport writes the result of a probe run.
430 func writeProbeReport(out io.Writer, appended int, stop string, records []usageRecord, sizes []int) error {
431 var input, cached, output, failed int
432 for _, record := range records {
433 input += record.InputTokens
434 cached += record.CachedTokens
435 output += record.OutputTokens
436 if record.Error != "" {
443 lines = append(lines, "stopped early: "+stop)
446 lines = append(lines,
447 fmt.Sprintf("messages: %d", appended),
448 fmt.Sprintf("calls: %d (%d failed), %.2f per message", len(records), failed, ratio(len(records), appended)),
449 fmt.Sprintf("model lines: %d, retries: %d, %.2f calls per model line", len(sizes), len(records)-failed-len(sizes), ratio(len(records), len(sizes))),
450 fmt.Sprintf("tokens: %d input, %d cached (%.1f%%), %d output", input, cached, 100*ratio(cached, input), output),
454 lines = append(lines, sizeText(sizes))
457 if len(records) > 0 {
458 lines = append(lines, timeText(records))
461 if len(records) > 0 {
462 lines = append(lines,
463 "quota at the first call: "+quotaText(records[0]),
464 "quota at the last call: "+quotaText(records[len(records)-1]),
468 _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
473 // sizeText describes the sizes of the model lines.
474 func sizeText(sizes []int) string {
475 sorted := slices.Sorted(slices.Values(sizes))
477 for _, size := range sorted {
479 if size > nodeBytes {
484 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)
487 // timeText describes the time per call and how many calls ran at once. A call
488 // runs from its date for its seconds.
489 func timeText(records []usageRecord) string {
496 seconds := make([]float64, 0, len(records))
498 for _, record := range records {
499 start, err := time.Parse(time.RFC3339Nano, record.Date)
504 length := time.Duration(record.Seconds * float64(time.Second))
505 events = append(events, event{
509 at: start.Add(length),
512 seconds = append(seconds, record.Seconds)
513 total += record.Seconds
516 if len(events) == 0 {
517 return "time: no dated calls"
520 slices.SortFunc(events, func(a, b event) int {
521 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
524 running, most := 0, 0
525 for _, e := range events {
527 most = max(most, running)
530 wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
533 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))
536 // quotaText returns the quota headers of record, sorted by name.
537 func quotaText(record usageRecord) string {
538 names := slices.Sorted(maps.Keys(record.Quota))
539 parts := make([]string, len(names))
540 for n, name := range names {
541 parts[n] = strings.TrimPrefix(name, "x-codex-") + "=" + record.Quota[name]
544 return strings.Join(parts, " ")
547 // ratio returns a / b, or 0 when b is 0.
548 func ratio(a, b int) float64 {
553 return float64(a) / float64(b)