17 // errMemoryNoView tells that a chat has messages but no saved view.
18 errMemoryNoView = errors.New("the chat has messages but no saved view")
20 // errMemoryUnsettled tells that a line of the view stays pending,
21 // because its build failed.
22 errMemoryUnsettled = errors.New("a summary of the view failed, and it is tried again at the next message")
25 // openMemory opens the chat in root and starts the builds that are ready. The
26 // clock gives the dates of new messages and the days of new nodes. logger gets
27 // one line for each failed build. The builds stop when ctx ends or at Close.
28 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer, logger *log.Logger) (*Memory, error) {
29 log, err := openLog(ctx, root, clock)
37 queue: newBuildQueue(),
38 summarizer: summarizer,
40 changed: make(chan struct{}),
43 m.ctx, m.cancel = context.WithCancel(ctx)
45 m.syncer, err = openSyncer(root)
47 return nil, errors.Join(err, m.Close())
50 m.tree, err = openTree(ctx, root, log.Len(), clock)
52 return nil, errors.Join(err, m.Close())
57 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
60 err = m.restoreQueue()
62 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
67 return nil, errors.Join(err, m.Close())
78 // Summarizer builds the text of one node with a model.
79 type Summarizer interface {
80 Summarize(ctx context.Context, task Task) (string, error)
83 // Memory is the memory of one chat: the message log, the summary tree, the chat
84 // view, the compaction view, and the queue of the builds. The compaction view
85 // is the chat view merged further, at the limits of 16 to 32 KB. It takes the
86 // same new lines, and it merges again in one batch when it is too large or when
87 // the chat view merges. So the compactions share its prefix in the prompt
88 // cache. It saves the views to view.json after each change and loads them at
89 // start. It never builds the views again from the log, because a new view
90 // differs from the live one and so loses the prompt cache.
92 // Each write goes to the operating system at once, and a syncer makes the
93 // writes durable by group commit in the background. Flush waits until the
94 // writes so far are durable.
96 // The summarizer builds the nodes in the queue in the background. The start
97 // reads the indexes once to fill the queue again. After that, only a new
98 // message or a new node adds work. Memory keeps the nodes of the views and the
99 // tasks of the running builds. It reads all other messages and nodes from their
100 // day files through the indexes.
110 summarizer Summarizer
113 cancel context.CancelFunc
114 workers sync.WaitGroup
115 changed chan struct{}
118 // Close stops the builds, waits for them, makes the writes durable, closes the
119 // files of the chat, and releases its lock.
120 func (m *Memory) Close() error {
125 defer m.mutex.Unlock()
130 err = m.syncer.Close()
134 err = errors.Join(err, m.tree.Close())
137 return errors.Join(err, m.log.Close())
140 // Append logs a new message, adds it to the tree and the views, and starts the
141 // builds that are ready, also the failed ones.
142 func (m *Memory) Append(kind, text string) (Message, error) {
143 return m.AppendDated(kind, text, "")
146 // AppendDated appends a message with its RFC 3339 date and builds its nodes. An
147 // empty date uses the clock, as Append does.
148 func (m *Memory) AppendDated(kind, text, date string) (Message, error) {
150 defer m.mutex.Unlock()
152 message, err := m.log.AppendDated(kind, text, date)
154 return Message{}, fmt.Errorf("append dated log message: %w", err)
157 defer m.syncer.Written()
159 err = m.addMessage(message)
161 return Message{}, fmt.Errorf("add dated message to memory: %w", err)
166 return Message{}, fmt.Errorf("save dated message view: %w", err)
175 // children reads the two children of the node key.
176 func (m *Memory) children(key NodeKey) (Node, Node, error) {
179 for n := range children {
180 child, built, err := m.tree.Node(key.level-1, 2*key.index+n)
182 return Node{}, Node{}, err
186 return Node{}, Node{}, fmt.Errorf("node (%d, %d) is not built", key.level-1, 2*key.index+n)
192 return children[0], children[1], nil
195 // Wait returns when no build runs. The failed builds wait for the next message.
196 func (m *Memory) Wait(ctx context.Context) error {
200 running := m.queue.Running()
216 // Settle returns when the chat view has no pending line, so that every message
217 // so far is summarized. A pending line with no build that runs belongs to a
218 // failed build, which waits for the next message, so Settle returns
219 // errMemoryUnsettled in place of a wait that never ends.
220 func (m *Memory) Settle(ctx context.Context) error {
224 pending := m.chat.Pending()
225 running := m.queue.Running()
234 return errMemoryUnsettled
245 // Flush returns when every write before the call is durable.
246 func (m *Memory) Flush(ctx context.Context) error {
247 return m.syncer.Flush(ctx)
250 // ViewLines returns the lines of the chat view, each with its newline, without
251 // the leaf lines of the messages in skip.
252 func (m *Memory) ViewLines(skip map[int]bool) []string {
254 defer m.mutex.Unlock()
256 return m.chat.LinesWithout(skip)
259 // Len returns the number of messages in the log.
260 func (m *Memory) Len() int {
262 defer m.mutex.Unlock()
267 // Message reads the message with the given ID.
268 func (m *Memory) Message(id int) (Message, error) {
270 defer m.mutex.Unlock()
272 return m.log.Message(id)
275 // Node reads the node (l, i) if it is built.
276 func (m *Memory) Node(level, index int) (Node, bool, error) {
278 defer m.mutex.Unlock()
280 return m.tree.Node(level, index)
283 // load reads the saved views.
284 func (m *Memory) load() error {
285 data, err := os.ReadFile(m.viewPath())
286 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
287 m.chat = newView(viewChatHigh, viewChatLow)
288 m.cview = newView(viewCompactionHigh, viewCompactionLow)
293 if errors.Is(err, os.ErrNotExist) {
294 return errMemoryNoView
298 return fmt.Errorf("read view: %w", err)
301 var file MemoryViewFile
303 err = json.Unmarshal(data, &file)
305 return fmt.Errorf("decode view: %w", err)
308 m.chat, err = restoreView(file.Chat, viewChatHigh, viewChatLow, m.tree)
310 return fmt.Errorf("chat view: %w", err)
313 m.cview, err = restoreView(file.Compaction, viewCompactionHigh, viewCompactionLow, m.tree)
315 return fmt.Errorf("compaction view: %w", err)
318 if m.cview.end != m.chat.end {
319 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
322 if m.chat.end > m.log.Len() {
323 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
329 // restoreQueue adds the work of the messages in the view to the queue. It
330 // builds each node that needs no model call and that a crash left out.
331 func (m *Memory) restoreQueue() error {
332 for id := range m.chat.end {
333 built, err := m.tree.Built(0, id)
342 message, err := m.log.Message(id)
347 leaf, free := freeLeaf(message)
360 keys, err := m.tree.Keys()
365 for _, key := range keys {
366 if key.index%2 != 0 {
379 // catchUp adds the messages that the view does not cover yet. A crash can stop
380 // an append after the log write and before the view save.
381 func (m *Memory) catchUp() error {
382 if m.chat.end == m.log.Len() {
386 for m.chat.end < m.log.Len() {
387 message, err := m.log.Message(m.chat.end)
392 err = m.addMessage(message)
401 // dispatch starts the builds that are ready, up to the limit. A build whose
402 // input cannot be read fails and waits for the next message.
403 func (m *Memory) dispatch() {
404 for m.ctx.Err() == nil {
405 key, ready := m.queue.Next()
410 task, err := m.task(key)
412 m.failed(key, fmt.Errorf("read its input: %w", err))
424 // addMessage builds the leaf of message when it needs no model call, or else
425 // adds the leaf to the queue. Then it appends the leaf to the views. A crash can
426 // stop an append after the leaf build and before the view save, so a leaf that
427 // is built already stays as it is, and restoreQueue settles its parent.
428 func (m *Memory) addMessage(message Message) error {
429 built, err := m.tree.Built(0, message.ID)
434 leaf, free := freeLeaf(message)
443 m.queue.AddLeaf(message.ID)
446 merged, err := m.chat.Append(m.tree)
448 return fmt.Errorf("append to chat view: %w", err)
451 _, err = m.cview.Append(m.tree)
452 if err == nil && merged {
453 err = m.cview.Coarsen(m.chat, m.tree)
457 return fmt.Errorf("append to compaction view: %w", err)
463 // save writes the views to view.json.
464 func (m *Memory) save() error {
465 data, err := json.Marshal(MemoryViewFile{
466 Chat: m.chat.State(),
467 Compaction: m.cview.State(),
470 return fmt.Errorf("encode view: %w", err)
473 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
475 return fmt.Errorf("save view: %w", err)
481 func (m *Memory) viewPath() string {
482 return filepath.Join(m.root, "view.json")
485 // build adds node to the tree, keeps it in the views when it is a pending line,
486 // and settles its parent.
487 func (m *Memory) build(node Node) error {
488 err := m.tree.Add(node)
494 m.cview.Refresh(node)
496 return m.settle(NodeKey{node.Level, node.Index})
499 // settle looks at the parent of the built node key when both children are
500 // built. It builds each parent that needs no model call, up the tree, and adds
501 // the first other parent to the queue.
502 func (m *Memory) settle(key NodeKey) error {
504 parent := NodeKey{key.level + 1, key.index / 2}
505 ready, err := m.ready(parent)
506 if err != nil || !ready {
510 left, right, err := m.children(parent)
515 node, free := freeMerge(left, right)
517 m.queue.AddMerge(parent)
522 err = m.tree.Add(node)
531 // task returns the build task of the node key, with its input read from the log
533 func (m *Memory) task(key NodeKey) (Task, error) {
537 Context: m.context(key.level, key.index),
541 message, err := m.log.Message(key.index)
546 task.Input = []string{leafSource(message)}
551 left, right, err := m.children(key)
556 for _, child := range []Node{left, right} {
557 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
563 // run builds one node with the summarizer. A failed build stays in the queue
564 // until the next message.
565 func (m *Memory) run(key NodeKey, task Task) {
566 defer m.workers.Done()
568 text, err := m.summarizer.Summarize(m.ctx, task)
571 defer m.mutex.Unlock()
583 if err != nil && m.ctx.Err() == nil {
595 m.changed = make(chan struct{})
599 // failed logs the failed build of the node key with its cause err.
600 func (m *Memory) failed(key NodeKey, err error) {
601 m.logger.Printf("summary failed, retry at next message: node (%d, %d): %v", key.level, key.index, err)
604 // ready tells if both children of the node key are built and the node is not.
605 func (m *Memory) ready(key NodeKey) (bool, error) {
606 for _, index := range []int{2 * key.index, 2*key.index + 1} {
607 built, err := m.tree.Built(key.level-1, index)
608 if err != nil || !built {
613 built, err := m.tree.Built(key.level, key.index)
618 func (m *Memory) context(level, index int) string {
621 end = nodeEnd(level, index)
624 return m.cview.Context(end)
627 // View returns the chat view as the model reads it.
628 func (m *Memory) View() string {
630 defer m.mutex.Unlock()
632 return m.chat.Render()
635 // Context returns the compaction view for the build of node (l, i). It ends
636 // before the message of a leaf, or after the last message of a merge, and it
637 // stops at the first line that is not built.
638 func (m *Memory) Context(level, index int) string {
640 defer m.mutex.Unlock()
642 return m.context(level, index)
645 // rebuildComplete checks the whole tree, not only the visible view. A compactor
646 // can fail without an HTTP error, for example with an empty line. Such a failed
647 // merge can be absent from the view and must prevent a swap.
648 func (m *Memory) rebuildComplete() error {
650 defer m.mutex.Unlock()
652 if len(m.queue.leaves) != 0 || len(m.queue.queued) != 0 {
653 return errors.New("rebuild failed: summary tree has unfinished nodes")
659 // buildModelLines returns the sizes of the nodes that the model wrote, in tree
660 // order. A node that fits its source with no model call is not one of them.
661 func (m *Memory) buildModelLines() ([]int, error) {
663 defer m.mutex.Unlock()
665 keys, err := m.tree.Keys()
667 return nil, fmt.Errorf("list built nodes: %w", err)
672 for _, key := range keys {
675 node, _, err = m.tree.Node(key.level, key.index)
677 return nil, fmt.Errorf("read built node: %w", err)
682 model, err = m.buildBuiltByModel(key)
684 return nil, fmt.Errorf("check model source: %w", err)
688 sizes = append(sizes, node.Size)
695 // buildBuiltByModel tells if the node key needed a model call: a leaf whose
696 // source is over nodeBytes, or a merge whose children do not fit in one node.
697 func (m *Memory) buildBuiltByModel(key NodeKey) (bool, error) {
699 message, err := m.log.Message(key.index)
701 return false, fmt.Errorf("read leaf source: %w", err)
704 _, free := freeLeaf(message)
709 left, right, err := m.children(key)
711 return false, fmt.Errorf("read merge sources: %w", err)
714 _, free := freeMerge(left, right)
719 // Task is the build of the node (Level, Index). Context is the compaction view
720 // for the build. Input holds the source "kind: text" of a leaf, or the two
721 // child lines of a merge with their newlines as spaces.
729 // MemoryViewFile is the content of view.json.
730 type MemoryViewFile struct {
731 Chat ViewState `json:"chat"`
732 Compaction ViewState `json:"compaction"`