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 fmt.Errorf("max virtual level %d", currLvl)
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("key already exists. Existing node: %s, trying to add node: %s",
415 hex.EncodeToString(n.k), hex.EncodeToString(leaf.k))
416 }
417
418 oldLeaf := &node{
419 k: n.k,
420 v: n.v,
421 path: n.path,
422 }
423 // remove values from current node (converting it to mid node)
424 n.k = nil
425 n.v = nil
426 n.h = nil
427 n.path = nil
428 if err := n.downUntilDivergence(p, currLvl, oldLeaf, leaf); err != nil {
429 return err
430 }
431 case vtEmpty:
432 panic(fmt.Errorf("EMPTY %v", n)) // TODO TMP
433 default:
434 return fmt.Errorf("ERR") // TODO TMP
435 }
436
437 return nil
438}
439
440func (n *node) downUntilDivergence(p *params, currLvl int, oldLeaf, newLeaf *node) error {
441 if currLvl > p.maxLevels-1 {
442 return fmt.Errorf("max virtual level %d", currLvl)
443 }
444
445 if oldLeaf.path[currLvl] != newLeaf.path[currLvl] {
446 // reached divergence in next level
447 if newLeaf.path[currLvl] {
448 n.l = oldLeaf
449 n.r = newLeaf
450 } else {
451 n.l = newLeaf
452 n.r = oldLeaf
453 }
454 return nil
455 }
456 // no divergence yet, continue going down
457 if newLeaf.path[currLvl] {
458 // right
459 n.r = &node{}
460 if err := n.r.downUntilDivergence(p, currLvl+1, oldLeaf, newLeaf); err != nil {
461 return err
462 }
463 } else {
464 // left
465 n.l = &node{}
466 if err := n.l.downUntilDivergence(p, currLvl+1, oldLeaf, newLeaf); err != nil {
467 return err
468 }
469 }
470
471 return nil
472}
473
474func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
475 buckets := make([][]kv, nBuckets)
476 // 1. classify the keyvalues into buckets
477 for i := 0; i < len(kvs); i++ {
478 pair := kvs[i]
479
480 // bucketnum := keyToBucket(pair.k, nBuckets)
481 bucketnum := keyToBucket(pair.keyPath, nBuckets)
482 buckets[bucketnum] = append(buckets[bucketnum], pair)
483 }
484 return buckets
485}
486
487// TODO rename in a more 'real' name (calculate bucket from/for key)
488func keyToBucket(k []byte, nBuckets int) int {
489 nLevels := int(math.Log2(float64(nBuckets)))
490 b := make([]int, nBuckets)
491 for i := 0; i < nBuckets; i++ {
492 b[i] = i
493 }
494 r := b
495 mid := len(r) / 2 //nolint:gomnd
496 for i := 0; i < nLevels; i++ {
497 if int(k[i/8]&(1<<(i%8))) != 0 {
498 r = r[mid:]
499 mid = len(r) / 2 //nolint:gomnd
500 } else {
501 r = r[:mid]
502 mid = len(r) / 2 //nolint:gomnd
503 }
504 }
505 return r[0]
506}
507
508// flp2 computes the floor power of 2, the highest power of 2 under the given
509// value.
510func flp2(n int) int {
511 res := 0
512 for i := n; i >= 1; i-- {
513 if (i & (i - 1)) == 0 {
514 res = i
515 break
516 }
517 }
518 return res
519}
520
521// returns an array of key-values to store in the db
522func (n *node) computeHashes(currLvl, maxLvl int, p *params, pairs [][2][]byte) (
523 [][2][]byte, error) {
524 if n == nil || currLvl >= maxLvl {
525 // no need to compute any hash
526 return pairs, nil
527 }
528 if pairs == nil {
529 pairs = [][2][]byte{}
530 }
531 var err error
532 t := n.typ()
533 switch t {
534 case vtLeaf:
535 p.dbg.incHash()
536 leafKey, leafValue, err := newLeafValue(p.hashFunction, n.k, n.v)
537 if err != nil {
538 return pairs, err
539 }
540 n.h = leafKey
541 kv := [2][]byte{leafKey, leafValue}
542 pairs = append(pairs, kv)
543 case vtMid:
544 if n.l != nil {
545 pairs, err = n.l.computeHashes(currLvl+1, maxLvl, p, pairs)
546 if err != nil {
547 return pairs, err
548 }
549 } else {
550 n.l = &node{
551 h: p.emptyHash,
552 }
553 }
554 if n.r != nil {
555 pairs, err = n.r.computeHashes(currLvl+1, maxLvl, p, pairs)
556 if err != nil {
557 return pairs, err
558 }
559 } else {
560 n.r = &node{
561 h: p.emptyHash,
562 }
563 }
564 // once the sub nodes are computed, can compute the current node
565 // hash
566 p.dbg.incHash()
567 k, v, err := newIntermediate(p.hashFunction, n.l.h, n.r.h)
568 if err != nil {
569 return nil, err
570 }
571 n.h = k
572 kv := [2][]byte{k, v}
573 pairs = append(pairs, kv)
574 case vtEmpty:
575 default:
576 return nil, fmt.Errorf("ERR:n.computeHashes type (%d) no match", t) // TODO TMP
577 }
578
579 return pairs, nil
580}
581
582//nolint:unused
583func (t *vt) graphviz(w io.Writer) error {
584 fmt.Fprintf(w, `digraph hierarchy {
585node [fontname=Monospace,fontsize=10,shape=box]
586`)
587 if _, err := t.root.graphviz(w, t.params, 0); err != nil {
588 return err
589 }
590 fmt.Fprintf(w, "}\n")
591 return nil
592}
593
594//nolint:unused
595func (n *node) graphviz(w io.Writer, p *params, nEmpties int) (int, error) {
596 nChars := 4 // TODO move to global constant
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}