You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

671 lines
15 KiB

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