]> git.giacomolli.uk - onechat/blob - memory.go
Check test assertions with testifylint
[onechat] / memory.go
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "log"
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 *log.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 *log.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 if m.syncer != nil {
129 err = m.syncer.Close()
130 }
131
132 if m.tree != nil {
133 err = errors.Join(err, m.tree.Close())
134 }
135
136 return errors.Join(err, m.log.Close())
137 }
138
139 // Append logs a new message, adds it to the tree and the views, and starts the
140 // builds that are ready, also the failed ones.
141 func (m *Memory) Append(kind, text string) (Message, error) {
142 return m.AppendDated(kind, text, "")
143 }
144
145 // AppendDated appends a message with its RFC 3339 date and builds its nodes. An
146 // empty date uses the clock, as Append does.
147 func (m *Memory) AppendDated(kind, text, date string) (Message, error) {
148 m.mutex.Lock()
149 defer m.mutex.Unlock()
150
151 message, err := m.log.AppendDated(kind, text, date)
152 if err != nil {
153 return Message{}, fmt.Errorf("append dated log message: %w", err)
154 }
155
156 defer m.syncer.Written()
157
158 err = m.addMessage(message)
159 if err != nil {
160 return Message{}, fmt.Errorf("add dated message to memory: %w", err)
161 }
162
163 err = m.save()
164 if err != nil {
165 return Message{}, fmt.Errorf("save dated message view: %w", err)
166 }
167
168 m.queue.Retry()
169 m.dispatch()
170
171 return message, nil
172 }
173
174 // children reads the two children of the node key.
175 func (m *Memory) children(key NodeKey) (Node, Node, error) {
176 var children [2]Node
177 for n := range children {
178 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
179 if err != nil {
180 return Node{}, Node{}, err
181 }
182
183 if !built {
184 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
185 }
186
187 children[n] = child
188 }
189
190 return children[0], children[1], nil
191 }
192
193 // Wait returns when no build runs. The failed builds wait for the next message.
194 func (m *Memory) Wait(ctx context.Context) error {
195 for {
196 m.mutex.Lock()
197 running := m.queue.Running()
198 changed := m.changed
199 m.mutex.Unlock()
200
201 if running == 0 {
202 return nil
203 }
204
205 select {
206 case <-changed:
207 case <-ctx.Done():
208 return ctx.Err()
209 }
210 }
211 }
212
213 // Settle returns when the chat view has no pending line, so that every message
214 // so far is summarized. A pending line with no build that runs belongs to a
215 // failed build, which waits for the next message, so Settle returns
216 // errMemoryUnsettled in place of a wait that never ends.
217 func (m *Memory) Settle(ctx context.Context) error {
218 for {
219 m.mutex.Lock()
220 pending := m.chat.Pending()
221 running := m.queue.Running()
222 changed := m.changed
223 m.mutex.Unlock()
224
225 if !pending {
226 return nil
227 }
228
229 if running == 0 {
230 return errMemoryUnsettled
231 }
232
233 select {
234 case <-changed:
235 case <-ctx.Done():
236 return ctx.Err()
237 }
238 }
239 }
240
241 // Flush returns when every write before the call is durable.
242 func (m *Memory) Flush(ctx context.Context) error {
243 return m.syncer.Flush(ctx)
244 }
245
246 // ViewLines returns the lines of the chat view, each with its newline, without
247 // the leaf lines of the messages in skip.
248 func (m *Memory) ViewLines(skip map[int]bool) []string {
249 m.mutex.Lock()
250 defer m.mutex.Unlock()
251
252 return m.chat.LinesWithout(skip)
253 }
254
255 // Len returns the number of messages in the log.
256 func (m *Memory) Len() int {
257 m.mutex.Lock()
258 defer m.mutex.Unlock()
259
260 return m.log.Len()
261 }
262
263 // Message reads the message with the given ID.
264 func (m *Memory) Message(id int) (Message, error) {
265 m.mutex.Lock()
266 defer m.mutex.Unlock()
267
268 return m.log.Message(id)
269 }
270
271 // Node reads the node (l, i) if it is built.
272 func (m *Memory) Node(level, index int) (Node, bool, error) {
273 m.mutex.Lock()
274 defer m.mutex.Unlock()
275
276 return m.tree.Node(level, index)
277 }
278
279 // load reads the saved views.
280 func (m *Memory) load() error {
281 data, err := os.ReadFile(m.viewPath())
282 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
283 m.chat = newView(viewChatHigh, viewChatLow)
284 m.cview = newView(viewCompactionHigh, viewCompactionLow)
285
286 return nil
287 }
288
289 if errors.Is(err, os.ErrNotExist) {
290 return errMemoryNoView
291 }
292
293 if err != nil {
294 return fmt.Errorf("read view: %w", err)
295 }
296
297 var file MemoryViewFile
298 err = json.Unmarshal(data, &file)
299 if err != nil {
300 return fmt.Errorf("decode view: %w", err)
301 }
302
303 m.chat, err = restoreView(file.Chat, viewChatHigh, viewChatLow, m.tree)
304 if err != nil {
305 return fmt.Errorf("chat view: %w", err)
306 }
307
308 m.cview, err = restoreView(file.Compaction, viewCompactionHigh, viewCompactionLow, m.tree)
309 if err != nil {
310 return fmt.Errorf("compaction view: %w", err)
311 }
312
313 if m.cview.end != m.chat.end {
314 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
315 }
316
317 if m.chat.end > m.log.Len() {
318 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
319 }
320
321 return nil
322 }
323
324 // restoreQueue adds the work of the messages in the view to the queue. It
325 // builds each node that needs no model call and that a crash left out.
326 func (m *Memory) restoreQueue() error {
327 for id := range m.chat.end {
328 built, err := m.tree.Built(0, id)
329 if err != nil {
330 return err
331 }
332
333 if built {
334 continue
335 }
336
337 message, err := m.log.Message(id)
338 if err != nil {
339 return err
340 }
341
342 leaf, free := freeLeaf(message)
343 if !free {
344 m.queue.AddLeaf(id)
345 continue
346 }
347
348 err = m.build(leaf)
349 if err != nil {
350 return err
351 }
352 }
353
354 keys, err := m.tree.Keys()
355 if err != nil {
356 return err
357 }
358
359 for _, key := range keys {
360 if key.index%2 != 0 {
361 continue
362 }
363
364 err = m.settle(key)
365 if err != nil {
366 return err
367 }
368 }
369
370 return nil
371 }
372
373 // catchUp adds the messages that the view does not cover yet. A crash can stop
374 // an append after the log write and before the view save.
375 func (m *Memory) catchUp() error {
376 if m.chat.end == m.log.Len() {
377 return nil
378 }
379
380 for m.chat.end < m.log.Len() {
381 message, err := m.log.Message(m.chat.end)
382 if err != nil {
383 return err
384 }
385
386 err = m.addMessage(message)
387 if err != nil {
388 return err
389 }
390 }
391
392 return m.save()
393 }
394
395 // dispatch starts the builds that are ready, up to the limit. A build whose
396 // input cannot be read fails and waits for the next message.
397 func (m *Memory) dispatch() {
398 for m.ctx.Err() == nil {
399 key, ready := m.queue.Next()
400 if !ready {
401 return
402 }
403
404 task, err := m.task(key)
405 if err != nil {
406 m.failed(key, fmt.Errorf("read its input: %w", err))
407 m.queue.Fail(key)
408
409 continue
410 }
411
412 m.workers.Add(1)
413 go m.run(key, task)
414 }
415 }
416
417 // addMessage builds the leaf of message when it needs no model call, or else
418 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
419 // stop an append after the leaf build and before the view save, so a leaf that
420 // is built already stays as it is, and restoreQueue settles its parent.
421 func (m *Memory) addMessage(message Message) error {
422 built, err := m.tree.Built(0, message.ID)
423 if err != nil {
424 return err
425 }
426
427 leaf, free := freeLeaf(message)
428 switch {
429 case built:
430 case free:
431 err = m.build(leaf)
432 if err != nil {
433 return err
434 }
435 default:
436 m.queue.AddLeaf(message.ID)
437 }
438
439 merged, err := m.chat.Append(m.tree)
440 if err != nil {
441 return fmt.Errorf("append to chat view: %w", err)
442 }
443
444 _, err = m.cview.Append(m.tree)
445 if err == nil && merged {
446 err = m.cview.Coarsen(m.chat, m.tree)
447 }
448
449 if err != nil {
450 return fmt.Errorf("append to compaction view: %w", err)
451 }
452
453 return nil
454 }
455
456 // save writes the views to view.json.
457 func (m *Memory) save() error {
458 data, err := json.Marshal(MemoryViewFile{
459 Chat: m.chat.State(),
460 Compaction: m.cview.State(),
461 })
462 if err != nil {
463 return fmt.Errorf("encode view: %w", err)
464 }
465
466 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
467 if err != nil {
468 return fmt.Errorf("save view: %w", err)
469 }
470
471 return nil
472 }
473
474 func (m *Memory) viewPath() string {
475 return filepath.Join(m.root, "view.json")
476 }
477
478 // build adds node to the tree, keeps it in the views when it is a pending line,
479 // and settles its parent.
480 func (m *Memory) build(node Node) error {
481 err := m.tree.Add(node)
482 if err != nil {
483 return err
484 }
485
486 m.chat.Refresh(node)
487 m.cview.Refresh(node)
488
489 return m.settle(NodeKey{node.Level, node.Index})
490 }
491
492 // settle looks at the parent of the built node key when both children are
493 // built. It builds each parent that needs no model call, up the tree, and adds
494 // the first other parent to the queue.
495 func (m *Memory) settle(key NodeKey) error {
496 for {
497 parent := NodeKey{key.level + 1, key.index / 2}
498 ready, err := m.ready(parent)
499 if err != nil || !ready {
500 return err
501 }
502
503 left, right, err := m.children(parent)
504 if err != nil {
505 return err
506 }
507
508 node, free := freeMerge(left, right)
509 if !free {
510 m.queue.AddMerge(parent)
511 return nil
512 }
513
514 err = m.tree.Add(node)
515 if err != nil {
516 return err
517 }
518
519 key = parent
520 }
521 }
522
523 // task returns the build task of the node key, with its input read from the log
524 // or the tree.
525 func (m *Memory) task(key NodeKey) (Task, error) {
526 task := Task{
527 Level: key.level,
528 Index: key.index,
529 Context: m.context(key.level, key.index),
530 }
531
532 if key.level == 0 {
533 message, err := m.log.Message(key.index)
534 if err != nil {
535 return Task{}, err
536 }
537
538 task.Input = []string{leafSource(message)}
539
540 return task, nil
541 }
542
543 left, right, err := m.children(key)
544 if err != nil {
545 return Task{}, err
546 }
547
548 for _, child := range []Node{left, right} {
549 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
550 }
551
552 return task, nil
553 }
554
555 // run builds one node with the summarizer. A failed build stays in the queue
556 // until the next message.
557 func (m *Memory) run(key NodeKey, task Task) {
558 defer m.workers.Done()
559
560 text, err := m.summarizer.Summarize(m.ctx, task)
561
562 m.mutex.Lock()
563 defer m.mutex.Unlock()
564
565 if err == nil {
566 err = m.build(Node{
567 Level: key.level,
568 Index: key.index,
569 Text: text,
570 Size: len(text),
571 })
572 m.syncer.Written()
573 }
574
575 if err != nil && m.ctx.Err() == nil {
576 m.failed(key, err)
577 }
578
579 if err != nil {
580 m.queue.Fail(key)
581 } else {
582 m.queue.Done(key)
583 }
584
585 close(m.changed)
586 m.changed = make(chan struct{})
587 m.dispatch()
588 }
589
590 // failed logs the failed build of the node key with its cause err.
591 func (m *Memory) failed(key NodeKey, err error) {
592 m.logger.Printf("summary failed, retry at next message: node (%d, %d): %v", key.level, key.index, err)
593 }
594
595 // ready tells if both children of the node key are built and the node is not.
596 func (m *Memory) ready(key NodeKey) (bool, error) {
597 for _, index := range []int{2 * key.index, 2*key.index + 1} {
598 built, err := m.tree.Built(key.level-1, index)
599 if err != nil || !built {
600 return false, err
601 }
602 }
603
604 built, err := m.tree.Built(key.level, key.index)
605
606 return !built, err
607 }
608
609 func (m *Memory) context(level, index int) string {
610 end := index
611 if level > 0 {
612 end = nodeEnd(level, index)
613 }
614
615 return m.cview.Context(end)
616 }
617
618 // View returns the chat view as the model reads it.
619 func (m *Memory) View() string {
620 m.mutex.Lock()
621 defer m.mutex.Unlock()
622
623 return m.chat.Render()
624 }
625
626 // Context returns the compaction view for the build of node (l, i). It ends
627 // before the message of a leaf, or after the last message of a merge, and it
628 // stops at the first line that is not built.
629 func (m *Memory) Context(level, index int) string {
630 m.mutex.Lock()
631 defer m.mutex.Unlock()
632
633 return m.context(level, index)
634 }
635
636 // rebuildComplete checks the whole tree, not only the visible view. A compactor
637 // can fail without an HTTP error, for example with an empty line. Such a failed
638 // merge can be absent from the view and must prevent a swap.
639 func (m *Memory) rebuildComplete() error {
640 m.mutex.Lock()
641 defer m.mutex.Unlock()
642
643 if len(m.queue.leaves) != 0 || len(m.queue.queued) != 0 {
644 return errors.New("rebuild failed: summary tree has unfinished nodes")
645 }
646
647 return nil
648 }
649
650 // buildModelLines returns the sizes of the nodes that the model wrote, in tree
651 // order. A node that fits its source with no model call is not one of them.
652 func (m *Memory) buildModelLines() ([]int, error) {
653 m.mutex.Lock()
654 defer m.mutex.Unlock()
655
656 keys, err := m.tree.Keys()
657 if err != nil {
658 return nil, fmt.Errorf("list built nodes: %w", err)
659 }
660
661 var sizes []int
662 for _, key := range keys {
663 var node Node
664
665 node, _, err = m.tree.Node(key.level, key.index)
666 if err != nil {
667 return nil, fmt.Errorf("read built node: %w", err)
668 }
669
670 var model bool
671
672 model, err = m.buildBuiltByModel(key)
673 if err != nil {
674 return nil, fmt.Errorf("check model source: %w", err)
675 }
676
677 if model {
678 sizes = append(sizes, node.Size)
679 }
680 }
681
682 return sizes, nil
683 }
684
685 // buildBuiltByModel tells if the node key needed a model call: a leaf whose
686 // source is over nodeBytes, or a merge whose children do not fit in one node.
687 func (m *Memory) buildBuiltByModel(key NodeKey) (bool, error) {
688 if key.level == 0 {
689 message, err := m.log.Message(key.index)
690 if err != nil {
691 return false, fmt.Errorf("read leaf source: %w", err)
692 }
693
694 _, free := freeLeaf(message)
695
696 return !free, nil
697 }
698
699 left, right, err := m.children(key)
700 if err != nil {
701 return false, fmt.Errorf("read merge sources: %w", err)
702 }
703
704 _, free := freeMerge(left, right)
705
706 return !free, nil
707 }
708
709 // Task is the build of the node (Level, Index). Context is the compaction view
710 // for the build. Input holds the source "kind: text" of a leaf, or the two
711 // child lines of a merge with their newlines as spaces.
712 type Task struct {
713 Level int
714 Index int
715 Context string
716 Input []string
717 }
718
719 // MemoryViewFile is the content of view.json.
720 type MemoryViewFile struct {
721 Chat ViewState `json:"chat"`
722 Compaction ViewState `json:"compaction"`
723 }