15 // errNoView tells that a chat has messages but no saved view.
16 var errNoView = errors.New("the chat has messages but no saved view")
18 // Summarizer builds the text of one node with a model.
19 type Summarizer interface {
20 Summarize(ctx context.Context, task Task) (string, error)
23 // Task is the build of the node (Level, Index). Context is the compaction view
24 // for the build. Input holds the source "kind: text" of a leaf, or the two
25 // child lines of a merge with their newlines as spaces.
33 // Memory is the memory of one chat: the message log, the summary tree, the chat
34 // view, the compaction view, and the queue of the builds. The compaction view
35 // is the chat view merged further, at the limits of 16 to 32 KB. It takes the
36 // same new lines, and it merges again in one batch when it is too large or when
37 // the chat view merges. So the compactions share its prefix in the prompt
38 // cache. It saves the views to view.json after each change and loads them at
39 // start. It never builds the views again from the log, because a new view
40 // differs from the live one and so loses the prompt cache.
42 // The summarizer builds the nodes in the queue in the background. The start
43 // reads the indexes once to fill the queue again. After that, only a new
44 // message or a new node adds work. Memory keeps the nodes of the views and the
45 // tasks of the running builds. It reads all other messages and nodes from their
46 // day files through the indexes.
57 cancel context.CancelFunc
58 workers sync.WaitGroup
62 // viewFile is the content of view.json.
63 type viewFile struct {
64 Chat viewState `json:"chat"`
65 Compaction viewState `json:"compaction"`
68 // openMemory opens the chat in root and starts the builds that are ready. The
69 // clock gives the dates of new messages and the days of new nodes. The builds
70 // stop when ctx ends or at Close.
71 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer) (*Memory, error) {
72 log, err := openLog(ctx, root, clock)
81 summarizer: summarizer,
82 changed: make(chan struct{}),
85 m.ctx, m.cancel = context.WithCancel(ctx)
87 m.tree, err = openTree(ctx, root, log.Len(), clock)
89 return nil, errors.Join(err, m.Close())
94 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
97 err = m.restoreQueue()
99 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
104 return nil, errors.Join(err, m.Close())
114 // load reads the saved views.
115 func (m *Memory) load() error {
116 data, err := os.ReadFile(m.viewPath())
117 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
118 m.chat = newView(chatHigh, chatLow)
119 m.cview = newView(compactionHigh, compactionLow)
124 if errors.Is(err, os.ErrNotExist) {
129 return fmt.Errorf("read view: %w", err)
133 err = json.Unmarshal(data, &file)
135 return fmt.Errorf("decode view: %w", err)
138 m.chat, err = restoreView(file.Chat, chatHigh, chatLow, m.tree)
140 return fmt.Errorf("chat view: %w", err)
143 m.cview, err = restoreView(file.Compaction, compactionHigh, compactionLow, m.tree)
145 return fmt.Errorf("compaction view: %w", err)
148 if m.cview.end != m.chat.end {
149 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
152 if m.chat.end > m.log.Len() {
153 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
159 // restoreQueue adds the work of the messages in the view to the queue. It
160 // builds each node that needs no model call and that a crash left out.
161 func (m *Memory) restoreQueue() error {
162 for id := range m.chat.end {
163 built, err := m.tree.Built(0, id)
172 message, err := m.log.Message(id)
177 leaf, free := freeLeaf(message)
189 keys, err := m.tree.Keys()
194 for _, key := range keys {
195 if key.index%2 != 0 {
208 // catchUp adds the messages that the view does not cover yet. A crash can stop
209 // an append after the log write and before the view save.
210 func (m *Memory) catchUp() error {
211 if m.chat.end == m.log.Len() {
215 for m.chat.end < m.log.Len() {
216 message, err := m.log.Message(m.chat.end)
221 err = m.addMessage(message)
230 // Close stops the builds, waits for them, closes the files of the chat, and
231 // releases its lock.
232 func (m *Memory) Close() error {
237 defer m.mutex.Unlock()
244 return errors.Join(err, m.log.Close())
247 // Append logs a new message, adds it to the tree and the views, and starts the
248 // builds that are ready, also the failed ones.
249 func (m *Memory) Append(kind, text string) (Message, error) {
251 defer m.mutex.Unlock()
253 message, err := m.log.Append(kind, text)
255 return Message{}, err
258 err = m.addMessage(message)
260 return Message{}, err
265 return Message{}, err
274 // addMessage builds the leaf of message when it needs no model call, or else
275 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
276 // stop an append after the leaf build and before the view save, so a leaf that
277 // is built already stays as it is, and restoreQueue settles its parent.
278 func (m *Memory) addMessage(message Message) error {
279 built, err := m.tree.Built(0, message.ID)
284 leaf, free := freeLeaf(message)
293 m.queue.AddLeaf(message.ID)
296 merged, err := m.chat.Append(m.tree)
298 return fmt.Errorf("append to chat view: %w", err)
301 _, err = m.cview.Append(m.tree)
302 if err == nil && merged {
303 err = m.cview.Coarsen(m.chat, m.tree)
307 return fmt.Errorf("append to compaction view: %w", err)
313 // build adds node to the tree, keeps it in the views when it is a pending line,
314 // and settles its parent.
315 func (m *Memory) build(node Node) error {
316 err := m.tree.Add(node)
322 m.cview.Refresh(node)
324 return m.settle(nodeKey{node.Level, node.Index})
327 // settle looks at the parent of the built node key when both children are
328 // built. It builds each parent that needs no model call, up the tree, and adds
329 // the first other parent to the queue.
330 func (m *Memory) settle(key nodeKey) error {
332 parent := nodeKey{key.level + 1, key.index / 2}
333 ready, err := m.ready(parent)
334 if err != nil || !ready {
338 left, right, err := m.children(parent)
343 node, free := freeMerge(left, right)
345 m.queue.AddMerge(parent)
349 err = m.tree.Add(node)
358 // ready tells if both children of the node key are built and the node is not.
359 func (m *Memory) ready(key nodeKey) (bool, error) {
360 for _, index := range []int{2 * key.index, 2*key.index + 1} {
361 built, err := m.tree.Built(key.level-1, index)
362 if err != nil || !built {
367 built, err := m.tree.Built(key.level, key.index)
372 // children reads the two children of the node key.
373 func (m *Memory) children(key nodeKey) (Node, Node, error) {
375 for n := range children {
376 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
378 return Node{}, Node{}, err
382 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
388 return children[0], children[1], nil
391 // dispatch starts the builds that are ready, up to the limit. A build whose
392 // input cannot be read fails and waits for the next message.
393 func (m *Memory) dispatch() {
394 for m.ctx.Err() == nil {
395 key, ready := m.queue.Next()
400 task, err := m.task(key)
411 // task returns the build task of the node key, with its input read from the log
413 func (m *Memory) task(key nodeKey) (Task, error) {
417 Context: m.context(key.level, key.index),
421 message, err := m.log.Message(key.index)
426 task.Input = []string{leafSource(message)}
431 left, right, err := m.children(key)
436 for _, child := range []Node{left, right} {
437 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
443 // run builds one node with the summarizer. A failed build stays in the queue
444 // until the next message.
445 func (m *Memory) run(key nodeKey, task Task) {
446 defer m.workers.Done()
448 text, err := m.summarizer.Summarize(m.ctx, task)
451 defer m.mutex.Unlock()
469 m.changed = make(chan struct{})
473 // Wait returns when no build runs. The failed builds wait for the next message.
474 func (m *Memory) Wait(ctx context.Context) error {
477 running := m.queue.Running()
493 // save writes the views to view.json.
494 func (m *Memory) save() error {
495 data, err := json.Marshal(viewFile{
496 Chat: m.chat.State(),
497 Compaction: m.cview.State(),
500 return fmt.Errorf("encode view: %w", err)
503 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
505 return fmt.Errorf("save view: %w", err)
511 func (m *Memory) viewPath() string {
512 return filepath.Join(m.root, "view.json")
515 // View returns the chat view as the model reads it.
516 func (m *Memory) View() string {
518 defer m.mutex.Unlock()
520 return m.chat.Render()
523 // Context returns the compaction view for the build of node (l, i). It ends
524 // before the message of a leaf, or after the last message of a merge, and it
525 // stops at the first line that is not built.
526 func (m *Memory) Context(level, index int) string {
528 defer m.mutex.Unlock()
530 return m.context(level, index)
533 func (m *Memory) context(level, index int) string {
536 end = nodeEnd(level, index)
539 return m.cview.Context(end)