]> git.giacomolli.uk - onechat/blob - memory.go
Wait for the send back line in the retry test
[onechat] / memory.go
1 package main
2
3 import (
4         "context"
5         "encoding/json"
6         "errors"
7         "fmt"
8         "log/slog"
9         "os"
10         "path/filepath"
11         "strings"
12         "sync"
13         "time"
14 )
15
16 var (
17         // errMemoryNoView tells that a chat has messages but no saved view.
18         errMemoryNoView = errors.New("the chat has messages but no saved view")
19
20         // errMemoryUnsettled tells that a line of the view stays pending,
21         // because its build failed.
22         errMemoryUnsettled = errors.New("a summary of the view failed, and it is tried again at the next message")
23 )
24
25 // openMemory opens the chat in root and starts the builds that are ready. The
26 // clock gives the dates of new messages and the days of new nodes. logger gets
27 // one line for each failed build. The builds stop when ctx ends or at Close.
28 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer, logger *slog.Logger) (*Memory, error) {
29         log, err := openLog(ctx, root, clock)
30         if err != nil {
31                 return nil, err
32         }
33
34         m := &Memory{
35                 root:       root,
36                 log:        log,
37                 queue:      newBuildQueue(),
38                 summarizer: summarizer,
39                 logger:     logger,
40                 changed:    make(chan struct{}),
41         }
42
43         m.ctx, m.cancel = context.WithCancel(ctx)
44
45         m.syncer, err = openSyncer(root)
46         if err != nil {
47                 return nil, errors.Join(err, m.Close())
48         }
49
50         m.tree, err = openTree(ctx, root, log.Len(), clock)
51         if err != nil {
52                 return nil, errors.Join(err, m.Close())
53         }
54
55         err = m.load()
56         if err != nil {
57                 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
58         }
59
60         err = m.restoreQueue()
61         if err != nil {
62                 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
63         }
64
65         err = m.catchUp()
66         if err != nil {
67                 return nil, errors.Join(err, m.Close())
68         }
69
70         m.mutex.Lock()
71         m.syncer.Written()
72         m.dispatch()
73         m.mutex.Unlock()
74
75         return m, nil
76 }
77
78 // Summarizer builds the text of one node with a model.
79 type Summarizer interface {
80         Summarize(ctx context.Context, task Task) (string, error)
81 }
82
83 // Memory is the memory of one chat: the message log, the summary tree, the chat
84 // view, the compaction view, and the queue of the builds. The compaction view
85 // is the chat view merged further, at the limits of 16 to 32 KB. It takes the
86 // same new lines, and it merges again in one batch when it is too large or when
87 // the chat view merges. So the compactions share its prefix in the prompt
88 // cache. It saves the views to view.json after each change and loads them at
89 // start. It never builds the views again from the log, because a new view
90 // differs from the live one and so loses the prompt cache.
91 //
92 // Each write goes to the operating system at once, and a syncer makes the
93 // writes durable by group commit in the background. Flush waits until the
94 // writes so far are durable.
95 //
96 // The summarizer builds the nodes in the queue in the background. The start
97 // reads the indexes once to fill the queue again. After that, only a new
98 // message or a new node adds work. Memory keeps the nodes of the views and the
99 // tasks of the running builds. It reads all other messages and nodes from their
100 // day files through the indexes.
101 type Memory struct {
102         mutex      sync.Mutex
103         root       string
104         log        *Log
105         syncer     *Syncer
106         tree       *Tree
107         chat       *View
108         cview      *View
109         queue      *BuildQueue
110         summarizer Summarizer
111         logger     *slog.Logger
112         ctx        context.Context
113         cancel     context.CancelFunc
114         workers    sync.WaitGroup
115         changed    chan struct{}
116 }
117
118 // Close stops the builds, waits for them, makes the writes durable, closes the
119 // files of the chat, and releases its lock.
120 func (m *Memory) Close() error {
121         m.cancel()
122         m.workers.Wait()
123
124         m.mutex.Lock()
125         defer m.mutex.Unlock()
126
127         var err error
128
129         if m.syncer != nil {
130                 err = m.syncer.Close()
131         }
132
133         if m.tree != nil {
134                 err = errors.Join(err, m.tree.Close())
135         }
136
137         return errors.Join(err, m.log.Close())
138 }
139
140 // Append logs a new message, adds it to the tree and the views, and starts the
141 // builds that are ready, also the failed ones.
142 func (m *Memory) Append(kind, text string) (Message, error) {
143         return m.AppendDated(kind, text, "")
144 }
145
146 // AppendDated appends a message with its RFC 3339 date and builds its nodes. An
147 // empty date uses the clock, as Append does.
148 func (m *Memory) AppendDated(kind, text, date string) (Message, error) {
149         m.mutex.Lock()
150         defer m.mutex.Unlock()
151
152         message, err := m.log.AppendDated(kind, text, date)
153         if err != nil {
154                 return Message{}, fmt.Errorf("append dated log message: %w", err)
155         }
156
157         defer m.syncer.Written()
158
159         err = m.addMessage(message)
160         if err != nil {
161                 return Message{}, fmt.Errorf("add dated message to memory: %w", err)
162         }
163
164         err = m.save()
165         if err != nil {
166                 return Message{}, fmt.Errorf("save dated message view: %w", err)
167         }
168
169         m.queue.Retry()
170         m.dispatch()
171
172         return message, nil
173 }
174
175 // children reads the two children of the node key.
176 func (m *Memory) children(key NodeKey) (Node, Node, error) {
177         var children [2]Node
178
179         for n := range children {
180                 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
181                 if err != nil {
182                         return Node{}, Node{}, err
183                 }
184
185                 if !built {
186                         return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
187                 }
188
189                 children[n] = child
190         }
191
192         return children[0], children[1], nil
193 }
194
195 // Wait returns when no build runs. The failed builds wait for the next message.
196 func (m *Memory) Wait(ctx context.Context) error {
197         for {
198                 m.mutex.Lock()
199
200                 running := m.queue.Running()
201                 changed := m.changed
202                 m.mutex.Unlock()
203
204                 if running == 0 {
205                         return nil
206                 }
207
208                 select {
209                 case <-changed:
210                 case <-ctx.Done():
211                         return ctx.Err()
212                 }
213         }
214 }
215
216 // Settle returns when the chat view has no pending line, so that every message
217 // so far is summarized. A pending line with no build that runs belongs to a
218 // failed build, which waits for the next message, so Settle returns
219 // errMemoryUnsettled in place of a wait that never ends.
220 func (m *Memory) Settle(ctx context.Context) error {
221         for {
222                 m.mutex.Lock()
223
224                 pending := m.chat.Pending()
225                 running := m.queue.Running()
226                 changed := m.changed
227                 m.mutex.Unlock()
228
229                 if !pending {
230                         return nil
231                 }
232
233                 if running == 0 {
234                         return errMemoryUnsettled
235                 }
236
237                 select {
238                 case <-changed:
239                 case <-ctx.Done():
240                         return ctx.Err()
241                 }
242         }
243 }
244
245 // Flush returns when every write before the call is durable.
246 func (m *Memory) Flush(ctx context.Context) error {
247         return m.syncer.Flush(ctx)
248 }
249
250 // Snapshot flushes all memory writes and runs snapshot while no append or
251 // summary write can change the log, indexes, tree, or views. snapshot must not
252 // call Memory.
253 func (m *Memory) Snapshot(ctx context.Context, snapshot func() error) error {
254         m.mutex.Lock()
255         defer m.mutex.Unlock()
256
257         err := m.Flush(ctx)
258         if err != nil {
259                 return fmt.Errorf("flush memory snapshot: %w", err)
260         }
261
262         err = snapshot()
263         if err != nil {
264                 return fmt.Errorf("copy memory snapshot: %w", err)
265         }
266
267         return nil
268 }
269
270 // ViewLines returns the lines of the chat view, each with its newline, without
271 // the leaf lines of the messages in skip.
272 func (m *Memory) ViewLines(skip map[int]bool) []string {
273         m.mutex.Lock()
274         defer m.mutex.Unlock()
275
276         return m.chat.LinesWithout(skip)
277 }
278
279 // Len returns the number of messages in the log.
280 func (m *Memory) Len() int {
281         m.mutex.Lock()
282         defer m.mutex.Unlock()
283
284         return m.log.Len()
285 }
286
287 // Message reads the message with the given ID.
288 func (m *Memory) Message(id int) (Message, error) {
289         m.mutex.Lock()
290         defer m.mutex.Unlock()
291
292         return m.log.Message(id)
293 }
294
295 // Node reads the node (l, i) if it is built.
296 func (m *Memory) Node(level, index int) (Node, bool, error) {
297         m.mutex.Lock()
298         defer m.mutex.Unlock()
299
300         return m.tree.Node(level, index)
301 }
302
303 // load reads the saved views.
304 func (m *Memory) load() error {
305         data, err := os.ReadFile(m.viewPath())
306         if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
307                 m.chat = newView(viewChatHigh, viewChatLow)
308                 m.cview = newView(viewCompactionHigh, viewCompactionLow)
309
310                 return nil
311         }
312
313         if errors.Is(err, os.ErrNotExist) {
314                 return errMemoryNoView
315         }
316
317         if err != nil {
318                 return fmt.Errorf("read view: %w", err)
319         }
320
321         var file MemoryViewFile
322
323         err = json.Unmarshal(data, &file)
324         if err != nil {
325                 return fmt.Errorf("decode view: %w", err)
326         }
327
328         m.chat, err = restoreView(file.Chat, viewChatHigh, viewChatLow, m.tree)
329         if err != nil {
330                 return fmt.Errorf("chat view: %w", err)
331         }
332
333         m.cview, err = restoreView(file.Compaction, viewCompactionHigh, viewCompactionLow, m.tree)
334         if err != nil {
335                 return fmt.Errorf("compaction view: %w", err)
336         }
337
338         if m.cview.end != m.chat.end {
339                 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
340         }
341
342         if m.chat.end > m.log.Len() {
343                 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
344         }
345
346         return nil
347 }
348
349 // restoreQueue adds the work of the messages in the view to the queue. It
350 // builds each node that needs no model call and that a crash left out.
351 func (m *Memory) restoreQueue() error {
352         for id := range m.chat.end {
353                 built, err := m.tree.Built(0, id)
354                 if err != nil {
355                         return err
356                 }
357
358                 if built {
359                         continue
360                 }
361
362                 message, err := m.log.Message(id)
363                 if err != nil {
364                         return err
365                 }
366
367                 leaf, free := freeLeaf(message)
368                 if !free {
369                         m.queue.AddLeaf(id)
370
371                         continue
372                 }
373
374                 err = m.build(leaf)
375                 if err != nil {
376                         return err
377                 }
378         }
379
380         keys, err := m.tree.Keys()
381         if err != nil {
382                 return err
383         }
384
385         for _, key := range keys {
386                 if key.index%2 != 0 {
387                         continue
388                 }
389
390                 err = m.settle(key)
391                 if err != nil {
392                         return err
393                 }
394         }
395
396         return nil
397 }
398
399 // catchUp adds the messages that the view does not cover yet. A crash can stop
400 // an append after the log write and before the view save.
401 func (m *Memory) catchUp() error {
402         if m.chat.end == m.log.Len() {
403                 return nil
404         }
405
406         for m.chat.end < m.log.Len() {
407                 message, err := m.log.Message(m.chat.end)
408                 if err != nil {
409                         return err
410                 }
411
412                 err = m.addMessage(message)
413                 if err != nil {
414                         return err
415                 }
416         }
417
418         return m.save()
419 }
420
421 // dispatch starts the builds that are ready, up to the limit. A build whose
422 // input cannot be read fails and waits for the next message.
423 func (m *Memory) dispatch() {
424         for m.ctx.Err() == nil {
425                 key, ready := m.queue.Next()
426                 if !ready {
427                         return
428                 }
429
430                 task, err := m.task(key)
431                 if err != nil {
432                         m.failed(key, fmt.Errorf("read its input: %w", err))
433                         m.queue.Fail(key)
434
435                         continue
436                 }
437
438                 m.workers.Add(1)
439
440                 go m.run(key, task)
441         }
442 }
443
444 // addMessage builds the leaf of message when it needs no model call, or else
445 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
446 // stop an append after the leaf build and before the view save, so a leaf that
447 // is built already stays as it is, and restoreQueue settles its parent.
448 func (m *Memory) addMessage(message Message) error {
449         built, err := m.tree.Built(0, message.ID)
450         if err != nil {
451                 return err
452         }
453
454         leaf, free := freeLeaf(message)
455         switch {
456         case built:
457         case free:
458                 err = m.build(leaf)
459                 if err != nil {
460                         return err
461                 }
462         default:
463                 m.queue.AddLeaf(message.ID)
464         }
465
466         merged, err := m.chat.Append(m.tree)
467         if err != nil {
468                 return fmt.Errorf("append to chat view: %w", err)
469         }
470
471         _, err = m.cview.Append(m.tree)
472         if err == nil && merged {
473                 err = m.cview.Coarsen(m.chat, m.tree)
474         }
475
476         if err != nil {
477                 return fmt.Errorf("append to compaction view: %w", err)
478         }
479
480         return nil
481 }
482
483 // save writes the views to view.json.
484 func (m *Memory) save() error {
485         data, err := json.Marshal(MemoryViewFile{
486                 Chat:       m.chat.State(),
487                 Compaction: m.cview.State(),
488         })
489         if err != nil {
490                 return fmt.Errorf("encode view: %w", err)
491         }
492
493         err = writeFileAtomic(m.viewPath(), append(data, '\n'))
494         if err != nil {
495                 return fmt.Errorf("save view: %w", err)
496         }
497
498         return nil
499 }
500
501 func (m *Memory) viewPath() string {
502         return filepath.Join(m.root, "view.json")
503 }
504
505 // build adds node to the tree, keeps it in the views when it is a pending line,
506 // and settles its parent.
507 func (m *Memory) build(node Node) error {
508         err := m.tree.Add(node)
509         if err != nil {
510                 return err
511         }
512
513         m.chat.Refresh(node)
514         m.cview.Refresh(node)
515
516         return m.settle(NodeKey{node.Level, node.Index})
517 }
518
519 // settle looks at the parent of the built node key when both children are
520 // built. It builds each parent that needs no model call, up the tree, and adds
521 // the first other parent to the queue.
522 func (m *Memory) settle(key NodeKey) error {
523         for {
524                 parent := NodeKey{key.level + 1, key.index / 2}
525                 ready, err := m.ready(parent)
526                 if err != nil || !ready {
527                         return err
528                 }
529
530                 left, right, err := m.children(parent)
531                 if err != nil {
532                         return err
533                 }
534
535                 node, free := freeMerge(left, right)
536                 if !free {
537                         m.queue.AddMerge(parent)
538
539                         return nil
540                 }
541
542                 err = m.tree.Add(node)
543                 if err != nil {
544                         return err
545                 }
546
547                 key = parent
548         }
549 }
550
551 // task returns the build task of the node key, with its input read from the log
552 // or the tree.
553 func (m *Memory) task(key NodeKey) (Task, error) {
554         task := Task{
555                 Level:   key.level,
556                 Index:   key.index,
557                 Context: m.context(key.level, key.index),
558         }
559
560         if key.level == 0 {
561                 message, err := m.log.Message(key.index)
562                 if err != nil {
563                         return Task{}, err
564                 }
565
566                 task.Input = []string{leafSource(message)}
567
568                 return task, nil
569         }
570
571         left, right, err := m.children(key)
572         if err != nil {
573                 return Task{}, err
574         }
575
576         for _, child := range []Node{left, right} {
577                 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
578         }
579
580         return task, nil
581 }
582
583 // run builds one node with the summarizer. A failed build stays in the queue
584 // until the next message.
585 func (m *Memory) run(key NodeKey, task Task) {
586         defer m.workers.Done()
587
588         text, err := m.summarizer.Summarize(m.ctx, task)
589
590         m.mutex.Lock()
591         defer m.mutex.Unlock()
592
593         if err == nil {
594                 err = m.build(Node{
595                         Level: key.level,
596                         Index: key.index,
597                         Text:  text,
598                         Size:  len(text),
599                 })
600                 m.syncer.Written()
601         }
602
603         if err != nil && m.ctx.Err() == nil {
604                 m.failed(key, err)
605         }
606
607         if err != nil {
608                 m.queue.Fail(key)
609         } else {
610                 m.queue.Done(key)
611         }
612
613         close(m.changed)
614
615         m.changed = make(chan struct{})
616         m.dispatch()
617 }
618
619 // failed logs the failed build of the node key with its cause err.
620 func (m *Memory) failed(key NodeKey, err error) {
621         m.logger.Warn("summary failed", "level", key.level, "index", key.index, "err", err)
622 }
623
624 // ready tells if both children of the node key are built and the node is not.
625 func (m *Memory) ready(key NodeKey) (bool, error) {
626         for _, index := range []int{2 * key.index, 2*key.index + 1} {
627                 built, err := m.tree.Built(key.level-1, index)
628                 if err != nil || !built {
629                         return false, err
630                 }
631         }
632
633         built, err := m.tree.Built(key.level, key.index)
634
635         return !built, err
636 }
637
638 func (m *Memory) context(level, index int) string {
639         end := index
640         if level > 0 {
641                 end = nodeEnd(level, index)
642         }
643
644         return m.cview.Context(end)
645 }
646
647 // View returns the chat view as the model reads it.
648 func (m *Memory) View() string {
649         m.mutex.Lock()
650         defer m.mutex.Unlock()
651
652         return m.chat.Render()
653 }
654
655 // Context returns the compaction view for the build of node (l, i). It ends
656 // before the message of a leaf, or after the last message of a merge, and it
657 // stops at the first line that is not built.
658 func (m *Memory) Context(level, index int) string {
659         m.mutex.Lock()
660         defer m.mutex.Unlock()
661
662         return m.context(level, index)
663 }
664
665 // rebuildComplete checks the whole tree, not only the visible view. A compactor
666 // can fail without an HTTP error, for example with an empty line. Such a failed
667 // merge can be absent from the view and must prevent a swap.
668 func (m *Memory) rebuildComplete() error {
669         m.mutex.Lock()
670         defer m.mutex.Unlock()
671
672         if len(m.queue.leaves) != 0 || len(m.queue.queued) != 0 {
673                 return errors.New("rebuild failed: summary tree has unfinished nodes")
674         }
675
676         return nil
677 }
678
679 // buildModelLines returns the sizes of the nodes that the model wrote, in tree
680 // order. A node that fits its source with no model call is not one of them.
681 func (m *Memory) buildModelLines() ([]int, error) {
682         m.mutex.Lock()
683         defer m.mutex.Unlock()
684
685         keys, err := m.tree.Keys()
686         if err != nil {
687                 return nil, fmt.Errorf("list built nodes: %w", err)
688         }
689
690         var sizes []int
691
692         for _, key := range keys {
693                 var node Node
694
695                 node, _, err = m.tree.Node(key.level, key.index)
696                 if err != nil {
697                         return nil, fmt.Errorf("read built node: %w", err)
698                 }
699
700                 var model bool
701
702                 model, err = m.buildBuiltByModel(key)
703                 if err != nil {
704                         return nil, fmt.Errorf("check model source: %w", err)
705                 }
706
707                 if model {
708                         sizes = append(sizes, node.Size)
709                 }
710         }
711
712         return sizes, nil
713 }
714
715 // buildBuiltByModel tells if the node key needed a model call: a leaf whose
716 // source is over nodeBytes, or a merge whose children do not fit in one node.
717 func (m *Memory) buildBuiltByModel(key NodeKey) (bool, error) {
718         if key.level == 0 {
719                 message, err := m.log.Message(key.index)
720                 if err != nil {
721                         return false, fmt.Errorf("read leaf source: %w", err)
722                 }
723
724                 _, free := freeLeaf(message)
725
726                 return !free, nil
727         }
728
729         left, right, err := m.children(key)
730         if err != nil {
731                 return false, fmt.Errorf("read merge sources: %w", err)
732         }
733
734         _, free := freeMerge(left, right)
735
736         return !free, nil
737 }
738
739 // Task is the build of the node (Level, Index). Context is the compaction view
740 // for the build. Input holds the source "kind: text" of a leaf, or the two
741 // child lines of a merge with their newlines as spaces.
742 type Task struct {
743         Level   int
744         Index   int
745         Context string
746         Input   []string
747 }
748
749 // MemoryViewFile is the content of view.json.
750 type MemoryViewFile struct {
751         Chat       ViewState `json:"chat"`
752         Compaction ViewState `json:"compaction"`
753 }