-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathpalmtree.h
1671 lines (1450 loc) · 54.6 KB
/
palmtree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include <functional>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <chrono>
#include <assert.h>
#include <thread>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <memory>
#include <atomic>
#include <glog/logging.h>
#include "immintrin.h"
// #include "smmintrin.h"
#include "CycleTimer.h"
#include "barrier.h"
#include <jemalloc/jemalloc.h>
using std::cout;
using std::endl;
#define UNUSED __attribute__((unused))
#define PROFILE
namespace palmtree {
static std::atomic<int> NODE_NUM(0);
unsigned int batch_id = 0;
/**
* Tree operation types
*/
enum TreeOpType {
TREE_OP_FIND = 0,
TREE_OP_INSERT,
TREE_OP_REMOVE
};
enum NodeType {
INNERNODE = 0,
LEAFNODE
};
class Stats {
public:
Stats(int worker_num): worker_num_(worker_num) {}
Stats() {}
/**
* add stat for one metric of one worker
*/
void add_stat(int worker_id, std::string metric_name, double metric_value) {
stats_[metric_name][worker_id] += metric_value;
}
void init_metric(std::string metric_name) {
stats_[metric_name] = std::vector<CycleTimer::SysClock>(worker_num_);
for (int i = 0; i < worker_num_; i++)
stats_[metric_name][i] = 0;
metric_names_.push_back(metric_name);
}
/**
* Print the stats out
*/
void print_stat() {
for (auto &metric_name : metric_names_) {
LOG(INFO) << "\033[1m[" << metric_name << "]\033[0m ";
auto &values = stats_[metric_name];
std::string line = "";
for (int i = 0; i < worker_num_; i++) {
if (metric_name == "leaf_task") {
line += "\t" + std::to_string(i) + ": " + std::to_string(values[i]);
} else {
line += "\t" + std::to_string(i) + ": " + std::to_string(values[i] * CycleTimer::secondsPerTick());
}
}
LOG(INFO) << line;
}
}
void reset_metric() {
for (auto itr = stats_.begin(); itr != stats_.end(); itr++) {
for (int i = 0; i < worker_num_; i++) {
itr->second[i] = 0;
}
}
}
private:
std::unordered_map<std::string, std::vector<CycleTimer::SysClock>> stats_;
std::vector<std::string> metric_names_;
int worker_num_;
} STAT;
template <typename KeyType,
typename ValueType,
typename PairType = std::pair<KeyType, ValueType>,
typename KeyComparator = std::less<KeyType> >
class PalmTree {
public:
// Number of working threads
int NUM_WORKER;
int BATCH_SIZE;
private:
// Max number of slots per inner node
static const int INNER_MAX_SLOT = 256;
// Max number of slots per leaf node
static const int LEAF_MAX_SLOT = 64;
// Threshold to control bsearch or linear search
static const int BIN_SEARCH_THRESHOLD = 32;
// Number of working threads
static const int BATCH_SIZE_PER_WORKER = 4096;
private:
/**
* Tree node base class
*/
struct InnerNode;
struct Node {
// Number of actually used slots
int slot_used;
int id;
int level;
KeyType lower_bound;
Node *parent;
Node() = delete;
Node(Node *p, int lvl): slot_used(0), level(lvl), parent(p) {
id = NODE_NUM++;
};
virtual ~Node() {};
virtual std::string to_string() = 0;
virtual NodeType type() const = 0;
virtual bool is_few() = 0;
};
struct InnerNode : public Node {
InnerNode() = delete;
InnerNode(Node *parent, int level): Node(parent, level){};
virtual ~InnerNode() {};
// Keys for values
KeyType keys[LEAF_MAX_SLOT];
// Pointers for child nodes
Node *values[LEAF_MAX_SLOT];
virtual NodeType type() const {
return INNERNODE;
}
virtual std::string to_string() {
std::string res;
res += "InnerNode[" + std::to_string(Node::id) + " @ " + std::to_string(Node::level) + "] ";
for (int i = 0 ; i < Node::slot_used ; i++) {
res += " " + std::to_string(keys[i]) + ":" + std::to_string(values[i]->id);
}
return res;
}
inline bool is_full() const {
return Node::slot_used == MAX_SLOT();
}
inline size_t MAX_SLOT() const {
return LEAF_MAX_SLOT;
}
virtual inline bool is_few() {
return Node::slot_used < MAX_SLOT()/4 || Node::slot_used == 0;
}
};
struct LeafNode : public Node {
LeafNode() = delete;
LeafNode(Node *parent, int level): Node(parent, level){};
virtual ~LeafNode() {};
// Keys and values for leaf node
KeyType keys[INNER_MAX_SLOT];
ValueType values[INNER_MAX_SLOT];
virtual NodeType type() const {
return LEAFNODE;
}
virtual std::string to_string() {
std::string res;
res += "LeafNode[" + std::to_string(Node::id) + " @ " + std::to_string(Node::level) + "] ";
for (int i = 0 ; i < Node::slot_used ; i++) {
res += " " + std::to_string(keys[i]) + ":" + std::to_string(values[i]);
}
return res;
}
inline bool is_full() const {
return Node::slot_used == MAX_SLOT();
}
inline size_t MAX_SLOT() const {
return INNER_MAX_SLOT;
}
virtual inline bool is_few() {
return Node::slot_used < MAX_SLOT()/4 || Node::slot_used == 0;
}
};
/**
* Tree operation wrappers
*/
struct TreeOp {
// Op can either be none, add or delete
TreeOp(TreeOpType op_type, const KeyType &key, const ValueType &value):
op_type_(op_type), key_(key), value_(value), target_node_(nullptr),
boolean_result_(false), done_(false) {};
TreeOp(TreeOpType op_type, const KeyType &key):
op_type_(op_type), key_(key), target_node_(nullptr),
boolean_result_(false), done_(false) {};
TreeOpType op_type_;
KeyType key_;
ValueType value_;
LeafNode *target_node_;
ValueType result_;
bool boolean_result_;
bool done_;
// Wait until this operation is done
// Now use busy waiting, should use something more smart. But be careful
// that conditional variable could be very expensive
inline void wait() {
while (!done_) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
}
}
};
/**
* A batch of tree operations, this data structure is not thread safe
* The major goal of this class is to amortize memory allocation of
* tree operations
*/
class TaskBatch {
public:
TaskBatch(size_t capacity): capacity_(capacity), ntask_(0) {
ops_ = (TreeOp *)malloc(sizeof(TreeOp) * capacity_);
}
void destroy() {
free(ops_);
ops_ = nullptr;
}
// Add a tree operation to the batch
inline void add_op(TreeOpType op_type, const KeyType *keyp, const ValueType *valp) {
assert(ntask_ != capacity_);
if (op_type == TREE_OP_INSERT) {
assert(valp != nullptr);
ops_[ntask_++] = TreeOp(op_type, *keyp, *valp);
} else {
ops_[ntask_++] = TreeOp(op_type, *keyp);
}
}
// Whether the tree is full or not
inline bool is_full() { return ntask_ == capacity_; }
// The size of the batch
inline size_t size() { return ntask_; }
// Overloading [] to return the ith operation in the batch
TreeOp * get_op(int i) {
assert(i < ntask_);
return ops_ + i;
}
// Capacity of the batch
size_t capacity_;
// Number of tasks currently in the batch
size_t ntask_;
// Tree opearations
TreeOp *ops_;
};
enum ModType {
MOD_TYPE_ADD,
MOD_TYPE_DEC,
MOD_TYPE_NONE
};
/**
* Wrapper for node modification
*/
struct NodeMod {
NodeMod(ModType type): type_(type) {}
NodeMod(const TreeOp &op) {
CHECK(op.op_type_ != TREE_OP_FIND) << "NodeMod can't convert from a find operation" << endl;
if (op.op_type_ == TREE_OP_REMOVE) {
this->type_ = MOD_TYPE_DEC;
this->value_items.emplace_back(std::make_pair(op.key_, ValueType()));
} else {
this->type_ = MOD_TYPE_ADD;
this->value_items.emplace_back(std::make_pair(op.key_, op.value_));
}
}
ModType type_;
// For leaf modification
std::vector<std::pair<KeyType, ValueType>> value_items;
// For inner node modification
std::vector<std::pair<KeyType, Node *>> node_items;
// For removed keys
std::vector<std::pair<KeyType, ValueType>> orphaned_kv;
};
/********************
* PalmTree private
* ******************/
private:
// Root of the palm tree
Node *tree_root;
// Height of the tree
int tree_depth_;
// Number of nodes on each layer
std::vector<std::atomic<int> *> layer_width_;
// Is the tree being destroyed or not
bool destroyed_;
// Minimal key
KeyType min_key_;
// Key comparator
KeyComparator kcmp;
// Current batch of the tree
TaskBatch *tree_current_batch_;
// Push a task into the current batch, if the batch is full, push the batch
// into the batch queue.
void push_task(TreeOpType op_type, const KeyType *keyp, const ValueType *valp) {
tree_current_batch_->add_op(op_type, keyp, valp);
task_nums += 2;
if (tree_current_batch_->is_full()) {
task_batch_queue_.push(tree_current_batch_);
tree_current_batch_ = (TaskBatch *)malloc(sizeof(TaskBatch));
new (tree_current_batch_) TaskBatch(BATCH_SIZE);
DLOG(INFO) << "Push one batch into the queue ";
}
}
// Return true if k1 < k2
inline bool key_less(const KeyType &k1, const KeyType &k2) {
return kcmp(k1, k2);
}
// Return true if k1 == k2
inline bool key_eq(const KeyType &k1, const KeyType &k2) {
return !kcmp(k1, k2) && !kcmp(k2, k1);
}
// Return the index of the largest slot whose key <= @target
// assume there is no duplicated element
int search_helper(const KeyType *input, int size, const KeyType &target) {
int res = -1;
// loop all element
for (int i = 0; i < size; i++) {
if(key_less(target, input[i])){
// target < input
// ignore
continue;
}
if (res == -1 || key_less(input[res], input[i])) {
res = i;
}
}
return res;
}
// liner search in leaf
// assume there is no duplicated element
// int search_leaf(const KeyType *data, int size, const KeyType &target) {
// const __m128i keys = _mm_set1_epi32(target);
//
// const auto n = size;
// const auto rounded = 8 * (n / 8);
//
// for (int i = 0; i < rounded; i += 8) {
//
// const __m128i vec1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&data[i]));
// const __m128i vec2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&data[i + 4]));
//
// const __m128i cmp1 = _mm_cmpeq_epi32(vec1, keys);
// const __m128i cmp2 = _mm_cmpeq_epi32(vec2, keys);
//
// const __m128i tmp = _mm_packs_epi32(cmp1, cmp2);
// const uint32_t mask = _mm_movemask_epi8(tmp);
//
// if (mask != 0) {
// return i + __builtin_ctz(mask) / 2;
// }
// }
//
// for (int i = rounded; i < n; i++) {
// if (data[i] == target) {
// return i;
// }
// }
//
// return -1;
// }
int search_leaf(const KeyType *data, int size, const KeyType &target) {
// #ifdef PROFILE
// auto bt = CycleTimer::currentTicks();
// #endif
const __m256i keys = _mm256_set1_epi32(target);
const auto n = size;
const auto rounded = 8 * (n/8);
for (int i=0; i < rounded; i += 8) {
const __m256i vec1 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(&data[i]));
const __m256i cmp1 = _mm256_cmpeq_epi32(vec1, keys);
const uint32_t mask = _mm256_movemask_epi8(cmp1);
if (mask != 0) {
// #ifdef PROFILE
// STAT.add_stat(0, "search_leaf", CycleTimer::currentTicks() - bt);
// #endif
return i + __builtin_ctz(mask)/4;
}
}
for (int i = rounded; i < n; i++) {
if (data[i] == target) {
// #ifdef PROFILE
// STAT.add_stat(0, "search_leaf", CycleTimer::currentTicks() - bt);
// #endif
return i;
}
}
// #ifdef PROFILE
// STAT.add_stat(0, "search_leaf", CycleTimer::currentTicks() - bt);
// #endif
return -1;
}
// Return the index of the largest slot whose key <= @target
// assume there is no duplicated element
int search_inner(const KeyType *input, int size, const KeyType &target) {
// #ifdef PROFILE
// auto bt = CycleTimer::currentTicks();
// #endif
int low = 0, high = size - 1;
while (low != high) {
int mid = (low + high) / 2 + 1;
if (key_less(target, input[mid])) {
// target < input[mid]
high = mid - 1;
}
else {
// target >= input[mid];
low = mid;
}
}
// #ifdef PROFILE
// STAT.add_stat(0, "search_inner", CycleTimer::currentTicks() - bt);
// #endif
if (low == size) {
return -1;
}
return low;
}
/**
* @brief Return the leaf node that contains the @key
*/
LeafNode *search(const KeyType &key UNUSED) {
auto ptr = (InnerNode *)tree_root;
for (;;) {
CHECK(ptr->slot_used > 0) << "Search empty inner node";
auto idx = this->search_inner(ptr->keys, ptr->slot_used, key);
CHECK(idx != -1) << "search innerNode fail" << endl;
CHECK(key_less(ptr->keys[idx], key) || key_eq(ptr->keys[idx], key));
if(idx + 1 < ptr->slot_used) {
CHECK(key_less(key, ptr->keys[idx + 1]));
}
Node *child = ptr->values[idx];
if (child->type() == LEAFNODE) {
return (LeafNode *)child;
} else {
ptr = (InnerNode *)child;
}
}
// we shouldn't reach here
assert(0);
}
/**
* @brief big_split will split the kv pair vector into multiple tree nodes
* that is within the threshold. The actual type of value is templated as V.
* The splited nodes should be stored in Node, respect to appropriate
* node types
*/
template<typename NodeType, typename V>
void big_split(std::vector<std::pair<KeyType, V>> &input, NodeType *node, std::vector<std::pair<KeyType, Node *>> &new_nodes) {
std::sort(input.begin(), input.end(), [this](const std::pair<KeyType, V> &p1, const std::pair<KeyType, V> &p2) {
return key_less(p1.first, p2.first);
});
auto itr = input.begin();
auto item_per_node = node->MAX_SLOT() / 2;
auto node_num = input.size() / (item_per_node);
// save first half items (small part) in old node
node->slot_used = 0;
for (int i = 0; i < item_per_node; i++) {
// add_item<NodeType, V>(node, itr->first, itr->second);
node->keys[i] = itr->first;
node->values[i] = itr->second;
node->slot_used++;
itr++;
}
// Add a new node
int node_create_num = 1;
while(node_create_num < node_num) {
NodeType *new_node = new NodeType(node->parent, node->Node::level);
layer_width_[node->Node::level]->fetch_add(1);
// save the second-half in new node
auto new_key = (*itr).first;
int i = 0;
while (itr != input.end() && new_node->slot_used < item_per_node) {
// add_item<NodeType, V>(new_node, itr->first, itr->second);
new_node->keys[i] = itr->first;
new_node->values[i] = itr->second;
new_node->slot_used++;
itr++;
i++;
}
if(node_create_num == node_num - 1) {
while(itr != input.end()) {
new_node->keys[i] = itr->first;
new_node->values[i] = itr->second;
new_node->slot_used++;
itr++;
i++;
}
}
new_nodes.push_back(std::make_pair(new_key, new_node));
node_create_num++;
}
}
// Warning: if this function return true, the width of the layer will be
// decreased by 1, so the caller must actually merge the node
bool must_merge(Node *node) {
if (!node->is_few())
return false;
int old_width = layer_width_[node->level]->fetch_add(-1);
if (old_width == 1) {
// Can't merge
layer_width_[node->level]->fetch_add(1);
return false;
}
return true;
}
template <typename NodeType, typename V>
void add_item(NodeType *node, const KeyType &key, V value) {
// add item to leaf node
// just append it to the end of the slot
if (node->type() == LEAFNODE) {
// auto idx = node->slot_used++;
auto idx = search_leaf(node->keys, node->slot_used, key);
if(idx != -1) {
return;
}
idx = node->slot_used++;
node->keys[idx] = key;
node->values[idx] = value;
return;
}
if(node->slot_used == 0) {
node->keys[0] = key;
node->values[0] = value;
node->slot_used++;
return;
}
// add item to inner node
// ensure it's order
DLOG(INFO) << "search inner begin";
auto idx = search_inner(node->keys, node->slot_used, key);
CHECK(idx != -1) << "search innerNode fail" << key <<" " <<node->keys[0];
CHECK(key_less(node->keys[idx], key) || key_eq(node->keys[idx], key));
if(idx + 1 < node->slot_used) {
CHECK(key_less(key, node->keys[idx + 1])) << "search inner fail";
}
DLOG(INFO) << "search inner end";
auto k = key;
auto v = value;
for(int i = idx + 1; i < node->slot_used; i++) {
std::swap(node->keys[i], k);
std::swap(node->values[i], v);
}
node->keys[node->slot_used] = k;
node->values[node->slot_used] = v;
node->slot_used++;
}
template <typename NodeType>
void del_item(NodeType *node, const KeyType &key) {
auto lastIdx = node->slot_used - 1;
auto idx = search_helper(node->keys, node->slot_used, key);
DLOG(INFO) << "search in del, idx: " << idx;
if (idx == -1) {
DLOG(WARNING) << "del fail, can't find key in node";
return;
}
if (!key_eq(key, node->keys[idx])) {
DLOG(WARNING) << "del in inner, del idx: " << idx << " key != del_key" << endl;
if (node->type() == LEAFNODE)
return;
}
if (node->type() == INNERNODE) {
Node *child_node = reinterpret_cast<Node *>(&node->values[idx]);
DLOG(INFO) << "Delete node " << child_node->id;
free_recursive(child_node);
KeyType del_key = node->keys[idx];
// auto k = node->keys[idx];
// auto v = node->value[idx];
for(int i = idx; i < node->slot_used - 1; i++) {
std::swap(node->keys[i], node->keys[i + 1]);
std::swap(node->values[i], node->values[i + 1]);
}
if(idx == 0) {
node->keys[0] = del_key;
}
node->slot_used--;
}else {
// del in leaf
if (idx == lastIdx) {
// if it's the last element, just pop it
node->slot_used--;
} else {
// otherwise, swap
node->keys[idx] = node->keys[lastIdx];
node->values[idx] = node->values[lastIdx];
node->slot_used--;
}
}
return;
}
// collect kv pairs in (or under) this node
// used for merge
void collect_leaf(Node *node, std::vector<std::pair<KeyType, ValueType>> &container) {
if (node->type() == LEAFNODE) {
auto ptr = (LeafNode *)node;
for(int i = 0; i < node->slot_used; i++) {
container.push_back(std::make_pair(ptr->keys[i], ptr->values[i]));
}
} else if (node->type() == INNERNODE) {
auto ptr = (InnerNode *)node;
for(int i = 0; i < node->slot_used; i++) {
collect_leaf(ptr->values[i], container);
}
layer_width_[node->level-1]->fetch_add(-node->slot_used);
} else {
assert(0);
}
return;
}
/**
* @brief Modify @node by applying node modifications in @modes. If @node
* is a leaf node, @mods will be a list of add kv and del kv. If @node is
* a inner node, @mods will be a list of add range and del range. If new
* node modifications are triggered, record them in @new_mods.
*/
NodeMod modify_node(Node *node, const std::vector<NodeMod> &mods) {
DLOG(INFO) << "Modifying node " << node->id << " with " << mods.size() << " operations";
if(node->type() == LEAFNODE) {
return modify_node_leaf((LeafNode *)node, mods);
}else{
CHECK(node->type() == INNERNODE) << "unKnown node" << endl;
return modify_node_inner((InnerNode *)node, mods);
}
}
NodeMod modify_node_leaf(LeafNode *node, const std::vector<NodeMod> &mods) {
NodeMod ret(MOD_TYPE_NONE);
auto& kv = ret.orphaned_kv;
// randomly pick up a key, used for merge
auto node_key = node->keys[0];
// firstly, we loop all items to save orphaned and count nodes
int num = node->slot_used;
for (auto& item : mods) {
// save all orphaned_*
kv.insert(kv.end(), item.orphaned_kv.begin(), item.orphaned_kv.end());
auto item_size = (int)item.value_items.size();
if (item.type_ == MOD_TYPE_ADD) {
num += item_size;
} else if (item.type_ == MOD_TYPE_DEC) {
num -= item_size;
} else {
assert(item_size == 0);
}
}
DLOG(INFO) << "Result node size " << num;
if (num > node->MAX_SLOT()) {
DLOG(INFO) << "Going to split";
auto comp = [this](const std::pair<KeyType, ValueType> &p1, const std::pair<KeyType, ValueType> &p2) {
return key_less(p1.first, p2.first);
};
std::set<std::pair<KeyType, ValueType>, decltype(comp)> buf(comp);
// execute add/del
for (auto& item : mods) {
if (item.type_ == MOD_TYPE_ADD) {
for (auto& kv : item.value_items) {
buf.insert(kv);
}
} else if(item.type_ == MOD_TYPE_DEC) {
for (auto& kv : item.value_items) {
if(buf.count(kv)) {
buf.erase(kv);
}else{
del_item<LeafNode>(node, kv.first);
}
}
}
}
// construct input for split
std::vector<std::pair<KeyType, ValueType>> split_input;
for(auto itr = buf.begin(); itr != buf.end(); itr++) {
split_input.push_back(*itr);
}
for(auto i = 0; i < node->slot_used; i++) {
split_input.push_back(std::make_pair(node->keys[i], node->values[i]));
}
// do split based on this buf
big_split<LeafNode, ValueType>(split_input, node, ret.node_items);
ret.type_ = MOD_TYPE_ADD;
return ret;
} else {
DLOG(INFO) << "don't split";
for (auto& item : mods) {
if (item.type_ == MOD_TYPE_ADD) {
for (auto& kv : item.value_items) {
add_item<LeafNode, ValueType>(node, kv.first, kv.second);
}
} else if(item.type_ == MOD_TYPE_DEC) {
for (auto& kv : item.value_items) {
del_item<LeafNode>(node, kv.first);
}
}
}
}
// merge
// fixme: never merge the first leafnode
// because the min_key is in this node
// we can't delete min_key
if (must_merge(node)) {
DLOG(INFO) << "Merge leaf node " << node->id;
collect_leaf(node, ret.orphaned_kv);
ret.node_items.push_back(std::make_pair(node_key, node));
ret.type_ = MOD_TYPE_DEC;
}
return ret;
}
NodeMod modify_node_inner(InnerNode *node UNUSED, const std::vector<NodeMod> &mods UNUSED) {
NodeMod ret(MOD_TYPE_NONE);
auto& kv = ret.orphaned_kv;
// randomly pick up a key, used for merge
auto node_key = node->keys[0];
// firstly, we loop all items to save orphaned and count nodes
int num = node->slot_used;
for (auto& item : mods) {
// save all orphaned_*
kv.insert(kv.end(), item.orphaned_kv.begin(), item.orphaned_kv.end());
auto item_size = (int)item.node_items.size();
if (item.type_ == MOD_TYPE_ADD) {
num += item_size;
} else if (item.type_ == MOD_TYPE_DEC) {
num -= item_size;
} else {
assert(item_size == 0);
}
}
if (num > node->MAX_SLOT()) {
DLOG(INFO) << "inner will split";
auto comp = [this](const std::pair<KeyType, Node *> &p1, const std::pair<KeyType, Node *> &p2) {
return key_less(p1.first, p2.first);
};
std::set<std::pair<KeyType, Node *>, decltype(comp)> buf(comp);
// execute add/del
for (auto& item : mods) {
if (item.type_ == MOD_TYPE_ADD) {
for (auto& kv : item.node_items) {
buf.insert(kv);
}
} else if(item.type_ == MOD_TYPE_DEC) {
for (auto& kv : item.node_items) {
if(buf.count(kv)) {
buf.erase(kv);
// TODO: memleak
}else{
// cout << "del " << kv.first<<endl;
del_item<InnerNode>(node, kv.first);
}
}
}
}
// construct input for split
std::vector<std::pair<KeyType, Node *>> split_input;
for(auto itr = buf.begin(); itr != buf.end(); itr++) {
split_input.push_back(*itr);
}
for(auto i = 0; i < node->slot_used; i++) {
split_input.push_back(std::make_pair(node->keys[i], node->values[i]));
}
// do split based on this buf
big_split<InnerNode, Node *>(split_input, node, ret.node_items);
for (auto itr = ret.node_items.begin(); itr != ret.node_items.end(); itr++) {
// Reset parent, the children of the newly splited node should point
// to the new parent
auto new_node = itr->second;
for (int i = 0; i < new_node->slot_used; i++) {
CHECK(new_node->type() == INNERNODE) << " split leaf node in modify_node_inner";
((InnerNode *)new_node)->values[i]->parent = new_node;
}
}
ret.type_ = MOD_TYPE_ADD;
return ret;
} else {
DLOG(INFO) << "inner not split";
for (auto& item : mods) {
if (item.type_ == MOD_TYPE_ADD) {
for (auto& kv : item.node_items) {
DLOG(INFO) << "Add item " << kv.first;
add_item<InnerNode, Node *>(node, kv.first, kv.second);
}
} else if(item.type_ == MOD_TYPE_DEC) {
for (auto& kv : item.node_items) {
DLOG(INFO) << "Del item " << kv.first;
del_item<InnerNode>(node, kv.first);
}
} else {
DLOG(INFO) << "A NOOP has propagated";
}
}
}
// merge
if (must_merge(node)) {
collect_leaf(node, ret.orphaned_kv);
ret.node_items.push_back(std::make_pair(node_key, node));
ret.type_ = MOD_TYPE_DEC;
} else {
DLOG(INFO) << "Don't merge " << layer_width_[node->level]->load() << " " << node->is_few() << " " << node->slot_used;
}
return ret;
}
// set the smallest key in node to min_key
void ensure_min_range(InnerNode *node UNUSED, const KeyType &min) {
if (node->slot_used <= 1) {
return;
}
// find the second smallest
int idx = 0;
for(int i = 1; i < node->slot_used; i++) {
if(key_less(node->keys[i], node->keys[idx])) {
idx = i;
}
}
CHECK(key_less(min, node->keys[idx]));
if(idx == 0) {
return;
}
// swap idx with slot 0
std::swap(node->keys[0], node->keys[idx]);
std::swap(node->values[0], node->values[idx]);
}
void ensure_min_key() {
auto ptr = (Node *)tree_root;
while(ptr->type() == INNERNODE) {
auto inner = (InnerNode *)ptr;
inner->keys[0] = min_key_;
ptr = inner->values[0];
}
}
void ensure_tree_structure(Node *node, int indent) {
std::map<int, int> recorder;
ensure_tree_structure_helper(node, indent, recorder);
CHECK(layer_width_.size() == recorder.size()) << "mismatch layer";
for(auto itr = recorder.begin(); itr != recorder.end(); itr++) {
CHECK(layer_width_[itr->first]->load() == itr->second) << "mismatch layer size in "<< itr->first <<" , expect: " << layer_width_[itr->first]->load()<< " actual "<<itr->second;
}
}
void ensure_tree_structure_helper(Node *node, int indent, std::map<int, int>& layer_size_recorder) {
if(layer_size_recorder.count(node->level)) {
layer_size_recorder[node->level]++;
} else {
layer_size_recorder[node->level] = 1;
}
std::string space;
for (int i = 0; i < indent; i++)
space += " ";
DLOG(INFO) << space << node->to_string() << " | Layer size " << layer_width_[node->level]->load();;
if (node->type() == INNERNODE) {
InnerNode *inode = (InnerNode *)node;
for (int i = 0; i < inode->slot_used; i++) {
auto child = inode->values[i];
CHECK(child->parent == node) << "My child " << i << " does not point to me";
}
}
if (node->type() == INNERNODE) {
InnerNode *inode = (InnerNode *)node;
for (int i = 0; i < inode->slot_used; i++) {
auto child = inode->values[i];
KeyType *key_set;
if (child->type() == LEAFNODE)
key_set = ((LeafNode *)child)->keys;
else
key_set = ((InnerNode *)child)->keys;
if (child->slot_used == 0) {