16 // errMemoryNoView tells that a chat has messages but no saved view.
17 errMemoryNoView = errors.New("the chat has messages but no saved view")
19 // errMemoryUnsettled tells that a line of the view stays pending,
20 // because its build failed.
21 errMemoryUnsettled = errors.New("a summary of the view failed, and it is tried again at the next message")
24 // openMemory opens the chat in root and starts the builds that are ready. The
25 // clock gives the dates of new messages and the days of new nodes. The builds
26 // stop when ctx ends or at Close.
27 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer) (*Memory, error) {
28 log, err := openLog(ctx, root, clock)
36 queue: newBuildQueue(),
37 summarizer: summarizer,
38 changed: make(chan struct{}),
41 m.ctx, m.cancel = context.WithCancel(ctx)
43 m.syncer, err = openSyncer(root)
45 return nil, errors.Join(err, m.Close())
48 m.tree, err = openTree(ctx, root, log.Len(), clock)
50 return nil, errors.Join(err, m.Close())
55 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
58 err = m.restoreQueue()
60 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
65 return nil, errors.Join(err, m.Close())
76 // Summarizer builds the text of one node with a model.
77 type Summarizer interface {
78 Summarize(ctx context.Context, task Task) (string, error)
81 // Memory is the memory of one chat: the message log, the summary tree, the chat
82 // view, the compaction view, and the queue of the builds. The compaction view
83 // is the chat view merged further, at the limits of 16 to 32 KB. It takes the
84 // same new lines, and it merges again in one batch when it is too large or when
85 // the chat view merges. So the compactions share its prefix in the prompt
86 // cache. It saves the views to view.json after each change and loads them at
87 // start. It never builds the views again from the log, because a new view
88 // differs from the live one and so loses the prompt cache.
90 // Each write goes to the operating system at once, and a syncer makes the
91 // writes durable by group commit in the background. Flush waits until the
92 // writes so far are durable.
94 // The summarizer builds the nodes in the queue in the background. The start
95 // reads the indexes once to fill the queue again. After that, only a new
96 // message or a new node adds work. Memory keeps the nodes of the views and the
97 // tasks of the running builds. It reads all other messages and nodes from their
98 // day files through the indexes.
108 summarizer Summarizer
110 cancel context.CancelFunc
111 workers sync.WaitGroup
112 changed chan struct{}
115 // Close stops the builds, waits for them, makes the writes durable, closes the
116 // files of the chat, and releases its lock.
117 func (m *Memory) Close() error {
122 defer m.mutex.Unlock()
126 err = m.syncer.Close()
130 err = errors.Join(err, m.tree.Close())
133 return errors.Join(err, m.log.Close())
136 // Append logs a new message, adds it to the tree and the views, and starts the
137 // builds that are ready, also the failed ones.
138 func (m *Memory) Append(kind, text string) (Message, error) {
140 defer m.mutex.Unlock()
142 message, err := m.log.Append(kind, text)
144 return Message{}, err
147 defer m.syncer.Written()
149 err = m.addMessage(message)
151 return Message{}, err
156 return Message{}, err
165 // children reads the two children of the node key.
166 func (m *Memory) children(key NodeKey) (Node, Node, error) {
168 for n := range children {
169 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
171 return Node{}, Node{}, err
175 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
181 return children[0], children[1], nil
184 // Wait returns when no build runs. The failed builds wait for the next message.
185 func (m *Memory) Wait(ctx context.Context) error {
188 running := m.queue.Running()
204 // Settle returns when the chat view has no pending line, so that every message
205 // so far is summarized. A pending line with no build that runs belongs to a
206 // failed build, which waits for the next message, so Settle returns
207 // errMemoryUnsettled in place of a wait that never ends.
208 func (m *Memory) Settle(ctx context.Context) error {
211 pending := m.chat.Pending()
212 running := m.queue.Running()
221 return errMemoryUnsettled
232 // Flush returns when every write before the call is durable.
233 func (m *Memory) Flush(ctx context.Context) error {
234 return m.syncer.Flush(ctx)
237 // ViewLines returns the lines of the chat view, each with its newline, without
238 // the leaf lines of the messages in skip.
239 func (m *Memory) ViewLines(skip map[int]bool) []string {
241 defer m.mutex.Unlock()
243 return m.chat.LinesWithout(skip)
246 // Len returns the number of messages in the log.
247 func (m *Memory) Len() int {
249 defer m.mutex.Unlock()
254 // Message reads the message with the given ID.
255 func (m *Memory) Message(id int) (Message, error) {
257 defer m.mutex.Unlock()
259 return m.log.Message(id)
262 // Node reads the node (l, i) if it is built.
263 func (m *Memory) Node(level, index int) (Node, bool, error) {
265 defer m.mutex.Unlock()
267 return m.tree.Node(level, index)
270 // load reads the saved views.
271 func (m *Memory) load() error {
272 data, err := os.ReadFile(m.viewPath())
273 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
274 m.chat = newView(viewChatHigh, viewChatLow)
275 m.cview = newView(viewCompactionHigh, viewCompactionLow)
280 if errors.Is(err, os.ErrNotExist) {
281 return errMemoryNoView
285 return fmt.Errorf("read view: %w", err)
288 var file MemoryViewFile
289 err = json.Unmarshal(data, &file)
291 return fmt.Errorf("decode view: %w", err)
294 m.chat, err = restoreView(file.Chat, viewChatHigh, viewChatLow, m.tree)
296 return fmt.Errorf("chat view: %w", err)
299 m.cview, err = restoreView(file.Compaction, viewCompactionHigh, viewCompactionLow, m.tree)
301 return fmt.Errorf("compaction view: %w", err)
304 if m.cview.end != m.chat.end {
305 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
308 if m.chat.end > m.log.Len() {
309 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
315 // restoreQueue adds the work of the messages in the view to the queue. It
316 // builds each node that needs no model call and that a crash left out.
317 func (m *Memory) restoreQueue() error {
318 for id := range m.chat.end {
319 built, err := m.tree.Built(0, id)
328 message, err := m.log.Message(id)
333 leaf, free := freeLeaf(message)
345 keys, err := m.tree.Keys()
350 for _, key := range keys {
351 if key.index%2 != 0 {
364 // catchUp adds the messages that the view does not cover yet. A crash can stop
365 // an append after the log write and before the view save.
366 func (m *Memory) catchUp() error {
367 if m.chat.end == m.log.Len() {
371 for m.chat.end < m.log.Len() {
372 message, err := m.log.Message(m.chat.end)
377 err = m.addMessage(message)
386 // dispatch starts the builds that are ready, up to the limit. A build whose
387 // input cannot be read fails and waits for the next message.
388 func (m *Memory) dispatch() {
389 for m.ctx.Err() == nil {
390 key, ready := m.queue.Next()
395 task, err := m.task(key)
406 // addMessage builds the leaf of message when it needs no model call, or else
407 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
408 // stop an append after the leaf build and before the view save, so a leaf that
409 // is built already stays as it is, and restoreQueue settles its parent.
410 func (m *Memory) addMessage(message Message) error {
411 built, err := m.tree.Built(0, message.ID)
416 leaf, free := freeLeaf(message)
425 m.queue.AddLeaf(message.ID)
428 merged, err := m.chat.Append(m.tree)
430 return fmt.Errorf("append to chat view: %w", err)
433 _, err = m.cview.Append(m.tree)
434 if err == nil && merged {
435 err = m.cview.Coarsen(m.chat, m.tree)
439 return fmt.Errorf("append to compaction view: %w", err)
445 // save writes the views to view.json.
446 func (m *Memory) save() error {
447 data, err := json.Marshal(MemoryViewFile{
448 Chat: m.chat.State(),
449 Compaction: m.cview.State(),
452 return fmt.Errorf("encode view: %w", err)
455 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
457 return fmt.Errorf("save view: %w", err)
463 func (m *Memory) viewPath() string {
464 return filepath.Join(m.root, "view.json")
467 // build adds node to the tree, keeps it in the views when it is a pending line,
468 // and settles its parent.
469 func (m *Memory) build(node Node) error {
470 err := m.tree.Add(node)
476 m.cview.Refresh(node)
478 return m.settle(NodeKey{node.Level, node.Index})
481 // settle looks at the parent of the built node key when both children are
482 // built. It builds each parent that needs no model call, up the tree, and adds
483 // the first other parent to the queue.
484 func (m *Memory) settle(key NodeKey) error {
486 parent := NodeKey{key.level + 1, key.index / 2}
487 ready, err := m.ready(parent)
488 if err != nil || !ready {
492 left, right, err := m.children(parent)
497 node, free := freeMerge(left, right)
499 m.queue.AddMerge(parent)
503 err = m.tree.Add(node)
512 // task returns the build task of the node key, with its input read from the log
514 func (m *Memory) task(key NodeKey) (Task, error) {
518 Context: m.context(key.level, key.index),
522 message, err := m.log.Message(key.index)
527 task.Input = []string{leafSource(message)}
532 left, right, err := m.children(key)
537 for _, child := range []Node{left, right} {
538 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
544 // run builds one node with the summarizer. A failed build stays in the queue
545 // until the next message.
546 func (m *Memory) run(key NodeKey, task Task) {
547 defer m.workers.Done()
549 text, err := m.summarizer.Summarize(m.ctx, task)
552 defer m.mutex.Unlock()
571 m.changed = make(chan struct{})
575 // ready tells if both children of the node key are built and the node is not.
576 func (m *Memory) ready(key NodeKey) (bool, error) {
577 for _, index := range []int{2 * key.index, 2*key.index + 1} {
578 built, err := m.tree.Built(key.level-1, index)
579 if err != nil || !built {
584 built, err := m.tree.Built(key.level, key.index)
589 func (m *Memory) context(level, index int) string {
592 end = nodeEnd(level, index)
595 return m.cview.Context(end)
598 // View returns the chat view as the model reads it.
599 func (m *Memory) View() string {
601 defer m.mutex.Unlock()
603 return m.chat.Render()
606 // Context returns the compaction view for the build of node (l, i). It ends
607 // before the message of a leaf, or after the last message of a merge, and it
608 // stops at the first line that is not built.
609 func (m *Memory) Context(level, index int) string {
611 defer m.mutex.Unlock()
613 return m.context(level, index)
616 // Task is the build of the node (Level, Index). Context is the compaction view
617 // for the build. Input holds the source "kind: text" of a leaf, or the two
618 // child lines of a merge with their newlines as spaces.
626 // MemoryViewFile is the content of view.json.
627 type MemoryViewFile struct {
628 Chat ViewState `json:"chat"`
629 Compaction ViewState `json:"compaction"`