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 log and the tree once to fill the queue again. After that, only a
44 // new message or a new node adds work.
55 cancel context.CancelFunc
56 workers sync.WaitGroup
60 // viewFile is the content of view.json.
61 type viewFile struct {
62 Chat viewState `json:"chat"`
63 Compaction viewState `json:"compaction"`
66 // openMemory opens the chat in root and starts the builds that are ready. The
67 // clock gives the dates of new messages and the days of new nodes. The builds
68 // stop when ctx ends or at Close.
69 func openMemory(ctx context.Context, root string, clock func() time.Time, summarizer Summarizer) (*Memory, error) {
70 log, err := openLog(ctx, root, clock)
79 summarizer: summarizer,
80 changed: make(chan struct{}),
83 m.ctx, m.cancel = context.WithCancel(ctx)
85 m.tree, err = openTree(ctx, root, log.Len(), clock)
87 return nil, errors.Join(err, m.Close())
92 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
95 err = m.restoreQueue()
97 return nil, errors.Join(fmt.Errorf("restore build queue: %w", err), m.Close())
102 return nil, errors.Join(err, m.Close())
112 // load reads the saved views.
113 func (m *Memory) load() error {
114 data, err := os.ReadFile(m.viewPath())
115 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
116 m.chat = newView(chatHigh, chatLow)
117 m.cview = newView(compactionHigh, compactionLow)
122 if errors.Is(err, os.ErrNotExist) {
127 return fmt.Errorf("read view: %w", err)
131 err = json.Unmarshal(data, &file)
133 return fmt.Errorf("decode view: %w", err)
136 m.chat, err = restoreView(file.Chat, chatHigh, chatLow, m.tree)
138 return fmt.Errorf("chat view: %w", err)
141 m.cview, err = restoreView(file.Compaction, compactionHigh, compactionLow, m.tree)
143 return fmt.Errorf("compaction view: %w", err)
146 if m.cview.end != m.chat.end {
147 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
150 if m.chat.end > m.log.Len() {
151 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
157 // restoreQueue adds the work of the messages in the view to the queue. It
158 // builds each node that needs no model call and that a crash left out.
159 func (m *Memory) restoreQueue() error {
160 for id := range m.chat.end {
161 if m.tree.Built(0, id) {
165 leaf, free := freeLeaf(m.log.Message(id))
177 for _, node := range m.tree.Nodes() {
178 if node.Index%2 != 0 {
182 err := m.settle(node)
191 // catchUp adds the messages that the view does not cover yet. A crash can stop
192 // an append after the log write and before the view save.
193 func (m *Memory) catchUp() error {
194 if m.chat.end == m.log.Len() {
198 for m.chat.end < m.log.Len() {
199 err := m.addMessage(m.log.Message(m.chat.end))
208 // Close stops the builds, waits for them, closes the files of the chat, and
209 // releases its lock.
210 func (m *Memory) Close() error {
215 defer m.mutex.Unlock()
222 return errors.Join(err, m.log.Close())
225 // Append logs a new message, adds it to the tree and the views, and starts the
226 // builds that are ready, also the failed ones.
227 func (m *Memory) Append(kind, text string) (Message, error) {
229 defer m.mutex.Unlock()
231 message, err := m.log.Append(kind, text)
233 return Message{}, err
236 err = m.addMessage(message)
238 return Message{}, err
243 return Message{}, err
252 // addMessage builds the leaf of message when it needs no model call, or else
253 // adds the leaf to the queue. Then it appends the leaf to the views.
254 func (m *Memory) addMessage(message Message) error {
255 leaf, free := freeLeaf(message)
262 m.queue.AddLeaf(message.ID)
265 merged := m.chat.Append(m.tree)
266 m.cview.Append(m.tree)
268 m.cview.Coarsen(m.chat, m.tree)
274 // build adds node to the tree and settles its parent.
275 func (m *Memory) build(node Node) error {
276 err := m.tree.Add(node)
281 return m.settle(node)
284 // settle looks at the parent of node when both children are built. It builds
285 // each parent that needs no model call, up the tree, and adds the first other
286 // parent to the queue.
287 func (m *Memory) settle(node Node) error {
289 sibling, built := m.tree.Node(node.Level, node.Index^1)
290 if !built || m.tree.Built(node.Level+1, node.Index/2) {
294 left, right := node, sibling
295 if node.Index%2 != 0 {
296 left, right = sibling, node
299 parent, free := freeMerge(left, right)
301 m.queue.AddMerge(nodeKey{node.Level + 1, node.Index / 2})
305 err := m.tree.Add(parent)
314 // dispatch starts the builds that are ready, up to the limit.
315 func (m *Memory) dispatch() {
316 for m.ctx.Err() == nil {
317 key, ready := m.queue.Next()
328 // task returns the build task of the node key.
329 func (m *Memory) task(key nodeKey) Task {
333 Context: m.context(key.level, key.index),
337 task.Input = []string{leafSource(m.log.Message(key.index))}
341 for _, index := range []int{2 * key.index, 2*key.index + 1} {
342 child, _ := m.tree.Node(key.level-1, index)
343 task.Input = append(task.Input, strings.ReplaceAll(child.Text, "\n", " "))
349 // run builds one node with the summarizer. A failed build stays in the queue
350 // until the next message.
351 func (m *Memory) run(key nodeKey, task Task) {
352 defer m.workers.Done()
354 text, err := m.summarizer.Summarize(m.ctx, task)
357 defer m.mutex.Unlock()
375 m.changed = make(chan struct{})
379 // Wait returns when no build runs. The failed builds wait for the next message.
380 func (m *Memory) Wait(ctx context.Context) error {
383 running := m.queue.Running()
399 // save writes the views to view.json.
400 func (m *Memory) save() error {
401 data, err := json.Marshal(viewFile{
402 Chat: m.chat.State(),
403 Compaction: m.cview.State(),
406 return fmt.Errorf("encode view: %w", err)
409 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
411 return fmt.Errorf("save view: %w", err)
417 func (m *Memory) viewPath() string {
418 return filepath.Join(m.root, "view.json")
421 // View returns the chat view as the model reads it.
422 func (m *Memory) View() string {
424 defer m.mutex.Unlock()
426 return m.chat.Render(m.tree)
429 // Context returns the compaction view for the build of node (l, i). It ends
430 // before the message of a leaf, or after the last message of a merge, and it
431 // stops at the first line that is not built.
432 func (m *Memory) Context(level, index int) string {
434 defer m.mutex.Unlock()
436 return m.context(level, index)
439 func (m *Memory) context(level, index int) string {
442 end = nodeEnd(level, index)
445 return m.cview.Context(m.tree, end)
448 // writeFileAtomic replaces the file at path with data through a temporary file
449 // and a rename. A reader or a crash of the process sees the old file or the new
450 // file, never a part of one.
451 func writeFileAtomic(path string, data []byte) error {
452 file, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
454 return fmt.Errorf("create temporary file: %w", err)
457 _, err = file.Write(data)
458 err = errors.Join(err, file.Close())
460 err = os.Rename(file.Name(), path)
464 return errors.Join(fmt.Errorf("replace file: %w", err), os.Remove(file.Name()))