]> git.giacomolli.uk - onechat/blob - tree.go
Add local context to chat operation failures
[onechat] / tree.go
1 package main
2
3 import (
4 "cmp"
5 "context"
6 "encoding/binary"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "math/bits"
11 "os"
12 "path/filepath"
13 "slices"
14 "time"
15 "unicode/utf8"
16 )
17
18 // nodeBytes is the size limit of a node text in UTF-8 bytes. A model can go a
19 // few bytes over it, because the view measures the real sizes.
20 const nodeBytes = 512
21
22 // treeRecordBytes is the size of a record of index/tree.idx: the position of
23 // the node line, the node index, and the node level.
24 const treeRecordBytes = 32
25
26 // Tree holds the built nodes of one chat. It writes one JSON line for each node
27 // to tree/YYYY-MM-DD.jsonl, named for the local day of the build. Each node is
28 // built once and never again. A node of a higher level is built only after both
29 // of its children. After a failed write, the tree refuses all writes until it
30 // is opened again. The caller holds the lock of the chat and serializes all
31 // calls.
32 //
33 // The tree keeps no node in memory. The index index/tree.idx lists the node
34 // lines in file order, and index/tree-L.idx holds the position of node (L, i)
35 // in record i, with a zero record for a node that is not built. At open the
36 // tree indexes the lines after the last indexed one, so a missing index is
37 // built again from the day files.
38 type Tree struct {
39 clock func() time.Time
40 journal Journal
41 dir string
42 order *Records
43 levels map[int]*Records
44 failure error
45 }
46
47 // Node is one line of the summary tree. Node (l, i) covers the 2^l messages
48 // from i*2^l on. A node of level 0 holds one message. A node of a higher level
49 // merges its two children, (l-1, 2i) and (l-1, 2i+1). Size is the UTF-8 byte
50 // length of Text.
51 type Node struct {
52 Level int `json:"l"`
53 Index int `json:"i"`
54 Text string `json:"text"`
55 Size int `json:"size"`
56 }
57
58 // NodeKey names the node (l, i).
59 type NodeKey struct {
60 level int
61 index int
62 }
63
64 // openTree opens the tree of the chat in root and indexes its new lines. A chat
65 // of total messages cannot have a node that covers a later message.
66 func openTree(ctx context.Context, root string, total int, clock func() time.Time) (*Tree, error) {
67 for _, dir := range []string{"tree", "index"} {
68 err := os.MkdirAll(filepath.Join(root, dir), 0o700)
69 if err != nil {
70 return nil, fmt.Errorf("create %s directory: %w", dir, err)
71 }
72 }
73
74 t := &Tree{
75 clock: clock,
76 journal: Journal{
77 dir: filepath.Join(root, "tree"),
78 },
79 dir: filepath.Join(root, "index"),
80 levels: make(map[int]*Records),
81 }
82
83 err := t.open(ctx, total)
84 if err != nil {
85 return nil, errors.Join(fmt.Errorf("index tree: %w", err), t.Close())
86 }
87
88 return t, nil
89 }
90
91 func (t *Tree) open(ctx context.Context, total int) error {
92 var err error
93
94 t.order, err = openRecords(filepath.Join(t.dir, "tree.idx"), treeRecordBytes)
95 if err != nil {
96 return fmt.Errorf("open node order index: %w", err)
97 }
98
99 start := Position{}
100 if t.order.count == 0 {
101 err = t.removeLevels()
102 if err != nil {
103 return fmt.Errorf("remove empty level indexes: %w", err)
104 }
105 } else {
106 record, _, err := t.order.Read(t.order.count - 1)
107 if err != nil {
108 return fmt.Errorf("read last node order: %w", err)
109 }
110
111 // A crash can stop an add between the two index writes, so the
112 // last node gets its level record again.
113 node, last := treeDecodeRecord(record)
114 err = t.writeLevel(node, last)
115 if err != nil {
116 return fmt.Errorf("restore last node level: %w", err)
117 }
118
119 start = Position{
120 day: last.day,
121 offset: last.offset + uint64(last.length),
122 }
123 }
124
125 return t.journal.Scan(ctx, start, func(line []byte, place Position) error {
126 var node Node
127
128 err := json.Unmarshal(line, &node)
129 if err != nil {
130 return fmt.Errorf("decode tree node: %w", err)
131 }
132
133 err = t.check(node)
134 if err != nil {
135 return err
136 }
137
138 if nodeEnd(node.Level, node.Index) > total {
139 return fmt.Errorf("node (%d, %d) covers messages after the log", node.Level, node.Index)
140 }
141
142 return t.addIndex(NodeKey{node.Level, node.Index}, place)
143 })
144 }
145
146 // Close closes the files of the tree.
147 func (t *Tree) Close() error {
148 err := t.journal.Close()
149 if t.order != nil {
150 err = errors.Join(err, t.order.Close())
151 t.order = nil
152 }
153
154 for level, index := range t.levels {
155 err = errors.Join(err, index.Close())
156
157 delete(t.levels, level)
158 }
159
160 return err
161 }
162
163 // removeLevels removes the level indexes, which are not valid without the order
164 // index.
165 func (t *Tree) removeLevels() error {
166 paths, err := filepath.Glob(filepath.Join(t.dir, "tree-*.idx"))
167 if err != nil {
168 return fmt.Errorf("list level indexes: %w", err)
169 }
170
171 for _, path := range paths {
172 err = os.Remove(path)
173 if err != nil {
174 return fmt.Errorf("remove level index: %w", err)
175 }
176 }
177
178 return nil
179 }
180
181 // writeLevel writes the position of node to its level index.
182 func (t *Tree) writeLevel(node NodeKey, place Position) error {
183 level, err := t.level(node.level)
184 if err != nil {
185 return fmt.Errorf("open node level index: %w", err)
186 }
187
188 record := make([]byte, positionBytes)
189 encodePosition(record, place)
190
191 return level.Write(node.index, record)
192 }
193
194 // check makes sure that node is valid and can join the tree now.
195 func (t *Tree) check(node Node) error {
196 if node.Level < 0 || node.Level >= bits.UintSize-2 || node.Index < 0 {
197 return fmt.Errorf("node (%d, %d) is out of range", node.Level, node.Index)
198 }
199
200 if node.Text == "" || !utf8.ValidString(node.Text) || node.Size != len(node.Text) {
201 return fmt.Errorf("node (%d, %d) has no valid text of its size", node.Level, node.Index)
202 }
203
204 built, err := t.Built(node.Level, node.Index)
205 if err != nil {
206 return fmt.Errorf("check target node: %w", err)
207 }
208
209 if built {
210 return fmt.Errorf("node (%d, %d) is already built", node.Level, node.Index)
211 }
212
213 if node.Level == 0 {
214 return nil
215 }
216
217 for _, index := range []int{2 * node.Index, 2*node.Index + 1} {
218 built, err = t.Built(node.Level-1, index)
219 if err != nil {
220 return fmt.Errorf("check child node: %w", err)
221 }
222
223 if !built {
224 return fmt.Errorf("node (%d, %d) has a child that is not built", node.Level, node.Index)
225 }
226 }
227
228 return nil
229 }
230
231 // addIndex adds the node line at place to both indexes.
232 func (t *Tree) addIndex(node NodeKey, place Position) error {
233 record := make([]byte, treeRecordBytes)
234 encodePosition(record, place)
235 binary.LittleEndian.PutUint64(record[positionBytes:], uint64(node.index))
236 binary.LittleEndian.PutUint32(record[positionBytes+8:], uint32(node.level))
237
238 err := t.order.Append(record)
239 if err != nil {
240 return fmt.Errorf("append node order: %w", err)
241 }
242
243 return t.writeLevel(node, place)
244 }
245
246 // level returns the index of level, and opens it at first use.
247 func (t *Tree) level(level int) (*Records, error) {
248 index, open := t.levels[level]
249 if open {
250 return index, nil
251 }
252
253 index, err := openRecords(filepath.Join(t.dir, fmt.Sprintf("tree-%d.idx", level)), positionBytes)
254 if err != nil {
255 return nil, err
256 }
257
258 t.levels[level] = index
259
260 return index, nil
261 }
262
263 // Built tells if the node (l, i) is built.
264 func (t *Tree) Built(level, index int) (bool, error) {
265 _, built, err := t.place(level, index)
266 return built, err
267 }
268
269 // place returns the position of the node (l, i) if it is built.
270 func (t *Tree) place(level, index int) (Position, bool, error) {
271 if level < 0 || level >= bits.UintSize-2 || index < 0 {
272 return Position{}, false, nil
273 }
274
275 records, err := t.level(level)
276 if err != nil {
277 return Position{}, false, fmt.Errorf("open node level index: %w", err)
278 }
279
280 record, found, err := records.Read(index)
281 if err != nil || !found {
282 if err != nil {
283 return Position{}, false, fmt.Errorf("read node level record: %w", err)
284 }
285
286 return Position{}, false, nil
287 }
288
289 place := decodePosition(record)
290
291 return place, place.length > 0, nil
292 }
293
294 // Add writes a new node to the tree.
295 func (t *Tree) Add(node Node) error {
296 if t.failure != nil {
297 return fmt.Errorf("tree needs a reopen after a failed write: %w", t.failure)
298 }
299
300 err := t.check(node)
301 if err != nil {
302 return fmt.Errorf("validate node: %w", err)
303 }
304
305 line, err := json.Marshal(node)
306 if err != nil {
307 return fmt.Errorf("encode node: %w", err)
308 }
309
310 place, err := t.journal.Write(t.clock().Format(time.DateOnly), append(line, '\n'))
311 if err == nil {
312 err = t.addIndex(NodeKey{node.Level, node.Index}, place)
313 }
314
315 if err != nil {
316 t.failure = err
317 return fmt.Errorf("write node (%d, %d): %w", node.Level, node.Index, err)
318 }
319
320 return nil
321 }
322
323 // Node reads the node (l, i) if it is built.
324 func (t *Tree) Node(level, index int) (Node, bool, error) {
325 place, built, err := t.place(level, index)
326 if err != nil || !built {
327 if err != nil {
328 return Node{}, false, fmt.Errorf("find node position: %w", err)
329 }
330
331 return Node{}, false, nil
332 }
333
334 line, err := t.journal.Read(place)
335 if err != nil {
336 return Node{}, false, fmt.Errorf("read node (%d, %d): %w", level, index, err)
337 }
338
339 var node Node
340
341 err = json.Unmarshal(line, &node)
342 if err != nil {
343 return Node{}, false, fmt.Errorf("decode node (%d, %d): %w", level, index, err)
344 }
345
346 if node.Level != level || node.Index != index {
347 return Node{}, false, fmt.Errorf("index of node (%d, %d) points to node (%d, %d)", level, index, node.Level, node.Index)
348 }
349
350 return node, true, nil
351 }
352
353 // Keys returns the keys of the built nodes, ordered by level and then by index.
354 func (t *Tree) Keys() ([]NodeKey, error) {
355 keys := make([]NodeKey, 0, t.order.count)
356 for n := range t.order.count {
357 record, _, err := t.order.Read(n)
358 if err != nil {
359 return nil, err
360 }
361
362 key, _ := treeDecodeRecord(record)
363 keys = append(keys, key)
364 }
365
366 slices.SortFunc(keys, func(a, b NodeKey) int {
367 return cmp.Or(cmp.Compare(a.level, b.level), cmp.Compare(a.index, b.index))
368 })
369
370 return keys, nil
371 }
372
373 // Count returns the number of built nodes.
374 func (t *Tree) Count() int {
375 return t.order.count
376 }
377
378 // treeDecodeRecord reads the key and the position of a record of
379 // index/tree.idx.
380 func treeDecodeRecord(record []byte) (NodeKey, Position) {
381 key := NodeKey{
382 level: int(binary.LittleEndian.Uint32(record[positionBytes+8:])),
383 index: int(binary.LittleEndian.Uint64(record[positionBytes:])),
384 }
385
386 return key, decodePosition(record)
387 }
388
389 // nodeEnd returns the ID after the last message of node (l, i).
390 func nodeEnd(level, index int) int {
391 return (index + 1) << level
392 }
393
394 // freeLeaf returns a text-only leaf when its source fits in a node. Images need
395 // a model description even when their text fits.
396 func freeLeaf(message Message) (Node, bool) {
397 text := leafSource(message)
398 if len(text) > nodeBytes || len(imageFiles(message.Text)) > 0 {
399 return Node{}, false
400 }
401
402 return Node{
403 Level: 0,
404 Index: message.ID,
405 Text: text,
406 Size: len(text),
407 }, true
408 }
409
410 // leafSource returns the text that the leaf of message holds or summarizes.
411 func leafSource(message Message) string {
412 return message.Kind + ": " + message.Text
413 }
414
415 // freeMerge returns the parent of two sibling nodes when both texts, joined by
416 // a newline, fit in a node. Such a parent needs no model call.
417 func freeMerge(left, right Node) (Node, bool) {
418 if left.Size+1+right.Size > nodeBytes {
419 return Node{}, false
420 }
421
422 text := left.Text + "\n" + right.Text
423
424 return Node{
425 Level: left.Level + 1,
426 Index: left.Index / 2,
427 Text: text,
428 Size: len(text),
429 }, true
430 }