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". It appends the first COUNT messages of
37 // LOG, one JSON object {kind, text} per line, to a new chat in probe/ in the
38 // data directory, and builds its tree with the real compactor. Before each
39 // user message it waits for the builds, as a turn does. It stops at the first
40 // failed call, after probeCallLimit calls, or when the used percent of a quota
41 // window grows by more than probeQuotaLimit points. At the end it reports the
42 // calls, the time per call, the calls at once, the cached share, the quota,
43 // the retries, and the line sizes.
44 func probe(ctx context.Context, args []string, out io.Writer) error {
46 return errors.New("usage: onechat probe LOG COUNT")
49 count, err := strconv.Atoi(args[1])
50 if err != nil || count <= 0 {
51 return fmt.Errorf("COUNT %q is not a positive number", args[1])
54 entries, err := readProbeLog(args[0], count)
64 config, err := loadConfig(dir)
69 address, auth, err := modelEndpoint(config, dir)
74 root := filepath.Join(dir, "probe", time.Now().Format("20060102-150405"))
75 err = os.MkdirAll(root, 0o700)
77 return fmt.Errorf("create probe directory: %w", err)
80 usagePath := filepath.Join(root, "usage.jsonl")
81 client := newClient(address, auth, "onechat-"+probeName, usagePath)
82 client.LimitCalls(probeCallLimit)
83 memory, err := openMemory(ctx, root, time.Now, newCompactor(client, probeName, config.Compactor))
88 _, err = fmt.Fprintf(out, "probe: %d messages into %s with %s at %s effort\n", len(entries), root, config.Compactor.Model, config.Compactor.Effort)
90 return errors.Join(err, memory.Close())
99 appended, stop := run.Run(ctx, entries)
100 sizes, err := modelLines(memory)
101 err = errors.Join(err, memory.Close())
106 records, err := readUsageFile(usagePath)
111 return writeProbeReport(out, appended, stop, records, sizes)
114 // probeRun appends the messages of a probe run to its chat and stops the run
115 // by the rules of probeStop.
116 type probeRun struct {
122 // Run appends the entries. It waits for the builds only before a user message,
123 // as a turn does, so up to maxBuilds builds run at once in between, and it
124 // waits for all builds at the end. It returns the number of messages appended
125 // and why the run stopped early, or "" when it did not. After a stop it waits
126 // for the calls in flight, so no sent call is cancelled.
127 func (r *probeRun) Run(ctx context.Context, entries []probeEntry) (int, string) {
128 appended, reason := r.append(ctx, entries)
133 err := r.memory.Wait(ctx)
135 reason += "; " + err.Error()
138 return appended, reason
141 // append appends the entries and stops at the first stop rule.
142 func (r *probeRun) append(ctx context.Context, entries []probeEntry) (int, string) {
143 for n, entry := range entries {
144 if entry.Kind == "user" {
145 reason := r.wait(ctx)
151 _, err := r.memory.Append(entry.Kind, entry.Text)
153 return n, err.Error()
162 return len(entries), r.wait(ctx)
165 // wait returns when no build runs, or when a stop rule ends the run. It checks
166 // the rules each second, so a run stops soon also during a long wait.
167 func (r *probeRun) wait(ctx context.Context) string {
174 waitCtx, cancel := context.WithTimeout(ctx, time.Second)
175 err := r.memory.Wait(waitCtx)
181 if ctx.Err() != nil {
182 return ctx.Err().Error()
187 // check returns why the run must stop, or "" when it can go on.
188 func (r *probeRun) check() string {
189 if r.client.LimitReached() {
190 return fmt.Sprintf("call limit of %d reached", r.client.limit)
193 records, err := readUsageFile(r.usagePath)
198 return probeStop(records)
201 // probeEntry is one message of a probe log.
202 type probeEntry struct {
203 Kind string `json:"kind"`
204 Text string `json:"text"`
207 // readProbeLog reads the first count messages of the probe log at path.
208 func readProbeLog(path string, count int) (entries []probeEntry, err error) {
209 file, err := os.Open(path)
211 return nil, fmt.Errorf("open probe log: %w", err)
215 err = errors.Join(err, file.Close())
218 scanner := bufio.NewScanner(file)
219 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
220 for len(entries) < count && scanner.Scan() {
222 err = json.Unmarshal(scanner.Bytes(), &entry)
224 return nil, fmt.Errorf("probe log line %d: %w", len(entries)+1, err)
227 entries = append(entries, entry)
232 return nil, fmt.Errorf("read probe log: %w", err)
235 if len(entries) < count {
236 return nil, fmt.Errorf("probe log has %d messages, fewer than %d", len(entries), count)
242 // probeStop returns why a probe run must stop: a failed call, or a quota window
243 // whose used percent grew by more than probeQuotaLimit points since the first
244 // call. It returns "" when the run can go on.
245 func probeStop(records []usageRecord) string {
246 for _, record := range records {
247 if record.Error != "" {
248 return "call failed: " + record.Error
252 if len(records) == 0 {
256 first := usedPercents(records[0])
257 for name, used := range usedPercents(records[len(records)-1]) {
258 start, found := first[name]
259 if found && used-start > probeQuotaLimit {
260 return fmt.Sprintf("%s grew from %g to %g", name, start, used)
267 // modelLines returns the sizes of the nodes that the model wrote, in tree
268 // order. A node that fits its source with no model call is not one of them.
269 func modelLines(memory *Memory) ([]int, error) {
271 defer memory.mutex.Unlock()
273 keys, err := memory.tree.Keys()
279 for _, key := range keys {
280 node, _, err := memory.tree.Node(key.level, key.index)
285 model, err := builtByModel(memory, key)
291 sizes = append(sizes, node.Size)
298 // builtByModel tells if the node key needed a model call: a leaf whose source
299 // is over nodeBytes, or a merge whose children do not fit in one node.
300 func builtByModel(memory *Memory, key nodeKey) (bool, error) {
302 message, err := memory.log.Message(key.index)
307 _, free := freeLeaf(message)
312 left, right, err := memory.children(key)
317 _, free := freeMerge(left, right)
322 // readUsageFile reads the records of usage.jsonl at path.
323 func readUsageFile(path string) (records []usageRecord, err error) {
324 file, err := os.Open(path)
325 if errors.Is(err, os.ErrNotExist) {
330 return nil, fmt.Errorf("open usage file: %w", err)
334 err = errors.Join(err, file.Close())
337 scanner := bufio.NewScanner(file)
338 scanner.Buffer(make([]byte, 64*1024), probeLineBytes)
340 var record usageRecord
341 err = json.Unmarshal(scanner.Bytes(), &record)
343 return nil, fmt.Errorf("decode usage: %w", err)
346 records = append(records, record)
351 return nil, fmt.Errorf("read usage file: %w", err)
357 // usedPercents returns the used percent of each quota window of record, by
359 func usedPercents(record usageRecord) map[string]float64 {
360 used := make(map[string]float64)
361 for name, value := range record.Quota {
362 if !strings.HasSuffix(name, "-used-percent") {
366 percent, err := strconv.ParseFloat(value, 64)
375 // writeProbeReport writes the result of a probe run.
376 func writeProbeReport(out io.Writer, appended int, stop string, records []usageRecord, sizes []int) error {
377 var input, cached, output, failed int
378 for _, record := range records {
379 input += record.InputTokens
380 cached += record.CachedTokens
381 output += record.OutputTokens
382 if record.Error != "" {
389 lines = append(lines, "stopped early: "+stop)
392 lines = append(lines,
393 fmt.Sprintf("messages: %d", appended),
394 fmt.Sprintf("calls: %d (%d failed), %.2f per message", len(records), failed, ratio(len(records), appended)),
395 fmt.Sprintf("model lines: %d, retries: %d, %.2f calls per model line", len(sizes), len(records)-failed-len(sizes), ratio(len(records), len(sizes))),
396 fmt.Sprintf("tokens: %d input, %d cached (%.1f%%), %d output", input, cached, 100*ratio(cached, input), output),
400 lines = append(lines, sizeText(sizes))
403 if len(records) > 0 {
404 lines = append(lines, timeText(records))
407 if len(records) > 0 {
408 lines = append(lines,
409 "quota at the first call: "+quotaText(records[0]),
410 "quota at the last call: "+quotaText(records[len(records)-1]),
414 _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
419 // sizeText describes the sizes of the model lines.
420 func sizeText(sizes []int) string {
421 sorted := slices.Sorted(slices.Values(sizes))
423 for _, size := range sorted {
425 if size > nodeBytes {
430 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)
433 // timeText describes the time per call and how many calls ran at once. A call
434 // runs from its date for its seconds.
435 func timeText(records []usageRecord) string {
442 seconds := make([]float64, 0, len(records))
444 for _, record := range records {
445 start, err := time.Parse(time.RFC3339Nano, record.Date)
450 length := time.Duration(record.Seconds * float64(time.Second))
451 events = append(events, event{
455 at: start.Add(length),
458 seconds = append(seconds, record.Seconds)
459 total += record.Seconds
462 if len(events) == 0 {
463 return "time: no dated calls"
466 slices.SortFunc(events, func(a, b event) int {
467 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
470 running, most := 0, 0
471 for _, e := range events {
473 most = max(most, running)
476 wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
479 return fmt.Sprintf("time: %.0f s in all, %.1f s per call (median %.1f, max %.1f), calls at once: at most %d, %.1f on average", wall, total/float64(len(seconds)), seconds[len(seconds)/2], seconds[len(seconds)-1], most, total/max(wall, 1e-9))
482 // quotaText returns the quota headers of record, sorted by name.
483 func quotaText(record usageRecord) string {
484 names := slices.Sorted(maps.Keys(record.Quota))
485 parts := make([]string, len(names))
486 for n, name := range names {
487 parts[n] = strings.TrimPrefix(name, "x-codex-") + "=" + record.Quota[name]
490 return strings.Join(parts, " ")
493 // ratio returns a / b, or 0 when b is 0.
494 func ratio(a, b int) float64 {
499 return float64(a) / float64(b)