]> git.giacomolli.uk - onechat/blob - replay_test.go
Name the test group in English
[onechat] / replay_test.go
1 package main
2
3 import (
4 "fmt"
5 "math/rand/v2"
6 "os"
7 "path/filepath"
8 "runtime"
9 "strings"
10 "testing"
11 "time"
12
13 "github.com/stretchr/testify/require"
14 )
15
16 const (
17 // replayMessages is the length of the synthetic log.
18 replayMessages = 100000
19
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
23 )
24
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) {
32 start := time.Now()
33 messages := replayMessages
34 if testing.Short() {
35 messages = replayShortMessages
36 }
37
38 root := t.TempDir()
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)
43
44 defer func() {
45 require.NoError(t, memory.Close())
46 }()
47
48 batches := 0
49 low := viewChatHigh
50 long := make([]bool, messages)
51 for id := range messages {
52 if id == messages/2 {
53 memory = replayRequireRestart(t, memory, root, clock)
54 }
55
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)
62
63 size, merged := replayRequireViews(t, memory, lines, long, id%1000 == 0)
64 if merged {
65 batches++
66 low = min(low, size)
67 }
68
69 require.NoError(t, memory.Wait(t.Context()))
70 }
71
72 memory = replayRequireRestart(t, memory, root, clock)
73 require.Equal(t, messages, memory.log.Len())
74 require.Greater(t, batches, 0)
75
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())
80
81 runtime.GC()
82
83 var stats runtime.MemStats
84 runtime.ReadMemStats(&stats)
85 t.Logf("heap in use: %d KB", stats.HeapInuse/1024)
86 }
87
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 {
91 t.Helper()
92
93 require.NoError(t, memory.Wait(t.Context()))
94
95 view := memory.View()
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())
100
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()))
106
107 loaded, err := os.ReadFile(filepath.Join(root, "view.json"))
108 require.NoError(t, err)
109 require.Equal(t, saved, loaded)
110
111 return memory
112 }
113
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
116 // is over 30 KB.
117 func replayMessage(random *rand.Rand, id int) (string, string) {
118 roll := random.IntN(100)
119 switch {
120 case roll < 5:
121 return "user", replayText(id, 10+random.IntN(200))
122 case roll < 10:
123 return "reply", replayText(id, 100+random.IntN(1500))
124 case roll < 12:
125 return "note", replayText(id, 50+random.IntN(600))
126 case roll < 13:
127 return "work", replayText(id, 300+random.IntN(3000))
128 case roll < 56:
129 return "tool", replayText(id, 60+random.IntN(400))
130 case roll < 57:
131 return "echo", replayText(id, 30000+random.IntN(30000))
132 default:
133 return "echo", replayText(id, 20+random.IntN(4000))
134 }
135 }
136
137 // replayViewLines returns the number of lines in the chat view of memory.
138 func replayViewLines(memory *Memory) int {
139 memory.mutex.Lock()
140 defer memory.mutex.Unlock()
141
142 return len(memory.chat.lines)
143 }
144
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) {
152 t.Helper()
153
154 memory.mutex.Lock()
155 defer memory.mutex.Unlock()
156
157 size := replayAppendSize(memory.chat)
158 require.LessOrEqual(t, size, viewChatHigh)
159 require.LessOrEqual(t, replayAppendSize(memory.cview), viewCompactionHigh)
160
161 merged := len(memory.chat.lines) < lines
162 if merged {
163 require.LessOrEqual(t, size, viewChatLow)
164 }
165
166 replayRequireOnlySummaries(t, memory, long, full)
167
168 return size, merged
169 }
170
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é "
176
177 return head + strings.Repeat(words, max(1, (size-len(head))/len(words)))
178 }
179
180 // replayAppendSize returns the size of view with its last line as the pending
181 // mark.
182 func replayAppendSize(view *View) int {
183 last := view.lines[len(view.lines)-1]
184 return view.Size() - view.lineSize(last) + len(viewPending)
185 }
186
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) {
193 t.Helper()
194
195 rendered := strings.Split(memory.chat.Render(), "\n")
196 require.Len(t, rendered, len(memory.chat.lines)+2)
197
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]
201 if full {
202 require.Equal(t, treeIsBuilt(t, memory.tree, line.level, line.index), built)
203 }
204
205 if !built {
206 require.Equal(t, 0, line.level)
207 require.Equal(t, head+viewPending, rendered[n+1])
208
209 continue
210 }
211
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)
215 }
216 }
217 }