]> git.giacomolli.uk - onechat/blob - probe.go
Write private data archives with safe extraction
[onechat] / probe.go
1 package main
2
3 import (
4         "bufio"
5         "context"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "io"
10         "log/slog"
11         "os"
12         "path/filepath"
13         "strconv"
14         "time"
15 )
16
17 const (
18         // probeName is the agent name of a probe run. The cache key comes from
19         // it.
20         probeName = "Probe"
21
22         // probeCallLimit is the most model calls of a probe run.
23         probeCallLimit = 660
24 )
25
26 // probe runs "onechat probe LOG COUNT [BUILDS]". It appends the first COUNT
27 // messages of LOG, one JSON object {kind, text} per line, to a new chat in
28 // probe/ in the data directory, and builds its tree with the real compactor.
29 // Before each user message it waits for the builds, as a turn does. It stops at
30 // the first failed call, after probeCallLimit calls, or when the used percent
31 // of a quota window grows by more than buildQuotaLimit points. At the end it
32 // reports the calls, the time per call, the calls at once, the cached share,
33 // the quota, the retries, and the line sizes. BUILDS, from 1 to buildMax,
34 // limits the builds that call the model at once in this run only. The core
35 // still queues up to buildMax builds. The run holds the lock of the token file,
36 // so it does not run while the daemon runs.
37 func probe(ctx context.Context, args []string, out io.Writer) (err error) {
38         if len(args) != 2 && len(args) != 3 {
39                 return errors.New("usage: onechat probe LOG COUNT [BUILDS]")
40         }
41
42         count, err := strconv.Atoi(args[1])
43         if err != nil {
44                 return fmt.Errorf("parse probe count: %w", err)
45         }
46
47         if count <= 0 {
48                 return fmt.Errorf("COUNT %q is not a positive number", args[1])
49         }
50
51         builds := buildMax
52         if len(args) == 3 {
53                 builds, err = strconv.Atoi(args[2])
54                 if err != nil {
55                         return fmt.Errorf("parse probe builds: %w", err)
56                 }
57
58                 if builds < 1 || builds > buildMax {
59                         return fmt.Errorf("BUILDS %q is not a number from 1 to %d", args[2], buildMax)
60                 }
61         }
62
63         entries, err := probeReadLog(args[0], count)
64         if err != nil {
65                 return fmt.Errorf("read probe input: %w", err)
66         }
67
68         dir, err := dataDir()
69         if err != nil {
70                 return fmt.Errorf("find probe data directory: %w", err)
71         }
72
73         config, err := loadConfig(dir)
74         if err != nil {
75                 return fmt.Errorf("load probe configuration: %w", err)
76         }
77
78         tokens, err := lockTokens(dir)
79         if err != nil {
80                 return fmt.Errorf("lock probe tokens: %w", err)
81         }
82
83         defer func() {
84                 closeErr := tokens.Close()
85                 if closeErr != nil {
86                         err = errors.Join(err, fmt.Errorf("close probe token lock: %w", closeErr))
87                 }
88         }()
89
90         address, auth, err := modelEndpoint(config, dir)
91         if err != nil {
92                 return fmt.Errorf("select probe endpoint: %w", err)
93         }
94
95         root := filepath.Join(dir, "probe", time.Now().Format("20060102-150405"))
96         err = os.MkdirAll(root, 0o700)
97         if err != nil {
98                 return fmt.Errorf("create probe directory: %w", err)
99         }
100
101         usagePath := filepath.Join(root, "usage.jsonl")
102         client := newModelClient(address, auth, "onechat-"+probeName, usagePath)
103         client.LimitCalls(probeCallLimit)
104
105         summarizer := ProbeSlotSummarizer{
106                 inner: newCompactor(client, probePrompt, config.Compactor),
107                 slots: make(chan struct{}, builds),
108         }
109
110         // The report of the probe counts the failed calls, so the lines of the
111         // failed builds are not needed.
112         memory, err := openMemory(ctx, root, time.Now, summarizer, slog.New(slog.DiscardHandler))
113         if err != nil {
114                 return fmt.Errorf("open probe memory: %w", err)
115         }
116
117         _, 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)
118         if err != nil {
119                 return fmt.Errorf("write probe header: %w", errors.Join(err, memory.Close()))
120         }
121
122         run := BuildRun{
123                 memory:    memory,
124                 client:    client,
125                 usagePath: usagePath,
126         }
127
128         appended, stop := run.Run(ctx, entries)
129         sizes, err := memory.buildModelLines()
130         err = errors.Join(err, memory.Close())
131         if err != nil {
132                 return fmt.Errorf("finish probe memory: %w", err)
133         }
134
135         records, err := buildReadUsage(usagePath)
136         if err != nil {
137                 return fmt.Errorf("read probe usage: %w", err)
138         }
139
140         err = buildWriteReport(out, appended, stop, records, sizes)
141         if err != nil {
142                 return fmt.Errorf("write probe report: %w", err)
143         }
144
145         return nil
146 }
147
148 // ProbeSlotSummarizer lets at most cap(slots) builds call inner at once. A
149 // build past the limit waits for a slot.
150 type ProbeSlotSummarizer struct {
151         inner Summarizer
152         slots chan struct{}
153 }
154
155 // Summarize waits for a slot and builds the node with inner.
156 func (s ProbeSlotSummarizer) Summarize(ctx context.Context, task Task) (string, error) {
157         select {
158         case s.slots <- struct{}{}:
159         case <-ctx.Done():
160                 return "", ctx.Err()
161         }
162
163         defer func() {
164                 <-s.slots
165         }()
166
167         return s.inner.Summarize(ctx, task)
168 }
169
170 // probeReadLog reads the first count messages of the probe log at path. Source
171 // dates are ignored because a probe uses its own clock.
172 func probeReadLog(path string, count int) (entries []DatedMessage, err error) {
173         file, err := os.Open(path)
174         if err != nil {
175                 return nil, fmt.Errorf("open probe log: %w", err)
176         }
177
178         defer func() {
179                 closeErr := file.Close()
180                 if closeErr != nil {
181                         err = errors.Join(err, fmt.Errorf("close probe log: %w", closeErr))
182                 }
183         }()
184
185         scanner := bufio.NewScanner(file)
186         scanner.Buffer(make([]byte, 64*1024), buildLineBytes)
187
188         for len(entries) < count && scanner.Scan() {
189                 var entry DatedMessage
190
191                 err = json.Unmarshal(scanner.Bytes(), &entry)
192                 if err != nil {
193                         return nil, fmt.Errorf("probe log line %d: %w", len(entries)+1, err)
194                 }
195
196                 entry.Date = ""
197                 entries = append(entries, entry)
198         }
199
200         err = scanner.Err()
201         if err != nil {
202                 return nil, fmt.Errorf("read probe log: %w", err)
203         }
204
205         if len(entries) < count {
206                 return nil, fmt.Errorf("probe log has %d messages, fewer than %d", len(entries), count)
207         }
208
209         return entries, nil
210 }
211
212 // probePrompt returns the system prompt of a probe run: the prompt of the agent
213 // probeName, without instructions and with a fixed instructions file path.
214 func probePrompt() (string, error) {
215         return prompt(probeName, "/PROBE/instructions.md", ""), nil
216 }