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 // Each write goes to the operating system at once, and a syncer makes the
43 // writes durable by group commit in the background. Flush waits until the
44 // writes so far are durable.
46 // The summarizer builds the nodes in the queue in the background. The start
47 // reads the indexes once to fill the queue again. After that, only a new
48 // message or a new node adds work. Memory keeps the nodes of the views and the
49 // tasks of the running builds. It reads all other messages and nodes from their
50 // day files through the indexes.
62 cancel context.CancelFunc
63 workers sync.WaitGroup
67 // viewFile is the content of view.json.
68 type viewFile struct {
69 Chat viewState `json:"chat"`
70 Compaction viewState `json:"compaction"`
73 // openMemory opens the chat in root and starts the builds that are ready. The
74 // clock gives the dates of new messages and the days of new nodes. The builds
75 // stop when ctx ends or at Close.
76 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer) (*Memory, error) {
77 log, err := openLog(ctx, root, clock)
86 summarizer: summarizer,
87 changed: make(chan struct{}),
90 m.ctx, m.cancel = context.WithCancel(ctx)
92 m.syncer, err = openSyncer(root)
94 return nil, errors.Join(err, m.Close())
97 m.tree, err = openTree(ctx, root, log.Len(), clock)
99 return nil, errors.Join(err, m.Close())
104 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
107 err = m.restoreQueue()
109 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
114 return nil, errors.Join(err, m.Close())
125 // load reads the saved views.
126 func (m *Memory) load() error {
127 data, err := os.ReadFile(m.viewPath())
128 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
129 m.chat = newView(chatHigh, chatLow)
130 m.cview = newView(compactionHigh, compactionLow)
135 if errors.Is(err, os.ErrNotExist) {
140 return fmt.Errorf("read view: %w", err)
144 err = json.Unmarshal(data, &file)
146 return fmt.Errorf("decode view: %w", err)
149 m.chat, err = restoreView(file.Chat, chatHigh, chatLow, m.tree)
151 return fmt.Errorf("chat view: %w", err)
154 m.cview, err = restoreView(file.Compaction, compactionHigh, compactionLow, m.tree)
156 return fmt.Errorf("compaction view: %w", err)
159 if m.cview.end != m.chat.end {
160 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
163 if m.chat.end > m.log.Len() {
164 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
170 // restoreQueue adds the work of the messages in the view to the queue. It
171 // builds each node that needs no model call and that a crash left out.
172 func (m *Memory) restoreQueue() error {
173 for id := range m.chat.end {
174 built, err := m.tree.Built(0, id)
183 message, err := m.log.Message(id)
188 leaf, free := freeLeaf(message)
200 keys, err := m.tree.Keys()
205 for _, key := range keys {
206 if key.index%2 != 0 {
219 // catchUp adds the messages that the view does not cover yet. A crash can stop
220 // an append after the log write and before the view save.
221 func (m *Memory) catchUp() error {
222 if m.chat.end == m.log.Len() {
226 for m.chat.end < m.log.Len() {
227 message, err := m.log.Message(m.chat.end)
232 err = m.addMessage(message)
241 // Close stops the builds, waits for them, makes the writes durable, closes the
242 // files of the chat, and releases its lock.
243 func (m *Memory) Close() error {
248 defer m.mutex.Unlock()
252 err = m.syncer.Close()
256 err = errors.Join(err, m.tree.Close())
259 return errors.Join(err, m.log.Close())
262 // Append logs a new message, adds it to the tree and the views, and starts the
263 // builds that are ready, also the failed ones.
264 func (m *Memory) Append(kind, text string) (Message, error) {
266 defer m.mutex.Unlock()
268 message, err := m.log.Append(kind, text)
270 return Message{}, err
273 defer m.syncer.Written()
275 err = m.addMessage(message)
277 return Message{}, err
282 return Message{}, err
291 // addMessage builds the leaf of message when it needs no model call, or else
292 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
293 // stop an append after the leaf build and before the view save, so a leaf that
294 // is built already stays as it is, and restoreQueue settles its parent.
295 func (m *Memory) addMessage(message Message) error {
296 built, err := m.tree.Built(0, message.ID)
301 leaf, free := freeLeaf(message)
310 m.queue.AddLeaf(message.ID)
313 merged, err := m.chat.Append(m.tree)
315 return fmt.Errorf("append to chat view: %w", err)
318 _, err = m.cview.Append(m.tree)
319 if err == nil && merged {
320 err = m.cview.Coarsen(m.chat, m.tree)
324 return fmt.Errorf("append to compaction view: %w", err)
330 // build adds node to the tree, keeps it in the views when it is a pending line,
331 // and settles its parent.
332 func (m *Memory) build(node Node) error {
333 err := m.tree.Add(node)
339 m.cview.Refresh(node)
341 return m.settle(nodeKey{node.Level, node.Index})
344 // settle looks at the parent of the built node key when both children are
345 // built. It builds each parent that needs no model call, up the tree, and adds
346 // the first other parent to the queue.
347 func (m *Memory) settle(key nodeKey) error {
349 parent := nodeKey{key.level + 1, key.index / 2}
350 ready, err := m.ready(parent)
351 if err != nil || !ready {
355 left, right, err := m.children(parent)
360 node, free := freeMerge(left, right)
362 m.queue.AddMerge(parent)
366 err = m.tree.Add(node)
375 // ready tells if both children of the node key are built and the node is not.
376 func (m *Memory) ready(key nodeKey) (bool, error) {
377 for _, index := range []int{2 * key.index, 2*key.index + 1} {
378 built, err := m.tree.Built(key.level-1, index)
379 if err != nil || !built {
384 built, err := m.tree.Built(key.level, key.index)
389 // children reads the two children of the node key.
390 func (m *Memory) children(key nodeKey) (Node, Node, error) {
392 for n := range children {
393 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
395 return Node{}, Node{}, err
399 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
405 return children[0], children[1], nil
408 // dispatch starts the builds that are ready, up to the limit. A build whose
409 // input cannot be read fails and waits for the next message.
410 func (m *Memory) dispatch() {
411 for m.ctx.Err() == nil {
412 key, ready := m.queue.Next()
417 task, err := m.task(key)
428 // task returns the build task of the node key, with its input read from the log
430 func (m *Memory) task(key nodeKey) (Task, error) {
434 Context: m.context(key.level, key.index),
438 message, err := m.log.Message(key.index)
443 task.Input = []string{leafSource(message)}
448 left, right, err := m.children(key)
453 for _, child := range []Node{left, right} {
454 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
460 // run builds one node with the summarizer. A failed build stays in the queue
461 // until the next message.
462 func (m *Memory) run(key nodeKey, task Task) {
463 defer m.workers.Done()
465 text, err := m.summarizer.Summarize(m.ctx, task)
468 defer m.mutex.Unlock()
487 m.changed = make(chan struct{})
491 // Wait returns when no build runs. The failed builds wait for the next message.
492 func (m *Memory) Wait(ctx context.Context) error {
495 running := m.queue.Running()
511 // Flush returns when every write before the call is durable.
512 func (m *Memory) Flush(ctx context.Context) error {
513 return m.syncer.Flush(ctx)
516 // save writes the views to view.json.
517 func (m *Memory) save() error {
518 data, err := json.Marshal(viewFile{
519 Chat: m.chat.State(),
520 Compaction: m.cview.State(),
523 return fmt.Errorf("encode view: %w", err)
526 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
528 return fmt.Errorf("save view: %w", err)
534 func (m *Memory) viewPath() string {
535 return filepath.Join(m.root, "view.json")
538 // View returns the chat view as the model reads it.
539 func (m *Memory) View() string {
541 defer m.mutex.Unlock()
543 return m.chat.Render()
546 // Len returns the number of messages in the log.
547 func (m *Memory) Len() int {
549 defer m.mutex.Unlock()
554 // Message reads the message with the given ID.
555 func (m *Memory) Message(id int) (Message, error) {
557 defer m.mutex.Unlock()
559 return m.log.Message(id)
562 // Node reads the node (l, i) if it is built.
563 func (m *Memory) Node(level, index int) (Node, bool, error) {
565 defer m.mutex.Unlock()
567 return m.tree.Node(level, index)
570 // Context returns the compaction view for the build of node (l, i). It ends
571 // before the message of a leaf, or after the last message of a merge, and it
572 // stops at the first line that is not built.
573 func (m *Memory) Context(level, index int) string {
575 defer m.mutex.Unlock()
577 return m.context(level, index)
580 func (m *Memory) context(level, index int) string {
583 end = nodeEnd(level, index)
586 return m.cview.Context(end)