15 // errMemoryNoView tells that a chat has messages but no saved view.
16 var errMemoryNoView = errors.New("the chat has messages but no saved view")
18 // openMemory opens the chat in root and starts the builds that are ready. The
19 // clock gives the dates of new messages and the days of new nodes. The builds
20 // stop when ctx ends or at Close.
21 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer) (*Memory, error) {
22 log, err := openLog(ctx, root, clock)
30 queue: newBuildQueue(),
31 summarizer: summarizer,
32 changed: make(chan struct{}),
35 m.ctx, m.cancel = context.WithCancel(ctx)
37 m.syncer, err = openSyncer(root)
39 return nil, errors.Join(err, m.Close())
42 m.tree, err = openTree(ctx, root, log.Len(), clock)
44 return nil, errors.Join(err, m.Close())
49 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
52 err = m.restoreQueue()
54 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
59 return nil, errors.Join(err, m.Close())
70 // Summarizer builds the text of one node with a model.
71 type Summarizer interface {
72 Summarize(ctx context.Context, task Task) (string, error)
75 // Memory is the memory of one chat: the message log, the summary tree, the chat
76 // view, the compaction view, and the queue of the builds. The compaction view
77 // is the chat view merged further, at the limits of 16 to 32 KB. It takes the
78 // same new lines, and it merges again in one batch when it is too large or when
79 // the chat view merges. So the compactions share its prefix in the prompt
80 // cache. It saves the views to view.json after each change and loads them at
81 // start. It never builds the views again from the log, because a new view
82 // differs from the live one and so loses the prompt cache.
84 // Each write goes to the operating system at once, and a syncer makes the
85 // writes durable by group commit in the background. Flush waits until the
86 // writes so far are durable.
88 // The summarizer builds the nodes in the queue in the background. The start
89 // reads the indexes once to fill the queue again. After that, only a new
90 // message or a new node adds work. Memory keeps the nodes of the views and the
91 // tasks of the running builds. It reads all other messages and nodes from their
92 // day files through the indexes.
102 summarizer Summarizer
104 cancel context.CancelFunc
105 workers sync.WaitGroup
106 changed chan struct{}
109 // Close stops the builds, waits for them, makes the writes durable, closes the
110 // files of the chat, and releases its lock.
111 func (m *Memory) Close() error {
116 defer m.mutex.Unlock()
120 err = m.syncer.Close()
124 err = errors.Join(err, m.tree.Close())
127 return errors.Join(err, m.log.Close())
130 // Append logs a new message, adds it to the tree and the views, and starts the
131 // builds that are ready, also the failed ones.
132 func (m *Memory) Append(kind, text string) (Message, error) {
134 defer m.mutex.Unlock()
136 message, err := m.log.Append(kind, text)
138 return Message{}, err
141 defer m.syncer.Written()
143 err = m.addMessage(message)
145 return Message{}, err
150 return Message{}, err
159 // children reads the two children of the node key.
160 func (m *Memory) children(key NodeKey) (Node, Node, error) {
162 for n := range children {
163 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
165 return Node{}, Node{}, err
169 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
175 return children[0], children[1], nil
178 // Wait returns when no build runs. The failed builds wait for the next message.
179 func (m *Memory) Wait(ctx context.Context) error {
182 running := m.queue.Running()
198 // Flush returns when every write before the call is durable.
199 func (m *Memory) Flush(ctx context.Context) error {
200 return m.syncer.Flush(ctx)
203 // ViewLines returns the lines of the chat view, each with its newline, without
204 // the leaf lines of the messages in skip.
205 func (m *Memory) ViewLines(skip map[int]bool) []string {
207 defer m.mutex.Unlock()
209 return m.chat.LinesWithout(skip)
212 // Len returns the number of messages in the log.
213 func (m *Memory) Len() int {
215 defer m.mutex.Unlock()
220 // Message reads the message with the given ID.
221 func (m *Memory) Message(id int) (Message, error) {
223 defer m.mutex.Unlock()
225 return m.log.Message(id)
228 // Node reads the node (l, i) if it is built.
229 func (m *Memory) Node(level, index int) (Node, bool, error) {
231 defer m.mutex.Unlock()
233 return m.tree.Node(level, index)
236 // load reads the saved views.
237 func (m *Memory) load() error {
238 data, err := os.ReadFile(m.viewPath())
239 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
240 m.chat = newView(viewChatHigh, viewChatLow)
241 m.cview = newView(viewCompactionHigh, viewCompactionLow)
246 if errors.Is(err, os.ErrNotExist) {
247 return errMemoryNoView
251 return fmt.Errorf("read view: %w", err)
254 var file MemoryViewFile
255 err = json.Unmarshal(data, &file)
257 return fmt.Errorf("decode view: %w", err)
260 m.chat, err = restoreView(file.Chat, viewChatHigh, viewChatLow, m.tree)
262 return fmt.Errorf("chat view: %w", err)
265 m.cview, err = restoreView(file.Compaction, viewCompactionHigh, viewCompactionLow, m.tree)
267 return fmt.Errorf("compaction view: %w", err)
270 if m.cview.end != m.chat.end {
271 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
274 if m.chat.end > m.log.Len() {
275 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
281 // restoreQueue adds the work of the messages in the view to the queue. It
282 // builds each node that needs no model call and that a crash left out.
283 func (m *Memory) restoreQueue() error {
284 for id := range m.chat.end {
285 built, err := m.tree.Built(0, id)
294 message, err := m.log.Message(id)
299 leaf, free := freeLeaf(message)
311 keys, err := m.tree.Keys()
316 for _, key := range keys {
317 if key.index%2 != 0 {
330 // catchUp adds the messages that the view does not cover yet. A crash can stop
331 // an append after the log write and before the view save.
332 func (m *Memory) catchUp() error {
333 if m.chat.end == m.log.Len() {
337 for m.chat.end < m.log.Len() {
338 message, err := m.log.Message(m.chat.end)
343 err = m.addMessage(message)
352 // dispatch starts the builds that are ready, up to the limit. A build whose
353 // input cannot be read fails and waits for the next message.
354 func (m *Memory) dispatch() {
355 for m.ctx.Err() == nil {
356 key, ready := m.queue.Next()
361 task, err := m.task(key)
372 // addMessage builds the leaf of message when it needs no model call, or else
373 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
374 // stop an append after the leaf build and before the view save, so a leaf that
375 // is built already stays as it is, and restoreQueue settles its parent.
376 func (m *Memory) addMessage(message Message) error {
377 built, err := m.tree.Built(0, message.ID)
382 leaf, free := freeLeaf(message)
391 m.queue.AddLeaf(message.ID)
394 merged, err := m.chat.Append(m.tree)
396 return fmt.Errorf("append to chat view: %w", err)
399 _, err = m.cview.Append(m.tree)
400 if err == nil && merged {
401 err = m.cview.Coarsen(m.chat, m.tree)
405 return fmt.Errorf("append to compaction view: %w", err)
411 // save writes the views to view.json.
412 func (m *Memory) save() error {
413 data, err := json.Marshal(MemoryViewFile{
414 Chat: m.chat.State(),
415 Compaction: m.cview.State(),
418 return fmt.Errorf("encode view: %w", err)
421 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
423 return fmt.Errorf("save view: %w", err)
429 func (m *Memory) viewPath() string {
430 return filepath.Join(m.root, "view.json")
433 // build adds node to the tree, keeps it in the views when it is a pending line,
434 // and settles its parent.
435 func (m *Memory) build(node Node) error {
436 err := m.tree.Add(node)
442 m.cview.Refresh(node)
444 return m.settle(NodeKey{node.Level, node.Index})
447 // settle looks at the parent of the built node key when both children are
448 // built. It builds each parent that needs no model call, up the tree, and adds
449 // the first other parent to the queue.
450 func (m *Memory) settle(key NodeKey) error {
452 parent := NodeKey{key.level + 1, key.index / 2}
453 ready, err := m.ready(parent)
454 if err != nil || !ready {
458 left, right, err := m.children(parent)
463 node, free := freeMerge(left, right)
465 m.queue.AddMerge(parent)
469 err = m.tree.Add(node)
478 // task returns the build task of the node key, with its input read from the log
480 func (m *Memory) task(key NodeKey) (Task, error) {
484 Context: m.context(key.level, key.index),
488 message, err := m.log.Message(key.index)
493 task.Input = []string{leafSource(message)}
498 left, right, err := m.children(key)
503 for _, child := range []Node{left, right} {
504 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
510 // run builds one node with the summarizer. A failed build stays in the queue
511 // until the next message.
512 func (m *Memory) run(key NodeKey, task Task) {
513 defer m.workers.Done()
515 text, err := m.summarizer.Summarize(m.ctx, task)
518 defer m.mutex.Unlock()
537 m.changed = make(chan struct{})
541 // ready tells if both children of the node key are built and the node is not.
542 func (m *Memory) ready(key NodeKey) (bool, error) {
543 for _, index := range []int{2 * key.index, 2*key.index + 1} {
544 built, err := m.tree.Built(key.level-1, index)
545 if err != nil || !built {
550 built, err := m.tree.Built(key.level, key.index)
555 func (m *Memory) context(level, index int) string {
558 end = nodeEnd(level, index)
561 return m.cview.Context(end)
564 // View returns the chat view as the model reads it.
565 func (m *Memory) View() string {
567 defer m.mutex.Unlock()
569 return m.chat.Render()
572 // Context returns the compaction view for the build of node (l, i). It ends
573 // before the message of a leaf, or after the last message of a merge, and it
574 // stops at the first line that is not built.
575 func (m *Memory) Context(level, index int) string {
577 defer m.mutex.Unlock()
579 return m.context(level, index)
582 // Task is the build of the node (Level, Index). Context is the compaction view
583 // for the build. Input holds the source "kind: text" of a leaf, or the two
584 // child lines of a merge with their newlines as spaces.
592 // MemoryViewFile is the content of view.json.
593 type MemoryViewFile struct {
594 Chat ViewState `json:"chat"`
595 Compaction ViewState `json:"compaction"`