-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmerge_iterator.go
More file actions
773 lines (671 loc) · 15.7 KB
/
merge_iterator.go
File metadata and controls
773 lines (671 loc) · 15.7 KB
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
package wildcat
import (
"bytes"
"container/heap"
"fmt"
"github.com/wildcatdb/wildcat/v2/skiplist"
"github.com/wildcatdb/wildcat/v2/tree"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"sync"
"sync/atomic"
)
// iteratorPool reuses iterator objects
var iteratorPool = sync.Pool{
New: func() interface{} {
return &iterator{}
},
}
// MergeIterator combines multiple iterators into a single iterator
type MergeIterator struct {
ascendingHeap iteratorHeap
descendingHeap reverseIteratorHeap
ts int64
ascending bool
lastKey []byte
lastTimestamp int64
allIterators []*iterator
db *DB
initialized bool
duplicateBuffer []*iterator
}
// iterator is the internal structure for each iterator
type iterator struct {
underlyingIterator interface{}
currentKey []byte
currentValue []byte
sst *SSTable
currentTimestamp int64
exhausted bool
index int
ascending bool
ts int64
initialized bool
}
// resetIterator clears iterator state for reuse
func (it *iterator) reset() {
it.underlyingIterator = nil
it.currentKey = nil
it.currentValue = nil
it.sst = nil
it.currentTimestamp = 0
it.exhausted = false
it.index = -1
it.ascending = false
it.ts = 0
it.initialized = false
}
// getIterator gets an iterator from the pool
func getIterator() *iterator {
return iteratorPool.Get().(*iterator)
}
// putIterator returns an iterator to the pool
func putIterator(it *iterator) {
it.reset()
iteratorPool.Put(it)
}
// NewMergeIterator creates a new MergeIterator with the given iterators
func NewMergeIterator(db *DB, iterators []*iterator, ts int64, ascending bool) (*MergeIterator, error) {
mi := &MergeIterator{
ascendingHeap: make(iteratorHeap, 0, len(iterators)),
descendingHeap: make(reverseIteratorHeap, 0, len(iterators)),
ts: ts,
ascending: ascending,
allIterators: make([]*iterator, len(iterators)),
db: db,
duplicateBuffer: make([]*iterator, 0, len(iterators)),
}
copy(mi.allIterators, iterators)
// Set timestamp for push-down filtering on each iterator
for _, it := range mi.allIterators {
it.ascending = ascending
it.ts = ts
}
return mi, nil
}
// ensureInitialized performs lazy initialization of all iterators
func (mi *MergeIterator) ensureInitialized() error {
if mi.initialized {
return nil
}
// Initialize both heaps simultaneously to avoid rebuilding on direction changes
for _, it := range mi.allIterators {
if err := mi.initializeIterator(it); err != nil {
return err
}
if !it.exhausted {
ascendingCopy := getIterator()
*ascendingCopy = *it
descendingCopy := getIterator()
*descendingCopy = *it
heap.Push(&mi.ascendingHeap, ascendingCopy)
heap.Push(&mi.descendingHeap, descendingCopy)
}
}
mi.initialized = true
return nil
}
// initializeIterator sets up the iterator with its first key-value pair
func (mi *MergeIterator) initializeIterator(it *iterator) error {
if it.initialized {
return nil
}
if it.sst != nil {
atomic.CompareAndSwapInt32(&it.sst.isBeingRead, 0, 1)
}
switch t := it.underlyingIterator.(type) {
case *skiplist.Iterator:
if t == nil {
it.exhausted = true
return nil
}
if it.ascending {
for {
key, value, ts, ok := t.Next()
if !ok {
it.exhausted = true
break
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
break
}
}
} else {
if !t.Valid() {
it.exhausted = true
return nil
}
t.ToLast()
for {
key, value, ts, ok := t.Peek()
if !ok {
key, value, ts, ok = t.Prev()
}
if !ok {
it.exhausted = true
break
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
break
}
_, _, _, ok = t.Prev()
if !ok {
it.exhausted = true
break
}
}
}
case *skiplist.RangeIterator:
if t == nil {
it.exhausted = true
return nil
}
if it.ascending {
for {
key, value, ts, ok := t.Next()
if !ok {
it.exhausted = true
break
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
break
}
}
} else {
if !t.Valid() {
it.exhausted = true
return nil
}
t.ToLast()
for {
key, value, ts, ok := t.Peek()
if !ok {
key, value, ts, ok = t.Prev()
}
if !ok {
it.exhausted = true
break
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
break
}
_, _, _, ok = t.Prev()
if !ok {
it.exhausted = true
break
}
}
}
case *skiplist.PrefixIterator:
if t == nil {
it.exhausted = true
return nil
}
if it.ascending {
for {
key, value, ts, ok := t.Next()
if !ok {
it.exhausted = true
break
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
break
}
}
} else {
if !t.Valid() {
it.exhausted = true
return nil
}
t.ToLast()
for {
key, value, ts, ok := t.Peek()
if !ok {
key, value, ts, ok = t.Prev()
}
if !ok {
it.exhausted = true
break
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
break
}
_, _, _, ok = t.Prev()
if !ok {
it.exhausted = true
break
}
}
}
case *tree.Iterator:
if t == nil {
it.exhausted = true
return nil
}
if it.ascending {
for t.Next() {
entry, err := mi.extractKLogEntry(t.Value())
if err != nil {
if it.sst != nil {
mi.db.log(fmt.Sprintf("Potential block corruption detected for SSTable %d at Level %d: %v", it.sst.Id, it.sst.Level, err))
}
it.exhausted = true
return err
}
if entry.Timestamp <= it.ts {
it.currentKey = entry.Key
it.currentValue = it.sst.readValueFromVLog(entry.ValueBlockID)
it.currentTimestamp = entry.Timestamp
break
}
}
if len(it.currentKey) == 0 {
it.exhausted = true
}
} else {
if err := t.SeekToLast(); err != nil {
it.exhausted = true
return err
}
for t.Valid() {
entry, err := mi.extractKLogEntry(t.Value())
if err != nil {
if it.sst != nil {
mi.db.log(fmt.Sprintf("Potential block corruption detected for SSTable %d at Level %d: %v", it.sst.Id, it.sst.Level, err))
}
it.exhausted = true
return err
}
if entry.Timestamp <= it.ts {
it.currentKey = entry.Key
it.currentValue = it.sst.readValueFromVLog(entry.ValueBlockID)
it.currentTimestamp = entry.Timestamp
break
}
if !t.Prev() {
break
}
}
if len(it.currentKey) == 0 {
it.exhausted = true
}
}
default:
it.exhausted = true
}
it.initialized = true
return nil
}
// extractKLogEntry converts various types to KLogEntry
func (mi *MergeIterator) extractKLogEntry(value interface{}) (*KLogEntry, error) {
if klogEntry, ok := value.(*KLogEntry); ok {
return klogEntry, nil
}
if doc, ok := value.(primitive.D); ok {
entry := &KLogEntry{}
for _, elem := range doc {
switch elem.Key {
case "key":
if keyData, ok := elem.Value.(primitive.Binary); ok {
entry.Key = keyData.Data
}
case "timestamp":
if ts, ok := elem.Value.(int64); ok {
entry.Timestamp = ts
}
case "valueblockid":
if blockID, ok := elem.Value.(int64); ok {
entry.ValueBlockID = blockID
}
}
}
return entry, nil
}
bsonData, err := bson.Marshal(value)
if err != nil {
return nil, err
}
entry := &KLogEntry{}
err = bson.Unmarshal(bsonData, entry)
return entry, err
}
// SetDirection changes the iteration direction
func (mi *MergeIterator) SetDirection(ascending bool) error {
if err := mi.ensureInitialized(); err != nil {
return err
}
if mi.ascending == ascending {
return nil
}
mi.ascending = ascending
return nil
}
// Next returns the next key-value pair in the configured direction
// Returns slices that reference existing data to avoid allocations
func (mi *MergeIterator) Next() ([]byte, []byte, int64, bool) {
if err := mi.ensureInitialized(); err != nil {
return nil, nil, 0, false
}
if mi.ascending {
return mi.nextAscending()
}
return mi.nextDescending()
}
// nextAscending handles ascending iteration with batch duplicate removal
func (mi *MergeIterator) nextAscending() ([]byte, []byte, int64, bool) {
if mi.ascendingHeap.Len() == 0 {
return nil, nil, 0, false
}
current := heap.Pop(&mi.ascendingHeap).(*iterator)
key := current.currentKey
value := current.currentValue
timestamp := current.currentTimestamp
// Batch process all duplicates with the same key
mi.duplicateBuffer = mi.duplicateBuffer[:0]
for mi.ascendingHeap.Len() > 0 && bytes.Equal(mi.ascendingHeap[0].currentKey, key) {
duplicate := heap.Pop(&mi.ascendingHeap).(*iterator)
mi.duplicateBuffer = append(mi.duplicateBuffer, duplicate)
}
mi.advanceIterator(current)
if !current.exhausted {
heap.Push(&mi.ascendingHeap, current)
} else {
putIterator(current)
}
for _, duplicate := range mi.duplicateBuffer {
mi.advanceIterator(duplicate)
if !duplicate.exhausted {
heap.Push(&mi.ascendingHeap, duplicate)
} else {
putIterator(duplicate)
}
}
mi.lastKey = key
mi.lastTimestamp = timestamp
return key, value, timestamp, true
}
// nextDescending handles descending iteration with batch duplicate removal
func (mi *MergeIterator) nextDescending() ([]byte, []byte, int64, bool) {
if mi.descendingHeap.Len() == 0 {
return nil, nil, 0, false
}
current := heap.Pop(&mi.descendingHeap).(*iterator)
key := current.currentKey
value := current.currentValue
timestamp := current.currentTimestamp
// Batch process all duplicates with the same key
mi.duplicateBuffer = mi.duplicateBuffer[:0]
for mi.descendingHeap.Len() > 0 && bytes.Equal(mi.descendingHeap[0].currentKey, key) {
duplicate := heap.Pop(&mi.descendingHeap).(*iterator)
mi.duplicateBuffer = append(mi.duplicateBuffer, duplicate)
}
mi.advanceIterator(current)
if !current.exhausted {
heap.Push(&mi.descendingHeap, current)
} else {
putIterator(current)
}
for _, duplicate := range mi.duplicateBuffer {
mi.advanceIterator(duplicate)
if !duplicate.exhausted {
heap.Push(&mi.descendingHeap, duplicate)
} else {
putIterator(duplicate)
}
}
mi.lastKey = key
mi.lastTimestamp = timestamp
return key, value, timestamp, true
}
// advanceIterator moves the iterator to the next valid entry with timestamp filtering
func (mi *MergeIterator) advanceIterator(it *iterator) {
switch t := it.underlyingIterator.(type) {
case *skiplist.Iterator:
if t == nil {
it.exhausted = true
return
}
for {
var key []byte
var value []byte
var ts int64
var ok bool
if it.ascending {
key, value, ts, ok = t.Next()
} else {
key, value, ts, ok = t.Prev()
}
if !ok {
it.exhausted = true
return
}
// Push-down timestamp filtering
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
return
}
}
case *skiplist.RangeIterator:
if t == nil {
it.exhausted = true
return
}
for {
var key []byte
var value []byte
var ts int64
var ok bool
if it.ascending {
key, value, ts, ok = t.Next()
} else {
key, value, ts, ok = t.Prev()
}
if !ok {
it.exhausted = true
return
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
return
}
}
case *skiplist.PrefixIterator:
if t == nil {
it.exhausted = true
return
}
for {
var key []byte
var value []byte
var ts int64
var ok bool
if it.ascending {
key, value, ts, ok = t.Next()
} else {
key, value, ts, ok = t.Prev()
}
if !ok {
it.exhausted = true
return
}
if ts <= it.ts {
it.currentKey = key
it.currentValue = value
it.currentTimestamp = ts
return
}
}
case *tree.Iterator:
if t == nil {
it.exhausted = true
return
}
for {
var hasNext bool
if it.ascending {
hasNext = t.Next()
} else {
hasNext = t.Prev()
}
if !hasNext {
it.exhausted = true
return
}
entry, err := mi.extractKLogEntry(t.Value())
if err != nil {
if it.sst != nil {
mi.db.log(fmt.Sprintf("Potential block corruption detected for SSTable %d at Level %d: %v", it.sst.Id, it.sst.Level, err))
}
it.exhausted = true
return
}
if entry.Timestamp <= it.ts {
it.currentKey = entry.Key
it.currentValue = it.sst.readValueFromVLog(entry.ValueBlockID)
it.currentTimestamp = entry.Timestamp
return
}
}
default:
it.exhausted = true
}
}
// Prev returns the previous key-value pair (opposite of configured direction)
func (mi *MergeIterator) Prev() ([]byte, []byte, int64, bool) {
if err := mi.ensureInitialized(); err != nil {
return nil, nil, 0, false
}
if mi.ascending {
mi.ascending = false
return mi.nextDescending()
} else {
mi.ascending = true
return mi.nextAscending()
}
}
// HasNext returns true if there are more entries in the configured direction
func (mi *MergeIterator) HasNext() bool {
if err := mi.ensureInitialized(); err != nil {
return false
}
if mi.ascending {
return mi.ascendingHeap.Len() > 0
}
return mi.descendingHeap.Len() > 0
}
// HasPrev returns true if there are entries in the opposite direction
func (mi *MergeIterator) HasPrev() bool {
if err := mi.ensureInitialized(); err != nil {
return false
}
if mi.ascending {
return mi.descendingHeap.Len() > 0
}
return mi.ascendingHeap.Len() > 0
}
// IsAscending returns the current iteration direction
func (mi *MergeIterator) IsAscending() bool {
return mi.ascending
}
// Close cleans up resources and returns iterators to the pool
func (mi *MergeIterator) Close() {
for _, it := range mi.allIterators {
if it.sst != nil {
atomic.CompareAndSwapInt32(&it.sst.isBeingRead, 1, 0)
}
putIterator(it)
}
// Clear heap references
for i := 0; i < mi.ascendingHeap.Len(); i++ {
putIterator(mi.ascendingHeap[i])
}
for i := 0; i < mi.descendingHeap.Len(); i++ {
putIterator(mi.descendingHeap[i])
}
mi.allIterators = mi.allIterators[:0]
mi.ascendingHeap = mi.ascendingHeap[:0]
mi.descendingHeap = mi.descendingHeap[:0]
mi.duplicateBuffer = mi.duplicateBuffer[:0]
}
// iteratorHeap implements heap.Interface for managing iterators by key
type iteratorHeap []*iterator
func (h iteratorHeap) Len() int { return len(h) }
func (h iteratorHeap) Less(i, j int) bool {
cmp := bytes.Compare(h[i].currentKey, h[j].currentKey)
if cmp != 0 {
return cmp < 0
}
return h[i].currentTimestamp > h[j].currentTimestamp
}
func (h iteratorHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].index = i
h[j].index = j
}
func (h *iteratorHeap) Push(x interface{}) {
n := len(*h)
item := x.(*iterator)
item.index = n
*h = append(*h, item)
}
func (h *iteratorHeap) Pop() interface{} {
old := *h
n := len(old)
item := old[n-1]
old[n-1] = nil
item.index = -1
*h = old[0 : n-1]
return item
}
// reverseIteratorHeap for descending iteration
type reverseIteratorHeap []*iterator
func (h reverseIteratorHeap) Len() int { return len(h) }
func (h reverseIteratorHeap) Less(i, j int) bool {
cmp := bytes.Compare(h[i].currentKey, h[j].currentKey)
if cmp != 0 {
return cmp > 0
}
return h[i].currentTimestamp > h[j].currentTimestamp
}
func (h reverseIteratorHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].index = i
h[j].index = j
}
func (h *reverseIteratorHeap) Push(x interface{}) {
n := len(*h)
item := x.(*iterator)
item.index = n
*h = append(*h, item)
}
func (h *reverseIteratorHeap) Pop() interface{} {
old := *h
n := len(old)
item := old[n-1]
old[n-1] = nil
item.index = -1
*h = old[0 : n-1]
return item
}