]> git.giacomolli.uk - onechat/blob - replay_test.go
Replay a synthetic log through the core
[onechat] / replay_test.go
1 package main
2
3 import (
4 "fmt"
5 "math/rand/v2"
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10 "time"
11
12 "github.com/stretchr/testify/require"
13 )
14
15 // syntheticMessages is the length of the synthetic log.
16 const syntheticMessages = 100000
17
18 // TestReplaySyntheticLog runs a synthetic log through the memory core with the
19 // fake summarizer. After each message it waits for the builds, as a turn does.
20 // It checks that each view stays within its sawtooth, that no view line holds a
21 // whole long message or a part of an unbuilt one, and that a restart in the
22 // middle and at the end loads the same views byte for byte.
23 func TestReplaySyntheticLog(t *testing.T) {
24 start := time.Now()
25 root := t.TempDir()
26 clock := newTestClock()
27 random := rand.New(rand.NewPCG(1, 2))
28 memory, err := openMemory(t.Context(), root, clock.Now, newFakeSummarizer())
29 require.NoError(t, err)
30
31 defer func() {
32 require.NoError(t, memory.Close())
33 }()
34
35 batches := 0
36 low := chatHigh
37 for id := range syntheticMessages {
38 if id == syntheticMessages/2 {
39 memory = requireRestart(t, memory, root, clock)
40 }
41
42 clock.now = clock.now.Add(time.Minute)
43 kind, text := syntheticMessage(random, id)
44 lines := viewLines(memory)
45 _, err = memory.Append(kind, text)
46 require.NoError(t, err)
47
48 size, merged := requireViews(t, memory, lines)
49 if merged {
50 batches++
51 low = min(low, size)
52 }
53
54 require.NoError(t, memory.Wait(t.Context()))
55 }
56
57 memory = requireRestart(t, memory, root, clock)
58 require.Equal(t, syntheticMessages, memory.log.Len())
59 require.Greater(t, batches, 0)
60
61 require.NoError(t, memory.Wait(t.Context()))
62 t.Logf("%d messages, %d nodes, %d batches in %s", syntheticMessages, len(memory.tree.nodes), batches, time.Since(start).Round(time.Second))
63 t.Logf("chat view: %d lines, %d bytes, lowest after a batch %d bytes", len(memory.chat.lines), memory.chat.Size(memory.tree), low)
64 t.Logf("compaction view: %d lines, %d bytes", len(memory.cview.lines), memory.cview.Size(memory.tree))
65 }
66
67 // syntheticMessage returns the kind and the text of message id. Most messages
68 // are tool calls and their output. Users write short lines. One output in a
69 // hundred is over 30 KB.
70 func syntheticMessage(random *rand.Rand, id int) (string, string) {
71 roll := random.IntN(100)
72 switch {
73 case roll < 5:
74 return "user", syntheticText(id, 10+random.IntN(200))
75 case roll < 10:
76 return "reply", syntheticText(id, 100+random.IntN(1500))
77 case roll < 12:
78 return "note", syntheticText(id, 50+random.IntN(600))
79 case roll < 13:
80 return "work", syntheticText(id, 300+random.IntN(3000))
81 case roll < 56:
82 return "tool", syntheticText(id, 60+random.IntN(400))
83 case roll < 57:
84 return "echo", syntheticText(id, 30000+random.IntN(30000))
85 default:
86 return "echo", syntheticText(id, 20+random.IntN(4000))
87 }
88 }
89
90 // syntheticText returns a text of about size bytes that starts with its message
91 // ID and holds some non-ASCII characters.
92 func syntheticText(id, size int) string {
93 head := fmt.Sprintf("m%d ", id)
94 words := "ação data line café "
95
96 return head + strings.Repeat(words, max(1, (size-len(head))/len(words)))
97 }
98
99 // requireViews checks the views after a new message, while no build changes the
100 // tree. Each view is at most its high limit, and a batch merges the chat view
101 // to its low limit. It returns the size of the chat view and if a batch merged
102 // it, from the number of lines before the message.
103 func requireViews(t *testing.T, memory *Memory, lines int) (int, bool) {
104 t.Helper()
105
106 memory.mutex.Lock()
107 defer memory.mutex.Unlock()
108
109 size := memory.chat.Size(memory.tree)
110 require.LessOrEqual(t, size, chatHigh)
111 require.LessOrEqual(t, memory.cview.Size(memory.tree), compactionHigh)
112
113 merged := len(memory.chat.lines) < lines
114 if merged {
115 require.LessOrEqual(t, size, chatLow)
116 }
117
118 requireOnlySummaries(t, memory)
119
120 return size, merged
121 }
122
123 // requireOnlySummaries checks each line of the chat view as the model reads it.
124 // A built line holds its node, a long message has a summary and not its text,
125 // and an unbuilt line holds only the pending mark. The caller holds the lock of
126 // memory.
127 func requireOnlySummaries(t *testing.T, memory *Memory) {
128 t.Helper()
129
130 rendered := strings.Split(memory.chat.Render(memory.tree), "\n")
131 require.Len(t, rendered, len(memory.chat.lines)+2)
132
133 for n, line := range memory.chat.lines {
134 head := fmt.Sprintf("%d+%d|", line.index<<line.level, 1<<line.level)
135 node, built := memory.tree.Node(line.level, line.index)
136 if !built {
137 require.Equal(t, 0, line.level)
138 require.Equal(t, head+pending, rendered[n+1])
139
140 continue
141 }
142
143 require.Equal(t, head+strings.ReplaceAll(node.Text, "\n", " "), rendered[n+1])
144 if line.level == 0 {
145 source := leafSource(memory.log.Message(line.index))
146 if len(source) > nodeBytes {
147 require.NotEqual(t, source, node.Text, "message %d", line.index)
148 }
149 }
150 }
151 }
152
153 // viewLines returns the number of lines in the chat view of memory.
154 func viewLines(memory *Memory) int {
155 memory.mutex.Lock()
156 defer memory.mutex.Unlock()
157
158 return len(memory.chat.lines)
159 }
160
161 // requireRestart closes memory, opens it again, and checks that the views and
162 // view.json stay the same byte for byte.
163 func requireRestart(t *testing.T, memory *Memory, root string, clock *testClock) *Memory {
164 t.Helper()
165
166 require.NoError(t, memory.Wait(t.Context()))
167
168 view := memory.View()
169 context := memory.Context(0, memory.log.Len())
170 saved, err := os.ReadFile(filepath.Join(root, "view.json"))
171 require.NoError(t, err)
172 require.NoError(t, memory.Close())
173
174 memory, err = openMemory(t.Context(), root, clock.Now, newFakeSummarizer())
175 require.NoError(t, err)
176 require.NoError(t, memory.Wait(t.Context()))
177 require.Equal(t, view, memory.View())
178 require.Equal(t, context, memory.Context(0, memory.log.Len()))
179
180 loaded, err := os.ReadFile(filepath.Join(root, "view.json"))
181 require.NoError(t, err)
182 require.Equal(t, saved, loaded)
183
184 return memory
185 }