]> git.giacomolli.uk - onechat/blob - replay_test.go
Fix two comments of the Telegram API and the view
[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 // replayMessages is the length of the synthetic log.
17 const replayMessages = 100000
18
19 // TestReplaySyntheticLog runs a synthetic log through the memory core with the
20 // fake summarizer. After each message it waits for the builds, as a turn does.
21 // It checks that each view stays within its sawtooth, that no view line holds a
22 // whole long message or a part of an unbuilt one, and that a restart in the
23 // middle and at the end loads the same views byte for byte.
24 func TestReplaySyntheticLog(t *testing.T) {
25 start := time.Now()
26 root := t.TempDir()
27 clock := newTestClock()
28 random := rand.New(rand.NewPCG(1, 2))
29 memory, err := openMemory(t.Context(), root, clock.Now, newFakeSummarizer())
30 require.NoError(t, err)
31
32 defer func() {
33 require.NoError(t, memory.Close())
34 }()
35
36 batches := 0
37 low := viewChatHigh
38 long := make([]bool, replayMessages)
39 for id := range replayMessages {
40 if id == replayMessages/2 {
41 memory = replayRequireRestart(t, memory, root, clock)
42 }
43
44 clock.now = clock.now.Add(time.Minute)
45 kind, text := replayMessage(random, id)
46 long[id] = len(kind)+len(": ")+len(text) > nodeBytes
47 lines := replayViewLines(memory)
48 _, err = memory.Append(kind, text)
49 require.NoError(t, err)
50
51 size, merged := replayRequireViews(t, memory, lines, long, id%1000 == 0)
52 if merged {
53 batches++
54 low = min(low, size)
55 }
56
57 require.NoError(t, memory.Wait(t.Context()))
58 }
59
60 memory = replayRequireRestart(t, memory, root, clock)
61 require.Equal(t, replayMessages, memory.log.Len())
62 require.Greater(t, batches, 0)
63
64 require.NoError(t, memory.Wait(t.Context()))
65 t.Logf("%d messages, %d nodes, %d batches in %s", replayMessages, memory.tree.Count(), batches, time.Since(start).Round(time.Second))
66 t.Logf("chat view: %d lines, %d bytes, lowest after a batch %d bytes", len(memory.chat.lines), memory.chat.Size(), low)
67 t.Logf("compaction view: %d lines, %d bytes", len(memory.cview.lines), memory.cview.Size())
68
69 runtime.GC()
70
71 var stats runtime.MemStats
72 runtime.ReadMemStats(&stats)
73 t.Logf("heap in use: %d KB", stats.HeapInuse/1024)
74 }
75
76 // replayRequireRestart closes memory, opens it again, and checks that the views
77 // and view.json stay the same byte for byte.
78 func replayRequireRestart(t *testing.T, memory *Memory, root string, clock *TestClock) *Memory {
79 t.Helper()
80
81 require.NoError(t, memory.Wait(t.Context()))
82
83 view := memory.View()
84 context := memory.Context(0, memory.log.Len())
85 saved, err := os.ReadFile(filepath.Join(root, "view.json"))
86 require.NoError(t, err)
87 require.NoError(t, memory.Close())
88
89 memory, err = openMemory(t.Context(), root, clock.Now, newFakeSummarizer())
90 require.NoError(t, err)
91 require.NoError(t, memory.Wait(t.Context()))
92 require.Equal(t, view, memory.View())
93 require.Equal(t, context, memory.Context(0, memory.log.Len()))
94
95 loaded, err := os.ReadFile(filepath.Join(root, "view.json"))
96 require.NoError(t, err)
97 require.Equal(t, saved, loaded)
98
99 return memory
100 }
101
102 // replayMessage returns the kind and the text of message id. Most messages are
103 // tool calls and their output. Users write short lines. One output in a hundred
104 // is over 30 KB.
105 func replayMessage(random *rand.Rand, id int) (string, string) {
106 roll := random.IntN(100)
107 switch {
108 case roll < 5:
109 return "user", replayText(id, 10+random.IntN(200))
110 case roll < 10:
111 return "reply", replayText(id, 100+random.IntN(1500))
112 case roll < 12:
113 return "note", replayText(id, 50+random.IntN(600))
114 case roll < 13:
115 return "work", replayText(id, 300+random.IntN(3000))
116 case roll < 56:
117 return "tool", replayText(id, 60+random.IntN(400))
118 case roll < 57:
119 return "echo", replayText(id, 30000+random.IntN(30000))
120 default:
121 return "echo", replayText(id, 20+random.IntN(4000))
122 }
123 }
124
125 // replayViewLines returns the number of lines in the chat view of memory.
126 func replayViewLines(memory *Memory) int {
127 memory.mutex.Lock()
128 defer memory.mutex.Unlock()
129
130 return len(memory.chat.lines)
131 }
132
133 // replayRequireViews checks the views after a new message, and with full
134 // compares them with the tree. Each view is at most its high limit, and a batch
135 // merges the chat view to its low limit. The leaf of the new message can be
136 // built after the append, so the sizes count it as the pending mark, as the
137 // append did. It returns the size of the chat view and if a batch merged it,
138 // from the number of lines before the message.
139 func replayRequireViews(t *testing.T, memory *Memory, lines int, long []bool, full bool) (int, bool) {
140 t.Helper()
141
142 memory.mutex.Lock()
143 defer memory.mutex.Unlock()
144
145 size := replayAppendSize(memory.chat)
146 require.LessOrEqual(t, size, viewChatHigh)
147 require.LessOrEqual(t, replayAppendSize(memory.cview), viewCompactionHigh)
148
149 merged := len(memory.chat.lines) < lines
150 if merged {
151 require.LessOrEqual(t, size, viewChatLow)
152 }
153
154 replayRequireOnlySummaries(t, memory, long, full)
155
156 return size, merged
157 }
158
159 // replayText returns a text of about size bytes that starts with its message ID
160 // and holds some non-ASCII characters.
161 func replayText(id, size int) string {
162 head := fmt.Sprintf("m%d ", id)
163 words := "ação data line café "
164
165 return head + strings.Repeat(words, max(1, (size-len(head))/len(words)))
166 }
167
168 // replayAppendSize returns the size of view with its last line as the pending
169 // mark.
170 func replayAppendSize(view *View) int {
171 last := view.lines[len(view.lines)-1]
172 return view.Size() - view.lineSize(last) + len(viewPending)
173 }
174
175 // replayRequireOnlySummaries checks each line of the chat view as the model
176 // reads it. A built line holds its node, a long message has a summary of the
177 // fake summarizer and not its text, and an unbuilt line holds only the pending
178 // mark. With full, it also checks that the view keeps the node of each built
179 // line. The caller holds the lock of memory.
180 func replayRequireOnlySummaries(t *testing.T, memory *Memory, long []bool, full bool) {
181 t.Helper()
182
183 rendered := strings.Split(memory.chat.Render(), "\n")
184 require.Len(t, rendered, len(memory.chat.lines)+2)
185
186 for n, line := range memory.chat.lines {
187 head := fmt.Sprintf("%d+%d|", line.index<<line.level, 1<<line.level)
188 node, built := memory.chat.nodes[line]
189 if full {
190 require.Equal(t, treeIsBuilt(t, memory.tree, line.level, line.index), built)
191 }
192
193 if !built {
194 require.Equal(t, 0, line.level)
195 require.Equal(t, head+viewPending, rendered[n+1])
196
197 continue
198 }
199
200 require.Equal(t, head+strings.ReplaceAll(node.Text, "\n", " "), rendered[n+1])
201 if line.level == 0 && long[line.index] {
202 require.True(t, strings.HasPrefix(node.Text, "summary "), "message %d", line.index)
203 }
204 }
205 }