19 // buildLineBytes is the most bytes of one line in a build input or usage log.
20 const buildLineBytes = 1 << 20
22 // buildQuotaLimit is the largest increase in used quota points of a run.
23 const buildQuotaLimit = 15.0
25 // BuildRun appends messages, builds their tree, and stops the run by the rules
27 type BuildRun struct {
33 // Run appends the entries. It waits for the builds only before a user message,
34 // as a turn does, so up to buildMax builds run at once in between, and it waits
35 // for all builds at the end. It returns the number of messages appended and why
36 // the run stopped early, or "" when it did not. After a stop it waits for the
37 // calls in flight, so no sent call is cancelled.
38 func (r *BuildRun) Run(ctx context.Context, entries []DatedMessage) (int, string) {
39 appended, reason := r.append(ctx, entries)
44 err := r.memory.Wait(ctx)
46 reason += "; " + err.Error()
49 return appended, reason
52 // append appends the entries and stops at the first stop rule.
53 func (r *BuildRun) append(ctx context.Context, entries []DatedMessage) (int, string) {
54 for n, entry := range entries {
55 if entry.Kind == "user" {
63 return n, ctx.Err().Error()
66 _, err := r.memory.AppendDated(entry.Kind, entry.Text, entry.Date)
77 return len(entries), r.wait(ctx)
80 // wait returns when no build runs, or when a stop rule ends the run. It checks
81 // the rules each second, so a run stops soon also during a long wait.
82 func (r *BuildRun) wait(ctx context.Context) string {
89 err := r.waitBuilds(ctx)
95 return ctx.Err().Error()
100 // check returns why the run must stop, or "" when it can go on.
101 func (r *BuildRun) check() string {
102 if r.client.LimitReached() {
103 return fmt.Sprintf("call limit of %d reached", r.client.CallLimit())
106 records, err := buildReadUsage(r.usagePath)
111 return buildStop(records)
114 // waitBuilds waits up to one second without leaving a child context open.
115 func (r *BuildRun) waitBuilds(ctx context.Context) error {
116 ctx, cancel := context.WithTimeout(ctx, time.Second)
119 return r.memory.Wait(ctx)
122 // DatedMessage is one message with an optional RFC 3339 date.
123 type DatedMessage struct {
124 Kind string `json:"kind"`
125 Text string `json:"text"`
126 Date string `json:"date,omitempty"`
129 // buildReadUsage reads the records of usage.jsonl at path, in the order of the
130 // start of their calls. The file has them in the order of the end of their
131 // calls, which differs when calls run at once.
132 func buildReadUsage(path string) (records []ModelUsageRecord, err error) {
133 file, err := os.Open(path)
134 if errors.Is(err, os.ErrNotExist) {
139 return nil, fmt.Errorf("open usage file: %w", err)
143 closeErr := file.Close()
145 err = errors.Join(err, fmt.Errorf("close build usage: %w", closeErr))
149 scanner := bufio.NewScanner(file)
150 scanner.Buffer(make([]byte, 64*1024), buildLineBytes)
153 var record ModelUsageRecord
155 err = json.Unmarshal(scanner.Bytes(), &record)
157 return nil, fmt.Errorf("decode usage: %w", err)
160 records = append(records, record)
165 return nil, fmt.Errorf("read usage file: %w", err)
168 slices.SortStableFunc(records, func(a, b ModelUsageRecord) int {
169 return buildCallStart(a).Compare(buildCallStart(b))
175 // buildWriteReport writes the result of a build run.
176 func buildWriteReport(out io.Writer, appended int, stop string, records []ModelUsageRecord, sizes []int) error {
177 var input, cached, output, failed int
179 for _, record := range records {
180 input += record.InputTokens
181 cached += record.CachedTokens
182 output += record.OutputTokens
183 if record.Error != "" {
191 lines = append(lines, "stopped early: "+stop)
194 lines = append(lines,
195 fmt.Sprintf("messages: %d", appended),
196 fmt.Sprintf("calls: %d (%d failed), %.2f per message", len(records), failed, buildRatio(len(records), appended)),
197 fmt.Sprintf("model lines: %d, retries: %d, %.2f calls per model line", len(sizes), len(records)-failed-len(sizes), buildRatio(len(records), len(sizes))),
198 fmt.Sprintf("tokens: %d input, %d cached (%.1f%%), %d output", input, cached, 100*buildRatio(cached, input), output),
202 lines = append(lines, buildSizeText(sizes))
205 if len(records) > 0 {
206 lines = append(lines, buildTimeText(records))
209 if len(records) > 0 {
210 lines = append(lines,
211 "quota at the first call: "+buildQuotaText(records[0]),
212 "quota at the last call: "+buildQuotaText(records[len(records)-1]),
216 _, err := io.WriteString(out, strings.Join(lines, "\n")+"\n")
218 return fmt.Errorf("write build report: %w", err)
224 // buildStop returns why a build run must stop: a failed call, or a quota window
225 // whose used percent grew by more than buildQuotaLimit points since the first
226 // call. It returns "" when the run can go on.
227 func buildStop(records []ModelUsageRecord) string {
228 for _, record := range records {
229 if record.Error != "" {
230 return "call failed: " + record.Error
234 if len(records) == 0 {
238 first := buildUsedPercents(records[0])
239 for name, used := range buildUsedPercents(records[len(records)-1]) {
240 start, found := first[name]
241 if found && used-start > buildQuotaLimit {
242 return fmt.Sprintf("%s grew from %g to %g", name, start, used)
249 // buildCallStart returns the start of the call of record, or the zero time when
250 // its date is not valid.
251 func buildCallStart(record ModelUsageRecord) time.Time {
252 start, err := time.Parse(time.RFC3339Nano, record.Date)
260 // buildRatio returns a / b, or 0 when b is 0.
261 func buildRatio(a, b int) float64 {
266 return float64(a) / float64(b)
269 // buildSizeText describes the sizes of the model lines.
270 func buildSizeText(sizes []int) string {
271 sorted := slices.Sorted(slices.Values(sizes))
273 for _, size := range sorted {
275 if size > nodeBytes {
280 return fmt.Sprintf("line bytes: min %d, median %d, mean %.0f, max %d, %d over %d", sorted[0], sorted[len(sorted)/2], buildRatio(total, len(sorted)), sorted[len(sorted)-1], over, nodeBytes)
283 // buildTimeText describes the time per call and how many calls ran at once. A
284 // call runs from its date for its seconds.
285 func buildTimeText(records []ModelUsageRecord) string {
293 seconds := make([]float64, 0, len(records))
295 for _, record := range records {
296 start, err := time.Parse(time.RFC3339Nano, record.Date)
301 length := time.Duration(record.Seconds * float64(time.Second))
302 events = append(events, event{
306 at: start.Add(length),
310 seconds = append(seconds, record.Seconds)
311 total += record.Seconds
314 if len(events) == 0 {
315 return "time: no dated calls"
318 slices.SortFunc(events, func(a, b event) int {
319 return cmp.Or(a.at.Compare(b.at), cmp.Compare(a.delta, b.delta))
322 running, most := 0, 0
323 for _, e := range events {
325 most = max(most, running)
328 wall := events[len(events)-1].at.Sub(events[0].at).Seconds()
332 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))
335 // buildQuotaText returns the quota headers of record, sorted by name.
336 func buildQuotaText(record ModelUsageRecord) string {
337 names := slices.Sorted(maps.Keys(record.Quota))
338 parts := make([]string, len(names))
339 for n, name := range names {
340 parts[n] = strings.TrimPrefix(name, "x-codex-") + "=" + record.Quota[name]
343 return strings.Join(parts, " ")
346 // buildUsedPercents returns the used percent of each quota window of record, by
348 func buildUsedPercents(record ModelUsageRecord) map[string]float64 {
349 used := make(map[string]float64)
350 for name, value := range record.Quota {
351 if !strings.HasSuffix(name, "-used-percent") {
355 percent, err := strconv.ParseFloat(value, 64)