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.
276 func (m *Memory) addMessage(message Message) error {
277 leaf, free := freeLeaf(message)
284 m.queue.AddLeaf(message.ID)
287 merged, err := m.chat.Append(m.tree)
289 return fmt.Errorf("append to chat view: %w", err)
292 _, err = m.cview.Append(m.tree)
293 if err == nil && merged {
294 err = m.cview.Coarsen(m.chat, m.tree)
298 return fmt.Errorf("append to compaction view: %w", err)
304 // build adds node to the tree, keeps it in the views when it is a pending line,
305 // and settles its parent.
306 func (m *Memory) build(node Node) error {
307 err := m.tree.Add(node)
313 m.cview.Refresh(node)
315 return m.settle(nodeKey{node.Level, node.Index})
318 // settle looks at the parent of the built node key when both children are
319 // built. It builds each parent that needs no model call, up the tree, and adds
320 // the first other parent to the queue.
321 func (m *Memory) settle(key nodeKey) error {
323 parent := nodeKey{key.level + 1, key.index / 2}
324 ready, err := m.ready(parent)
325 if err != nil || !ready {
329 left, right, err := m.children(parent)
334 node, free := freeMerge(left, right)
336 m.queue.AddMerge(parent)
340 err = m.tree.Add(node)
349 // ready tells if both children of the node key are built and the node is not.
350 func (m *Memory) ready(key nodeKey) (bool, error) {
351 for _, index := range []int{2 * key.index, 2*key.index + 1} {
352 built, err := m.tree.Built(key.level-1, index)
353 if err != nil || !built {
358 built, err := m.tree.Built(key.level, key.index)
363 // children reads the two children of the node key.
364 func (m *Memory) children(key nodeKey) (Node, Node, error) {
366 for n := range children {
367 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
369 return Node{}, Node{}, err
373 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
379 return children[0], children[1], nil
382 // dispatch starts the builds that are ready, up to the limit. A build whose
383 // input cannot be read fails and waits for the next message.
384 func (m *Memory) dispatch() {
385 for m.ctx.Err() == nil {
386 key, ready := m.queue.Next()
391 task, err := m.task(key)
402 // task returns the build task of the node key, with its input read from the log
404 func (m *Memory) task(key nodeKey) (Task, error) {
408 Context: m.context(key.level, key.index),
412 message, err := m.log.Message(key.index)
417 task.Input = []string{leafSource(message)}
422 left, right, err := m.children(key)
427 for _, child := range []Node{left, right} {
428 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
434 // run builds one node with the summarizer. A failed build stays in the queue
435 // until the next message.
436 func (m *Memory) run(key nodeKey, task Task) {
437 defer m.workers.Done()
439 text, err := m.summarizer.Summarize(m.ctx, task)
442 defer m.mutex.Unlock()
460 m.changed = make(chan struct{})
464 // Wait returns when no build runs. The failed builds wait for the next message.
465 func (m *Memory) Wait(ctx context.Context) error {
468 running := m.queue.Running()
484 // save writes the views to view.json.
485 func (m *Memory) save() error {
486 data, err := json.Marshal(viewFile{
487 Chat: m.chat.State(),
488 Compaction: m.cview.State(),
491 return fmt.Errorf("encode view: %w", err)
494 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
496 return fmt.Errorf("save view: %w", err)
502 func (m *Memory) viewPath() string {
503 return filepath.Join(m.root, "view.json")
506 // View returns the chat view as the model reads it.
507 func (m *Memory) View() string {
509 defer m.mutex.Unlock()
511 return m.chat.Render()
514 // Context returns the compaction view for the build of node (l, i). It ends
515 // before the message of a leaf, or after the last message of a merge, and it
516 // stops at the first line that is not built.
517 func (m *Memory) Context(level, index int) string {
519 defer m.mutex.Unlock()
521 return m.context(level, index)
524 func (m *Memory) context(level, index int) string {
527 end = nodeEnd(level, index)
530 return m.cview.Context(end)