13 "github.com/stretchr/testify/require"
17 // replayMessages is the length of the synthetic log.
18 replayMessages = 100000
20 // replayShortMessages is the length of the synthetic log with -short.
21 // It is long enough for batches of the chat view.
22 replayShortMessages = 5000
25 // TestReplaySyntheticLog runs a synthetic log through the memory core with the
26 // fake summarizer. After each message it waits for the builds, as a turn does.
27 // It checks that each view stays within its sawtooth, that no view line holds a
28 // whole long message or a part of an unbuilt one, and that a restart in the
29 // middle and at the end loads the same views byte for byte. With -short, the
30 // log is shorter, and the test still requires a batch of the chat view.
31 func TestReplaySyntheticLog(t *testing.T) {
33 messages := replayMessages
35 messages = replayShortMessages
39 clock := newTestClock()
40 random := rand.New(rand.NewPCG(1, 2))
41 memory, err := openMemory(t.Context(), root, clock.Now, newFakeSummarizer(), discardLog())
42 require.NoError(t, err)
45 require.NoError(t, memory.Close())
50 long := make([]bool, messages)
51 for id := range messages {
53 memory = replayRequireRestart(t, memory, root, clock)
56 clock.now = clock.now.Add(time.Minute)
57 kind, text := replayMessage(random, id)
58 long[id] = len(kind)+len(": ")+len(text) > nodeBytes
59 lines := replayViewLines(memory)
60 _, err = memory.Append(kind, text)
61 require.NoError(t, err)
63 size, merged := replayRequireViews(t, memory, lines, long, id%1000 == 0)
69 require.NoError(t, memory.Wait(t.Context()))
72 memory = replayRequireRestart(t, memory, root, clock)
73 require.Equal(t, messages, memory.log.Len())
74 require.Greater(t, batches, 0)
76 require.NoError(t, memory.Wait(t.Context()))
77 t.Logf("%d messages, %d nodes, %d batches in %s", messages, memory.tree.Count(), batches, time.Since(start).Round(time.Second))
78 t.Logf("chat view: %d lines, %d bytes, lowest after a batch %d bytes", len(memory.chat.lines), memory.chat.Size(), low)
79 t.Logf("compaction view: %d lines, %d bytes", len(memory.cview.lines), memory.cview.Size())
83 var stats runtime.MemStats
84 runtime.ReadMemStats(&stats)
85 t.Logf("heap in use: %d KB", stats.HeapInuse/1024)
88 // replayRequireRestart closes memory, opens it again, and checks that the views
89 // and view.json stay the same byte for byte.
90 func replayRequireRestart(t *testing.T, memory *Memory, root string, clock *TestClock) *Memory {
93 require.NoError(t, memory.Wait(t.Context()))
96 context := memory.Context(0, memory.log.Len())
97 saved, err := os.ReadFile(filepath.Join(root, "view.json"))
98 require.NoError(t, err)
99 require.NoError(t, memory.Close())
101 memory, err = openMemory(t.Context(), root, clock.Now, newFakeSummarizer(), discardLog())
102 require.NoError(t, err)
103 require.NoError(t, memory.Wait(t.Context()))
104 require.Equal(t, view, memory.View())
105 require.Equal(t, context, memory.Context(0, memory.log.Len()))
107 loaded, err := os.ReadFile(filepath.Join(root, "view.json"))
108 require.NoError(t, err)
109 require.Equal(t, saved, loaded)
114 // replayMessage returns the kind and the text of message id. Most messages are
115 // tool calls and their output. Users write short lines. One output in a hundred
117 func replayMessage(random *rand.Rand, id int) (string, string) {
118 roll := random.IntN(100)
121 return "user", replayText(id, 10+random.IntN(200))
123 return "reply", replayText(id, 100+random.IntN(1500))
125 return "note", replayText(id, 50+random.IntN(600))
127 return "work", replayText(id, 300+random.IntN(3000))
129 return "tool", replayText(id, 60+random.IntN(400))
131 return "echo", replayText(id, 30000+random.IntN(30000))
133 return "echo", replayText(id, 20+random.IntN(4000))
137 // replayViewLines returns the number of lines in the chat view of memory.
138 func replayViewLines(memory *Memory) int {
140 defer memory.mutex.Unlock()
142 return len(memory.chat.lines)
145 // replayRequireViews checks the views after a new message, and with full
146 // compares them with the tree. Each view is at most its high limit, and a batch
147 // merges the chat view to its low limit. The leaf of the new message can be
148 // built after the append, so the sizes count it as the pending mark, as the
149 // append did. It returns the size of the chat view and if a batch merged it,
150 // from the number of lines before the message.
151 func replayRequireViews(t *testing.T, memory *Memory, lines int, long []bool, full bool) (int, bool) {
155 defer memory.mutex.Unlock()
157 size := replayAppendSize(memory.chat)
158 require.LessOrEqual(t, size, viewChatHigh)
159 require.LessOrEqual(t, replayAppendSize(memory.cview), viewCompactionHigh)
161 merged := len(memory.chat.lines) < lines
163 require.LessOrEqual(t, size, viewChatLow)
166 replayRequireOnlySummaries(t, memory, long, full)
171 // replayText returns a text of about size bytes that starts with its message ID
172 // and holds some non-ASCII characters.
173 func replayText(id, size int) string {
174 head := fmt.Sprintf("m%d ", id)
175 words := "ação data line café "
177 return head + strings.Repeat(words, max(1, (size-len(head))/len(words)))
180 // replayAppendSize returns the size of view with its last line as the pending
182 func replayAppendSize(view *View) int {
183 last := view.lines[len(view.lines)-1]
184 return view.Size() - view.lineSize(last) + len(viewPending)
187 // replayRequireOnlySummaries checks each line of the chat view as the model
188 // reads it. A built line holds its node, a long message has a summary of the
189 // fake summarizer and not its text, and an unbuilt line holds only the pending
190 // mark. With full, it also checks that the view keeps the node of each built
191 // line. The caller holds the lock of memory.
192 func replayRequireOnlySummaries(t *testing.T, memory *Memory, long []bool, full bool) {
195 rendered := strings.Split(memory.chat.Render(), "\n")
196 require.Len(t, rendered, len(memory.chat.lines)+2)
198 for n, line := range memory.chat.lines {
199 head := fmt.Sprintf("%d+%d|", line.index<<line.level, 1<<line.level)
200 node, built := memory.chat.nodes[line]
202 require.Equal(t, treeIsBuilt(t, memory.tree, line.level, line.index), built)
206 require.Equal(t, 0, line.level)
207 require.Equal(t, head+viewPending, rendered[n+1])
212 require.Equal(t, head+strings.ReplaceAll(node.Text, "\n", " "), rendered[n+1])
213 if line.level == 0 && long[line.index] {
214 require.True(t, strings.HasPrefix(node.Text, "summary "), "message %d", line.index)