17 // errMemoryNoView tells that a chat has messages but no saved view.
18 errMemoryNoView = errors.New("the chat has messages but no saved view")
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")
25 // Summarizer builds the text of one node with a model.
26 type Summarizer interface {
27 Summarize(ctx context.Context, task Task) (string, error)
30 // Memory is the memory of one chat: the message log, the summary tree, the chat
31 // view, the compaction view, and the queue of the builds. The compaction view
32 // is the chat view merged further, at the limits of 16 to 32 KB. It takes the
33 // same new lines, and it merges again in one batch when it is too large or when
34 // the chat view merges. So the compactions share its prefix in the prompt
35 // cache. It saves the views to view.json after each change and loads them at
36 // start. It never builds the views again from the log, because a new view
37 // differs from the live one and so loses the prompt cache.
39 // Each write goes to the operating system at once, and a syncer makes the
40 // writes durable by group commit in the background. Flush waits until the
41 // writes so far are durable.
43 // The summarizer builds the nodes in the queue in the background. The start
44 // reads the indexes once to fill the queue again. After that, only a new
45 // message or a new node adds work. Memory keeps the nodes of the views and the
46 // tasks of the running builds. It reads all other messages and nodes from their
47 // day files through the indexes.
60 cancel context.CancelFunc
61 workers sync.WaitGroup
65 // Task is the build of the node (Level, Index). Context is the compaction view
66 // for the build. Input holds the source "kind: text" of a leaf, or the two
67 // child lines of a merge with their newlines as spaces. Images holds the leaf
68 // image filenames and is empty for merges.
77 // MemoryViewFile is the content of view.json.
78 type MemoryViewFile struct {
79 Chat ViewState `json:"chat"`
80 Compaction ViewState `json:"compaction"`
83 // openMemory opens the chat in root and starts the builds that are ready. The
84 // clock gives the dates of new messages and the days of new nodes. logger gets
85 // one line for each failed build. The builds stop when ctx ends or at Close.
86 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer, logger *slog.Logger) (*Memory, error) {
87 log, err := openLog(ctx, root, clock)
89 return nil, fmt.Errorf("open memory log: %w", err)
95 queue: newBuildQueue(),
96 summarizer: summarizer,
98 changed: make(chan struct{}),
101 m.ctx, m.cancel = context.WithCancel(ctx)
103 m.syncer, err = openSyncer(root)
105 return nil, errors.Join(err, m.Close())
108 m.tree, err = openTree(ctx, root, log.Len(), clock)
110 return nil, errors.Join(err, m.Close())
115 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
118 err = m.restoreQueue()
120 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
125 return nil, errors.Join(err, m.Close())
136 // Close stops the builds, waits for them, makes the writes durable, closes the
137 // files of the chat, and releases its lock.
138 func (m *Memory) Close() error {
143 defer m.mutex.Unlock()
148 err = m.syncer.Close()
152 err = errors.Join(err, m.tree.Close())
155 return errors.Join(err, m.log.Close())
158 // load reads the saved views.
159 func (m *Memory) load() error {
160 data, err := os.ReadFile(m.viewPath())
161 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
162 m.chat = newView(viewChatHigh, viewChatLow)
163 m.cview = newView(viewCompactionHigh, viewCompactionLow)
168 if errors.Is(err, os.ErrNotExist) {
169 return errMemoryNoView
173 return fmt.Errorf("read view: %w", err)
176 var file MemoryViewFile
178 err = json.Unmarshal(data, &file)
180 return fmt.Errorf("decode view: %w", err)
183 m.chat, err = restoreView(file.Chat, viewChatHigh, viewChatLow, m.tree)
185 return fmt.Errorf("chat view: %w", err)
188 m.cview, err = restoreView(file.Compaction, viewCompactionHigh, viewCompactionLow, m.tree)
190 return fmt.Errorf("compaction view: %w", err)
193 if m.cview.end != m.chat.end {
194 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
197 if m.chat.end > m.log.Len() {
198 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
204 // restoreQueue adds the work of the messages in the view to the queue. It
205 // builds each node that needs no model call and that a crash left out.
206 func (m *Memory) restoreQueue() error {
207 for id := range m.chat.end {
208 built, err := m.tree.Built(0, id)
210 return fmt.Errorf("check restored leaf: %w", err)
217 message, err := m.log.Message(id)
219 return fmt.Errorf("read restored message: %w", err)
222 leaf, free := freeLeaf(message)
231 return fmt.Errorf("build restored leaf: %w", err)
235 keys, err := m.tree.Keys()
237 return fmt.Errorf("read built nodes: %w", err)
240 for _, key := range keys {
241 if key.index%2 != 0 {
247 return fmt.Errorf("settle restored node: %w", err)
254 // catchUp adds the messages that the view does not cover yet. A crash can stop
255 // an append after the log write and before the view save.
256 func (m *Memory) catchUp() error {
257 if m.chat.end == m.log.Len() {
261 for m.chat.end < m.log.Len() {
262 message, err := m.log.Message(m.chat.end)
264 return fmt.Errorf("read pending message: %w", err)
267 err = m.addMessage(message)
269 return fmt.Errorf("add pending message: %w", err)
276 // dispatch starts the builds that are ready, up to the limit. A build whose
277 // input cannot be read fails and waits for the next message.
278 func (m *Memory) dispatch() {
279 for m.ctx.Err() == nil {
280 key, ready := m.queue.Next()
285 task, err := m.task(key)
287 m.failed(key, fmt.Errorf("read its input: %w", err))
299 func (m *Memory) viewPath() string {
300 return filepath.Join(m.root, "view.json")
303 // build adds node to the tree, keeps it in the views when it is a pending line,
304 // and settles its parent.
305 func (m *Memory) build(node Node) error {
306 err := m.tree.Add(node)
308 return fmt.Errorf("add built node: %w", err)
312 m.cview.Refresh(node)
314 return m.settle(NodeKey{node.Level, node.Index})
317 // settle looks at the parent of the built node key when both children are
318 // built. It builds each parent that needs no model call, up the tree, and adds
319 // the first other parent to the queue.
320 func (m *Memory) settle(key NodeKey) error {
322 parent := NodeKey{key.level + 1, key.index / 2}
323 ready, err := m.ready(parent)
324 if err != nil || !ready {
326 return fmt.Errorf("check parent readiness: %w", err)
332 left, right, err := m.children(parent)
334 return fmt.Errorf("read parent children: %w", err)
337 node, free := freeMerge(left, right)
339 m.queue.AddMerge(parent)
344 err = m.tree.Add(node)
346 return fmt.Errorf("add merged node: %w", err)
353 // addMessage builds the leaf of message when it needs no model call, or else
354 // adds the leaf to the queue. Then it appends the leaf to the views. A crash
355 // can stop an append after the leaf build and before the view save, so a leaf
356 // that is built already stays as it is, and restoreQueue settles its parent.
357 func (m *Memory) addMessage(message Message) error {
358 built, err := m.tree.Built(0, message.ID)
360 return fmt.Errorf("check message leaf: %w", err)
363 leaf, free := freeLeaf(message)
369 return fmt.Errorf("build message leaf: %w", err)
372 m.queue.AddLeaf(message.ID)
375 merged, err := m.chat.Append(m.tree)
377 return fmt.Errorf("append to chat view: %w", err)
380 _, err = m.cview.Append(m.tree)
381 if err == nil && merged {
382 err = m.cview.Coarsen(m.chat, m.tree)
386 return fmt.Errorf("append to compaction view: %w", err)
392 // save writes the views to view.json.
393 func (m *Memory) save() error {
394 data, err := json.Marshal(MemoryViewFile{
395 Chat: m.chat.State(),
396 Compaction: m.cview.State(),
399 return fmt.Errorf("encode view: %w", err)
402 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
404 return fmt.Errorf("save view: %w", err)
410 // task returns the build task of the node key, with its input read from the log
412 func (m *Memory) task(key NodeKey) (Task, error) {
416 Context: m.context(key.level, key.index),
420 message, err := m.log.Message(key.index)
422 return Task{}, fmt.Errorf("read leaf message: %w", err)
425 task.Input = []string{leafSource(message)}
426 task.Images = imageFiles(message.Text)
431 left, right, err := m.children(key)
433 return Task{}, fmt.Errorf("read task children: %w", err)
436 for _, child := range []Node{left, right} {
437 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
443 // failed logs the failed build of the node key with its cause err.
444 func (m *Memory) failed(key NodeKey, err error) {
445 m.logger.Warn("summary failed", "level", key.level, "index", key.index, "err", err)
448 // run builds one node with the summarizer. A failed build stays in the queue
449 // until the next message.
450 func (m *Memory) run(key NodeKey, task Task) {
451 defer m.workers.Done()
453 text, err := m.summarizer.Summarize(m.ctx, task)
456 defer m.mutex.Unlock()
469 if err != nil && m.ctx.Err() == nil {
481 m.changed = make(chan struct{})
485 // ready tells if both children of the node key are built and the node is not.
486 func (m *Memory) ready(key NodeKey) (bool, error) {
487 for _, index := range []int{2 * key.index, 2*key.index + 1} {
488 built, err := m.tree.Built(key.level-1, index)
489 if err != nil || !built {
491 return false, fmt.Errorf("check child readiness: %w", err)
498 built, err := m.tree.Built(key.level, key.index)
500 return !built, fmt.Errorf("check parent readiness: %w", err)
506 // children reads the two children of the node key.
507 func (m *Memory) children(key NodeKey) (Node, Node, error) {
510 for n := range children {
511 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
513 return Node{}, Node{}, fmt.Errorf("read child node: %w", err)
517 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
523 return children[0], children[1], nil
526 func (m *Memory) context(level, index int) string {
529 end = nodeEnd(level, index)
532 return m.cview.Context(end)
535 // Append logs a new message, adds it to the tree and the views, and starts the
536 // builds that are ready, also the failed ones.
537 func (m *Memory) Append(kind, text string) (Message, error) {
538 return m.AppendDated(kind, text, "")
541 // AppendDated appends a message with its RFC 3339 date and builds its nodes. An
542 // empty date uses the clock, as Append does.
543 func (m *Memory) AppendDated(kind, text, date string) (Message, error) {
545 defer m.mutex.Unlock()
547 return m.appendDated(kind, text, date)
550 // appendDated appends under the memory lock and updates the views and builds.
551 func (m *Memory) appendDated(kind, text, date string) (Message, error) {
552 message, err := m.log.AppendDated(kind, text, date)
554 return Message{}, fmt.Errorf("append dated log message: %w", err)
557 defer m.syncer.Written()
559 err = m.addMessage(message)
561 return Message{}, fmt.Errorf("add dated message to memory: %w", err)
566 return Message{}, fmt.Errorf("save dated message view: %w", err)
575 // AppendOnce appends a queued message. prepare saves its log ID before the
576 // append, under the memory lock. A saved ID permits recovery after a stop
577 // between that save and the append, without a second log entry. prepare must
578 // not call Memory. The caller stops delivery after a failed append.
579 func (m *Memory) AppendOnce(kind, text string, id *int, prepare func(int) error) (Message, error) {
581 defer m.mutex.Unlock()
583 if id != nil && *id < m.log.Len() {
584 message, err := m.log.Message(*id)
586 return Message{}, fmt.Errorf("read queued message: %w", err)
589 if message.Kind != kind || message.Text != text {
590 return Message{}, errors.New("queued message does not match its log entry")
596 if id != nil && *id != m.log.Len() {
597 return Message{}, errors.New("queued message is beyond the log")
600 err := prepare(m.log.Len())
602 return Message{}, fmt.Errorf("prepare queued message: %w", err)
605 message, err := m.appendDated(kind, text, "")
607 return Message{}, fmt.Errorf("append queued message: %w", err)
613 // Wait returns when no build runs. The failed builds wait for the next message.
614 func (m *Memory) Wait(ctx context.Context) error {
618 running := m.queue.Running()
634 // Settle returns when the chat view has no pending line, so that every message
635 // so far is summarized. A pending line with no build that runs belongs to a
636 // failed build, which waits for the next message, so Settle returns
637 // errMemoryUnsettled in place of a wait that never ends.
638 func (m *Memory) Settle(ctx context.Context) error {
642 pending := m.chat.Pending()
643 running := m.queue.Running()
652 return errMemoryUnsettled
663 // Snapshot flushes all memory writes and runs snapshot while no append or
664 // summary write can change the log, indexes, tree, or views. snapshot must not
666 func (m *Memory) Snapshot(ctx context.Context, snapshot func() error) error {
668 defer m.mutex.Unlock()
672 return fmt.Errorf("flush memory snapshot: %w", err)
677 return fmt.Errorf("copy memory snapshot: %w", err)
683 // Flush returns when every write before the call is durable.
684 func (m *Memory) Flush(ctx context.Context) error {
685 return m.syncer.Flush(ctx)
688 // ViewLines returns the lines of the chat view, each with its newline, without
689 // the leaf lines of the messages in skip.
690 func (m *Memory) ViewLines(skip map[int]bool) []string {
692 defer m.mutex.Unlock()
694 return m.chat.LinesWithout(skip)
697 // Len returns the number of messages in the log.
698 func (m *Memory) Len() int {
700 defer m.mutex.Unlock()
705 // Message reads the message with the given ID.
706 func (m *Memory) Message(id int) (Message, error) {
708 defer m.mutex.Unlock()
710 return m.log.Message(id)
713 // Node reads the node (l, i) if it is built.
714 func (m *Memory) Node(level, index int) (Node, bool, error) {
716 defer m.mutex.Unlock()
718 return m.tree.Node(level, index)
721 // View returns the chat view as the model reads it.
722 func (m *Memory) View() string {
724 defer m.mutex.Unlock()
726 return m.chat.Render()
729 // Context returns the compaction view for the build of node (l, i). It ends
730 // before the message of a leaf, or after the last message of a merge, and it
731 // stops at the first line that is not built.
732 func (m *Memory) Context(level, index int) string {
734 defer m.mutex.Unlock()
736 return m.context(level, index)
739 // rebuildComplete checks the whole tree, not only the visible view. A compactor
740 // can fail without an HTTP error, for example with an empty line. Such a failed
741 // merge can be absent from the view and must prevent a swap.
742 func (m *Memory) rebuildComplete() error {
744 defer m.mutex.Unlock()
746 if len(m.queue.leaves) != 0 || len(m.queue.queued) != 0 {
747 return errors.New("rebuild failed: summary tree has unfinished nodes")
753 // buildModelLines returns the sizes of the nodes that the model wrote, in tree
754 // order. A node that fits its source with no model call is not one of them.
755 func (m *Memory) buildModelLines() ([]int, error) {
757 defer m.mutex.Unlock()
759 keys, err := m.tree.Keys()
761 return nil, fmt.Errorf("list built nodes: %w", err)
766 for _, key := range keys {
769 node, _, err = m.tree.Node(key.level, key.index)
771 return nil, fmt.Errorf("read built node: %w", err)
776 model, err = m.buildBuiltByModel(key)
778 return nil, fmt.Errorf("check model source: %w", err)
782 sizes = append(sizes, node.Size)
789 // buildBuiltByModel tells if the node key needed a model call: a leaf whose
790 // source is over nodeBytes, or a merge whose children do not fit in one node.
791 func (m *Memory) buildBuiltByModel(key NodeKey) (bool, error) {
793 message, err := m.log.Message(key.index)
795 return false, fmt.Errorf("read leaf source: %w", err)
798 _, free := freeLeaf(message)
803 left, right, err := m.children(key)
805 return false, fmt.Errorf("read merge sources: %w", err)
808 _, free := freeMerge(left, right)