arbo/vt.go
vt.goRaw
1// Package arbo > vt.go implements the Virtual Tree, which computes a tree
2// without computing any hash. With the idea of once all the leafs are placed in
3// their positions, the hashes can be computed, avoiding computing a node hash
4// more than one time.
5package arbo
6
7import (
8 "bytes"
9 "encoding/hex"
10 "fmt"
11 "io"
12 "math"
13 "runtime"
14 "sync"
15)
16
17type node struct {
18 l *node
19 r *node
20 k []byte
21 v []byte
22 path []bool
23 h []byte
24}
25
26type params struct {
27 maxLevels int
28 hashFunction HashFunction
29 emptyHash []byte
30 dbg *dbgStats
31}
32
33type kv struct {
34 pos int // original position in the inputted array
35 keyPath []byte
36 k []byte
37 v []byte
38}
39
40func (p *params) keysValuesToKvs(ks, vs [][]byte) ([]kv, error) {
41 if len(ks) != len(vs) {
42 return nil, fmt.Errorf("len(keys)!=len(values) (%d!=%d)",
43 len(ks), len(vs))
44 }
45 kvs := make([]kv, len(ks))
46 for i := 0; i < len(ks); i++ {
47 keyPath := make([]byte, p.hashFunction.Len())
48 copy(keyPath[:], ks[i])
49 kvs[i].pos = i
50 kvs[i].keyPath = keyPath
51 kvs[i].k = ks[i]
52 kvs[i].v = vs[i]
53 }
54
55 return kvs, nil
56}
57
58// vt stands for virtual tree. It's a tree that does not have any computed hash
59// while placing the leafs. Once all the leafs are placed, it computes all the
60// hashes. In this way, each node hash is only computed one time (at the end)
61// and the tree is computed in memory.
62type vt struct {
63 root *node
64 params *params
65}
66
67func newVT(maxLevels int, hash HashFunction) vt {
68 return vt{
69 root: nil,
70 params: ¶ms{
71 maxLevels: maxLevels,
72 hashFunction: hash,
73 emptyHash: make([]byte, hash.Len()), // empty
74 },
75 }
76}
77
78// addBatch adds a batch of key-values to the VirtualTree. Returns an array
79// containing the indexes of the keys failed to add. Does not include the
80// computation of hashes of the nodes neither the storage of the key-values of
81// the tree into the db. After addBatch, vt.computeHashes should be called to
82// compute the hashes of all the nodes of the tree.
83func (t *vt) addBatch(ks, vs [][]byte) ([]int, error) {
84 nCPU := flp2(runtime.NumCPU())
85 if nCPU == 1 || len(ks) < nCPU {
86 var invalids []int
87 for i := 0; i < len(ks); i++ {
88 if err := t.add(0, ks[i], vs[i]); err != nil {
89 invalids = append(invalids, i)
90 }
91 }
92 return invalids, nil
93 }
94
95 l := int(math.Log2(float64(nCPU)))
96
97 kvs, err := t.params.keysValuesToKvs(ks, vs)
98 if err != nil {
99 return nil, err
100 }
101
102 buckets := splitInBuckets(kvs, nCPU)
103
104 nodesAtL, err := t.getNodesAtLevel(l)
105 if err != nil {
106 return nil, err
107 }
108 if len(nodesAtL) != nCPU && t.root != nil {
109 /*
110 Already populated Tree but Unbalanced
111 - Need to fill M1 and M2, and then will be able to continue with the flow
112 - Search for M1 & M2 in the inputed Keys
113 - Add M1 & M2 to the Tree
114 - From here can continue with the flow
115
116 R
117 / \
118 / \
119 / \
120 * *
121 | \
122 | \
123 | \
124 L: M1 * M2 * (where M1 and M2 are empty)
125 / | /
126 / | /
127 / | /
128 A * *
129 / \ | \
130 / \ | \
131 / \ | \
132 B * * C
133 / \ |\
134 ... ... | \
135 | \
136 D E
137 */
138
139 // add one key at each bucket, and then continue with the flow
140 for i := 0; i < len(buckets); i++ {
141 // add one leaf of the bucket, if there is an error when
142 // adding the k-v, try to add the next one of the bucket
143 // (until one is added)
144 inserted := -1
145 for j := 0; j < len(buckets[i]); j++ {
146 if err := t.add(0, buckets[i][j].k, buckets[i][j].v); err == nil {
147 inserted = j
148 break
149 }
150 }
151
152 // remove the inserted element from buckets[i]
153 // fmt.Println("rm-ins", inserted)
154 if inserted != -1 {
155 buckets[i] = append(buckets[i][:inserted], buckets[i][inserted+1:]...)
156 }
157 }
158 nodesAtL, err = t.getNodesAtLevel(l)
159 if err != nil {
160 return nil, err
161 }
162 }
163 if len(nodesAtL) != nCPU {
164 panic("should not happen") // TODO TMP
165 }
166
167 subRoots := make([]*node, nCPU)
168 invalidsInBucket := make([][]int, nCPU)
169
170 var wg sync.WaitGroup
171 wg.Add(nCPU)
172 for i := 0; i < nCPU; i++ {
173 go func(cpu int) {
174 bucketVT := newVT(t.params.maxLevels-l, t.params.hashFunction)
175 bucketVT.root = nodesAtL[cpu]
176 for j := 0; j < len(buckets[cpu]); j++ {
177 if err = bucketVT.add(l, buckets[cpu][j].k, buckets[cpu][j].v); err != nil {
178 invalidsInBucket[cpu] = append(invalidsInBucket[cpu], buckets[cpu][j].pos)
179 }
180 }
181 subRoots[cpu] = bucketVT.root
182 wg.Done()
183 }(i)
184 }
185 wg.Wait()
186
187 var invalids []int
188 for i := 0; i < len(invalidsInBucket); i++ {
189 invalids = append(invalids, invalidsInBucket[i]...)
190 }
191
192 newRootNode, err := upFromNodes(subRoots)
193 if err != nil {
194 return nil, err
195 }
196 t.root = newRootNode
197
198 return invalids, nil
199}
200
201func (t *vt) getNodesAtLevel(l int) ([]*node, error) {
202 if t.root == nil {
203 var r []*node
204 nChilds := int(math.Pow(2, float64(l))) //nolint:gomnd
205 for i := 0; i < nChilds; i++ {
206 r = append(r, nil)
207 }
208 return r, nil
209 }
210 return t.root.getNodesAtLevel(0, l)
211}
212
213func (n *node) getNodesAtLevel(currLvl, l int) ([]*node, error) {
214 if n == nil {
215 var r []*node
216 nChilds := int(math.Pow(2, float64(l-currLvl))) //nolint:gomnd
217 for i := 0; i < nChilds; i++ {
218 r = append(r, nil)
219 }
220 return r, nil
221 }
222
223 typ := n.typ()
224 if currLvl == l && typ != vtEmpty {
225 return []*node{n}, nil
226 }
227 if currLvl >= l {
228 panic("should not reach this point") // TODO TMP
229 }
230
231 var nodes []*node
232
233 nodesL, err := n.l.getNodesAtLevel(currLvl+1, l)
234 if err != nil {
235 return nil, err
236 }
237 nodes = append(nodes, nodesL...)
238
239 nodesR, err := n.r.getNodesAtLevel(currLvl+1, l)
240 if err != nil {
241 return nil, err
242 }
243 nodes = append(nodes, nodesR...)
244
245 return nodes, nil
246}
247
248func upFromNodes(ns []*node) (*node, error) {
249 if len(ns) == 1 {
250 return ns[0], nil
251 }
252
253 var res []*node
254 for i := 0; i < len(ns); i += 2 {
255 if ns[i].typ() == vtEmpty && ns[i+1].typ() == vtEmpty {
256 // if ns[i] == nil && ns[i+1] == nil {
257 // when both sub nodes are empty, the node is also empty
258 res = append(res, ns[i]) // empty node
259 continue
260 }
261 n := &node{
262 l: ns[i],
263 r: ns[i+1],
264 }
265 res = append(res, n)
266 }
267 return upFromNodes(res)
268}
269
270func (t *vt) add(fromLvl int, k, v []byte) error {
271 leaf := newLeafNode(t.params, k, v)
272 if t.root == nil {
273 t.root = leaf
274 return nil
275 }
276
277 if err := t.root.add(t.params, fromLvl, leaf); err != nil {
278 return err
279 }
280
281 return nil
282}
283
284// computeHashes should be called after all the vt.add is used, once all the
285// leafs are in the tree
286func (t *vt) computeHashes() ([][2][]byte, error) {
287 var err error
288
289 nCPU := flp2(runtime.NumCPU())
290 l := int(math.Log2(float64(nCPU)))
291 nodesAtL, err := t.getNodesAtLevel(l)
292 if err != nil {
293 return nil, err
294 }
295 subRoots := make([]*node, nCPU)
296 bucketPairs := make([][][2][]byte, nCPU)
297 dbgStatsPerBucket := make([]*dbgStats, nCPU)
298
299 var wg sync.WaitGroup
300 wg.Add(nCPU)
301 for i := 0; i < nCPU; i++ {
302 go func(cpu int) {
303 bucketVT := newVT(t.params.maxLevels-l, t.params.hashFunction)
304 bucketVT.params.dbg = newDbgStats()
305 bucketVT.root = nodesAtL[cpu]
306
307 bucketPairs[cpu], err = bucketVT.root.computeHashes(l,
308 t.params.maxLevels, bucketVT.params, bucketPairs[cpu])
309 if err != nil {
310 // TODO WIP
311 panic("TODO" + err.Error())
312 }
313
314 subRoots[cpu] = bucketVT.root
315 dbgStatsPerBucket[cpu] = bucketVT.params.dbg
316 wg.Done()
317 }(i)
318 }
319 wg.Wait()
320
321 for i := 0; i < len(dbgStatsPerBucket); i++ {
322 t.params.dbg.add(dbgStatsPerBucket[i])
323 }
324
325 var pairs [][2][]byte
326 for i := 0; i < len(bucketPairs); i++ {
327 pairs = append(pairs, bucketPairs[i]...)
328 }
329
330 nodesAtL, err = t.getNodesAtLevel(l)
331 if err != nil {
332 return nil, err
333 }
334 for i := 0; i < len(nodesAtL); i++ {
335 nodesAtL = subRoots
336 }
337
338 pairs, err = t.root.computeHashes(0, l, t.params, pairs)
339 if err != nil {
340 return nil, err
341 }
342
343 return pairs, nil
344}
345
346func newLeafNode(p *params, k, v []byte) *node {
347 keyPath := make([]byte, p.hashFunction.Len())
348 copy(keyPath[:], k)
349 path := getPath(p.maxLevels, keyPath)
350 n := &node{
351 k: k,
352 v: v,
353 path: path,
354 }
355 return n
356}
357
358type virtualNodeType int
359
360const (
361 vtEmpty = 0 // for convenience uses same value that PrefixValueEmpty
362 vtLeaf = 1 // for convenience uses same value that PrefixValueLeaf
363 vtMid = 2 // for convenience uses same value that PrefixValueIntermediate
364)
365
366func (n *node) typ() virtualNodeType {
367 if n == nil {
368 return vtEmpty // TODO decide if return 'vtEmpty' or an error
369 }
370 if n.l == nil && n.r == nil && n.k != nil {
371 return vtLeaf
372 }
373 if n.l != nil || n.r != nil {
374 return vtMid
375 }
376 return vtEmpty
377}
378
379func (n *node) add(p *params, currLvl int, leaf *node) error {
380 if currLvl > p.maxLevels-1 {
381 return ErrMaxVirtualLevel
382 }
383
384 if n == nil {
385 // n = leaf // TMP!
386 return nil
387 }
388
389 t := n.typ()
390 switch t {
391 case vtMid:
392 if leaf.path[currLvl] {
393 //right
394 if n.r == nil {
395 // empty sub-node, add the leaf here
396 n.r = leaf
397 return nil
398 }
399 if err := n.r.add(p, currLvl+1, leaf); err != nil {
400 return err
401 }
402 } else {
403 if n.l == nil {
404 // empty sub-node, add the leaf here
405 n.l = leaf
406 return nil
407 }
408 if err := n.l.add(p, currLvl+1, leaf); err != nil {
409 return err
410 }
411 }
412 case vtLeaf:
413 if bytes.Equal(n.k, leaf.k) {
414 return fmt.Errorf("%s. Existing node: %s, trying to add node: %s",
415 ErrKeyAlreadyExists, hex.EncodeToString(n.k),
416 hex.EncodeToString(leaf.k))
417 }
418
419 oldLeaf := &node{
420 k: n.k,
421 v: n.v,
422 path: n.path,
423 }
424 // remove values from current node (converting it to mid node)
425 n.k = nil
426 n.v = nil
427 n.h = nil
428 n.path = nil
429 if err := n.downUntilDivergence(p, currLvl, oldLeaf, leaf); err != nil {
430 return err
431 }
432 case vtEmpty:
433 panic(fmt.Errorf("EMPTY %v", n)) // TODO TMP
434 default:
435 return fmt.Errorf("ERR") // TODO TMP
436 }
437
438 return nil
439}
440
441func (n *node) downUntilDivergence(p *params, currLvl int, oldLeaf, newLeaf *node) error {
442 if currLvl > p.maxLevels-1 {
443 return ErrMaxVirtualLevel
444 }
445
446 if oldLeaf.path[currLvl] != newLeaf.path[currLvl] {
447 // reached divergence in next level
448 if newLeaf.path[currLvl] {
449 n.l = oldLeaf
450 n.r = newLeaf
451 } else {
452 n.l = newLeaf
453 n.r = oldLeaf
454 }
455 return nil
456 }
457 // no divergence yet, continue going down
458 if newLeaf.path[currLvl] {
459 // right
460 n.r = &node{}
461 if err := n.r.downUntilDivergence(p, currLvl+1, oldLeaf, newLeaf); err != nil {
462 return err
463 }
464 } else {
465 // left
466 n.l = &node{}
467 if err := n.l.downUntilDivergence(p, currLvl+1, oldLeaf, newLeaf); err != nil {
468 return err
469 }
470 }
471
472 return nil
473}
474
475func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
476 buckets := make([][]kv, nBuckets)
477 // 1. classify the keyvalues into buckets
478 for i := 0; i < len(kvs); i++ {
479 pair := kvs[i]
480
481 // bucketnum := keyToBucket(pair.k, nBuckets)
482 bucketnum := keyToBucket(pair.keyPath, nBuckets)
483 buckets[bucketnum] = append(buckets[bucketnum], pair)
484 }
485 return buckets
486}
487
488// TODO rename in a more 'real' name (calculate bucket from/for key)
489func keyToBucket(k []byte, nBuckets int) int {
490 nLevels := int(math.Log2(float64(nBuckets)))
491 b := make([]int, nBuckets)
492 for i := 0; i < nBuckets; i++ {
493 b[i] = i
494 }
495 r := b
496 mid := len(r) / 2 //nolint:gomnd
497 for i := 0; i < nLevels; i++ {
498 if int(k[i/8]&(1<<(i%8))) != 0 {
499 r = r[mid:]
500 mid = len(r) / 2 //nolint:gomnd
501 } else {
502 r = r[:mid]
503 mid = len(r) / 2 //nolint:gomnd
504 }
505 }
506 return r[0]
507}
508
509// flp2 computes the floor power of 2, the highest power of 2 under the given
510// value.
511func flp2(n int) int {
512 res := 0
513 for i := n; i >= 1; i-- {
514 if (i & (i - 1)) == 0 {
515 res = i
516 break
517 }
518 }
519 return res
520}
521
522// returns an array of key-values to store in the db
523func (n *node) computeHashes(currLvl, maxLvl int, p *params, pairs [][2][]byte) (
524 [][2][]byte, error) {
525 if n == nil || currLvl >= maxLvl {
526 // no need to compute any hash
527 return pairs, nil
528 }
529 if pairs == nil {
530 pairs = [][2][]byte{}
531 }
532 var err error
533 t := n.typ()
534 switch t {
535 case vtLeaf:
536 p.dbg.incHash()
537 leafKey, leafValue, err := newLeafValue(p.hashFunction, n.k, n.v)
538 if err != nil {
539 return pairs, err
540 }
541 n.h = leafKey
542 kv := [2][]byte{leafKey, leafValue}
543 pairs = append(pairs, kv)
544 case vtMid:
545 if n.l != nil {
546 pairs, err = n.l.computeHashes(currLvl+1, maxLvl, p, pairs)
547 if err != nil {
548 return pairs, err
549 }
550 } else {
551 n.l = &node{
552 h: p.emptyHash,
553 }
554 }
555 if n.r != nil {
556 pairs, err = n.r.computeHashes(currLvl+1, maxLvl, p, pairs)
557 if err != nil {
558 return pairs, err
559 }
560 } else {
561 n.r = &node{
562 h: p.emptyHash,
563 }
564 }
565 // once the sub nodes are computed, can compute the current node
566 // hash
567 p.dbg.incHash()
568 k, v, err := newIntermediate(p.hashFunction, n.l.h, n.r.h)
569 if err != nil {
570 return nil, err
571 }
572 n.h = k
573 kv := [2][]byte{k, v}
574 pairs = append(pairs, kv)
575 case vtEmpty:
576 default:
577 return nil, fmt.Errorf("ERR:n.computeHashes type (%d) no match", t) // TODO TMP
578 }
579
580 return pairs, nil
581}
582
583//nolint:unused
584func (t *vt) graphviz(w io.Writer) error {
585 fmt.Fprintf(w, `digraph hierarchy {
586node [fontname=Monospace,fontsize=10,shape=box]
587`)
588 if _, err := t.root.graphviz(w, t.params, 0); err != nil {
589 return err
590 }
591 fmt.Fprintf(w, "}\n")
592 return nil
593}
594
595//nolint:unused
596func (n *node) graphviz(w io.Writer, p *params, nEmpties int) (int, error) {
597 if n == nil {
598 return nEmpties, nil
599 }
600
601 t := n.typ()
602 switch t {
603 case vtLeaf:
604 leafKey, _, err := newLeafValue(p.hashFunction, n.k, n.v)
605 if err != nil {
606 return nEmpties, err
607 }
608 fmt.Fprintf(w, "\"%p\" [style=filled,label=\"%v\"];\n", n, hex.EncodeToString(leafKey[:nChars]))
609
610 fmt.Fprintf(w, "\"%p\" -> {\"k:%v\\nv:%v\"}\n", n,
611 hex.EncodeToString(n.k[:nChars]),
612 hex.EncodeToString(n.v[:nChars]))
613 fmt.Fprintf(w, "\"k:%v\\nv:%v\" [style=dashed]\n",
614 hex.EncodeToString(n.k[:nChars]),
615 hex.EncodeToString(n.v[:nChars]))
616 case vtMid:
617 fmt.Fprintf(w, "\"%p\" [label=\"\"];\n", n)
618
619 lStr := fmt.Sprintf("%p", n.l)
620 rStr := fmt.Sprintf("%p", n.r)
621 eStr := ""
622 if n.l == nil {
623 lStr = fmt.Sprintf("empty%v", nEmpties)
624 eStr += fmt.Sprintf("\"%v\" [style=dashed,label=0];\n",
625 lStr)
626 nEmpties++
627 }
628 if n.r == nil {
629 rStr = fmt.Sprintf("empty%v", nEmpties)
630 eStr += fmt.Sprintf("\"%v\" [style=dashed,label=0];\n",
631 rStr)
632 nEmpties++
633 }
634 fmt.Fprintf(w, "\"%p\" -> {\"%v\" \"%v\"}\n", n, lStr, rStr)
635 fmt.Fprint(w, eStr)
636 nEmpties, err := n.l.graphviz(w, p, nEmpties)
637 if err != nil {
638 return nEmpties, err
639 }
640 nEmpties, err = n.r.graphviz(w, p, nEmpties)
641 if err != nil {
642 return nEmpties, err
643 }
644
645 case vtEmpty:
646 default:
647 return nEmpties, fmt.Errorf("ERR")
648 }
649
650 return nEmpties, nil
651}
652
653//nolint:unused
654func (t *vt) printGraphviz() error {
655 w := bytes.NewBufferString("")
656 fmt.Fprintf(w,
657 "--------\nGraphviz:\n")
658 err := t.graphviz(w)
659 if err != nil {
660 fmt.Println(w)
661 return err
662 }
663 fmt.Fprintf(w,
664 "End of Graphviz --------\n")
665 fmt.Println(w)
666 return nil
667}