Repository navigation
Expand file tree
/
Copy pathatomic_index.go
More file actions
939 lines (856 loc) · 24.3 KB
/
Copy pathatomic_index.go
File metadata and controls
939 lines (856 loc) · 24.3 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
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
package bmdb
import (
"encoding/binary"
"log"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/RoaringBitmap/roaring"
)
// AtomicBTree provides lock-free reads by storing a snapshot of *BTree in an
// atomic.Value. Writes are implemented via copy-on-write: a writer clones the
// current BTree, applies the mutation, and stores the new snapshot. Writes are
// serialized with a small mutex; readers never lock.
type AtomicBTree struct {
mu sync.Mutex
v atomic.Value // stores *BTree
}
func NewAtomicBTree(initial *BTree) *AtomicBTree {
a := &AtomicBTree{}
if initial == nil {
a.v.Store(NewBTree())
return a
}
// fast clone using underlying btree Copy (shadow copy)
a.v.Store(initial.Copy())
return a
}
func (a *AtomicBTree) load() *BTree {
return a.v.Load().(*BTree)
}
// Find is lock-free.
func (a *AtomicBTree) Find(key []byte) (*Record, bool) {
return a.load().Find(key)
}
// Count is lock-free.
func (a *AtomicBTree) Count() int {
return a.load().Count()
}
// All returns all records (lock-free snapshot).
func (a *AtomicBTree) All() []*Record {
return a.load().All()
}
// AllItems returns all items (lock-free snapshot).
func (a *AtomicBTree) AllItems() []*Item {
return a.load().AllItems()
}
// Range returns records in [start, end] from the snapshot.
func (a *AtomicBTree) Range(start, end []byte) []*Record {
return a.load().Range(start, end)
}
// PrefixScan performs a prefix scan on the snapshot.
func (a *AtomicBTree) PrefixScan(prefix []byte, offset, limitNum int) []*Record {
return a.load().PrefixScan(prefix, offset, limitNum)
}
// PrefixSearchScan performs a prefix search scan with regex filter.
func (a *AtomicBTree) PrefixSearchScan(prefix []byte, reg string, offset, limitNum int) []*Record {
return a.load().PrefixSearchScan(prefix, reg, offset, limitNum)
}
// Min returns smallest item from snapshot.
func (a *AtomicBTree) Min() (*Item, bool) { return a.load().Min() }
// Max returns largest item from snapshot.
func (a *AtomicBTree) Max() (*Item, bool) { return a.load().Max() }
// Insert performs COW + atomic swap. Writes are serialized by mu.
func (a *AtomicBTree) Insert(record *Record) bool {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
// Use fast shadow copy provided by the underlying btree library.
nb := old.Copy()
replaced := nb.Insert(record)
a.v.Store(nb)
return replaced
}
// Delete performs COW + atomic swap. Writes are serialized by mu.
func (a *AtomicBTree) Delete(key []byte) bool {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
nb := old.Copy()
deleted := nb.Delete(key)
a.v.Store(nb)
return deleted
}
// ReplaceFromBTree replaces the atomic snapshot with a clone of the provided
// BTree. Callers should hold any external locks necessary to serialize
// concurrent updates for the same bucket.
func (a *AtomicBTree) ReplaceFromBTree(bt *BTree) {
a.mu.Lock()
defer a.mu.Unlock()
// Use the fast copy provided by the concrete BTree implementation
a.v.Store(bt.Copy())
}
// --- AtomicList (moved here) ---
// AtomicList provides lock-free reads by storing a snapshot of *List in an
// atomic.Value. Writes do copy-on-write and are serialized by a mutex.
type AtomicList struct {
// lock-free: use atomic.Pointer to hold *List snapshot
ptr atomic.Pointer[List]
}
func NewAtomicList(initial *List) *AtomicList {
a := &AtomicList{}
if initial == nil {
a.ptr.Store(NewList())
return a
}
a.ptr.Store(cloneList(initial))
return a
}
func cloneList(l *List) *List {
if l == nil {
return NewList()
}
nl := &List{
Items: make(map[string]*BTree, len(l.Items)),
TTL: make(map[string]uint32, len(l.TTL)),
TimeStamp: make(map[string]uint64, len(l.TimeStamp)),
Seq: make(map[string]*HeadTailSeq, len(l.Seq)),
}
for k, bt := range l.Items {
// Use BTree.Copy to do a fast shadow copy of each per-key BTree.
if bt != nil {
nl.Items[k] = bt.Copy()
} else {
nl.Items[k] = NewBTree()
}
}
for k, v := range l.TTL {
nl.TTL[k] = v
}
for k, v := range l.TimeStamp {
nl.TimeStamp[k] = v
}
for k, v := range l.Seq {
copySeq := *v
nl.Seq[k] = ©Seq
}
return nl
}
func (a *AtomicList) load() *List {
p := a.ptr.Load()
if p == nil {
return NewList()
}
return p
}
// LPush (lock-free COW with CAS)
func (a *AtomicList) LPush(key string, r *Record) error {
for {
old := a.load()
nl := cloneList(old)
if err := nl.LPush(key, r); err != nil {
return err
}
if a.ptr.CompareAndSwap(old, nl) {
return nil
}
// retry on concurrent modification
runtime.Gosched()
}
}
// RPush (lock-free COW with CAS)
func (a *AtomicList) RPush(key string, r *Record) error {
for {
old := a.load()
nl := cloneList(old)
if err := nl.RPush(key, r); err != nil {
return err
}
if a.ptr.CompareAndSwap(old, nl) {
return nil
}
runtime.Gosched()
}
}
// LPop (lock-free COW with CAS)
func (a *AtomicList) LPop(key string) (*Record, error) {
for {
old := a.load()
nl := cloneList(old)
r, err := nl.LPop(key)
if err != nil {
return nil, err
}
if a.ptr.CompareAndSwap(old, nl) {
return r, nil
}
runtime.Gosched()
}
}
// RPop (lock-free COW with CAS)
func (a *AtomicList) RPop(key string) (*Record, error) {
for {
old := a.load()
nl := cloneList(old)
r, err := nl.RPop(key)
if err != nil {
return nil, err
}
if a.ptr.CompareAndSwap(old, nl) {
return r, nil
}
runtime.Gosched()
}
}
// LRange (read-only)
func (a *AtomicList) LRange(key string, start, end int) ([]*Record, error) {
return a.load().LRange(key, start, end)
}
// Size (read-only)
func (a *AtomicList) Size(key string) (int, error) {
return a.load().Size(key)
}
// IsExpire (may mutate: do COW and CAS)
func (a *AtomicList) IsExpire(key string) bool {
for {
old := a.load()
nl := cloneList(old)
res := nl.IsExpire(key)
if !res {
return false
}
if a.ptr.CompareAndSwap(old, nl) {
return true
}
runtime.Gosched()
}
}
// GetSeq returns Seq entry if exists (read-only)
func (a *AtomicList) GetSeq(key string) (*HeadTailSeq, bool) {
if v, ok := a.load().Seq[key]; ok {
copySeq := *v
return ©Seq, true
}
return nil, false
}
// GetItems returns underlying *BTree for a key (read-only snapshot). Caller must not mutate it.
func (a *AtomicList) GetItems(key string) (*BTree, bool) {
bt, ok := a.load().Items[key]
return bt, ok
}
// GetValidIndexes mirrors List.getValidIndexes on a snapshot.
func (a *AtomicList) GetValidIndexes(key string, indexes []int) map[int]struct{} {
snap := a.load()
idxes := make(map[int]struct{})
size, err := snap.Size(key)
if err != nil || size == 0 {
return idxes
}
for _, idx := range indexes {
if idx < 0 || idx >= size {
continue
}
idxes[idx] = struct{}{}
}
return idxes
}
// ReplaceFromList replaces the atomic snapshot with a clone of the provided
// List. This uses an unconditional store (no external locks required).
func (a *AtomicList) ReplaceFromList(l *List) {
if l != nil {
// Diagnostic: attempt to log one key's size change to aid debugging
for k := range l.Items {
var before int
old := a.load()
if old != nil {
sz, err := old.Size(k)
if err == nil {
before = sz
}
}
a.ptr.Store(cloneList(l))
aft := a.load()
after, _ := aft.Size(k)
log.Printf("AtomicList.ReplaceFromList: key=%s size_before=%d size_after=%d", k, before, after)
return
}
}
a.ptr.Store(cloneList(l))
}
// --- AtomicSet (moved here) ---
// AtomicSet provides lock-free reads for Set via atomic snapshot.
type AtomicSet struct {
mu sync.Mutex
v atomic.Value // *Set
}
func NewAtomicSet(initial *Set) *AtomicSet {
a := &AtomicSet{}
if initial == nil {
a.v.Store(NewSet())
return a
}
// clone
clone := NewSet()
for k, m := range initial.M {
clone.M[k] = make(map[uint32]*Record)
for hash, rec := range m {
clone.M[k][hash] = rec
}
}
a.v.Store(clone)
return a
}
// ReplaceFromSet replaces the atomic snapshot with a clone of the provided
// Set. Callers should hold any external locks necessary to serialize
// concurrent updates for the same bucket.
func (a *AtomicSet) ReplaceFromSet(s *Set) {
a.mu.Lock()
defer a.mu.Unlock()
if s == nil {
a.v.Store(NewSet())
return
}
clone := NewSet()
for k, m := range s.M {
clone.M[k] = make(map[uint32]*Record, len(m))
for hash, rec := range m {
clone.M[k][hash] = rec
}
}
a.v.Store(clone)
}
func (a *AtomicSet) load() *Set { return a.v.Load().(*Set) }
func (a *AtomicSet) SIsMember(key string, val []byte) (bool, error) {
return a.load().SIsMember(key, val)
}
func (a *AtomicSet) SAdd(key string, vals [][]byte, records []*Record) error {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
nb := NewSet()
// shallow clone
for k, m := range old.M {
nb.M[k] = make(map[uint32]*Record)
for hash, rec := range m {
nb.M[k][hash] = rec
}
}
err := nb.SAdd(key, vals, records)
a.v.Store(nb)
return err
}
func (a *AtomicSet) SRem(key string, val []byte) error {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
nb := NewSet()
for k, m := range old.M {
nb.M[k] = make(map[uint32]*Record)
for hash, rec := range m {
nb.M[k][hash] = rec
}
}
err := nb.SRem(key, val)
a.v.Store(nb)
return err
}
// SMove moves a member from key1 to key2 atomically on the snapshot via COW.
func (a *AtomicSet) SMove(key1, key2 string, value []byte) (bool, error) {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
nb := NewSet()
for k, m := range old.M {
nb.M[k] = make(map[uint32]*Record, len(m))
for hash, rec := range m {
nb.M[k][hash] = rec
}
}
ok, err := nb.SMove(key1, key2, value)
a.v.Store(nb)
return ok, err
}
func (a *AtomicSet) SCard(key string) int {
return a.load().SCard(key)
}
// SAreMembers checks membership for multiple values on snapshot
func (a *AtomicSet) SAreMembers(key string, values ...[]byte) (bool, error) {
return a.load().SAreMembers(key, values...)
}
// SMembers returns snapshot member records
func (a *AtomicSet) SMembers(key string) ([]*Record, error) {
return a.load().SMembers(key)
}
// SHasKey returns whether the set exists in snapshot
func (a *AtomicSet) SHasKey(key string) bool {
return a.load().SHasKey(key)
}
// SnapshotHashes returns a compact binary snapshot of the set hashes to allow
// efficient publish/replication without copying full record values. Format:
// [N:uint32] then N * { klen:uint16, key, m:uint32, m * uint32(hash) }
func (a *AtomicSet) SnapshotHashes() ([]byte, error) {
s := a.load()
// Precompute total size to allocate a single buffer.
// Format: 4 bytes N, then for each key: 2 bytes klen, klen bytes key, 4 bytes m, then m * 4 bytes hashes
total := 4 // N
for key, members := range s.M {
total += 2 + len(key) // klen + key
total += 4 // m
total += 4 * len(members) // each hash uint32
}
buf := make([]byte, total)
off := 0
binary.BigEndian.PutUint32(buf[off:], uint32(len(s.M)))
off += 4
for key, members := range s.M {
kb := []byte(key)
binary.BigEndian.PutUint16(buf[off:], uint16(len(kb)))
off += 2
copy(buf[off:], kb)
off += len(kb)
binary.BigEndian.PutUint32(buf[off:], uint32(len(members)))
off += 4
for hash := range members {
binary.BigEndian.PutUint32(buf[off:], hash)
off += 4
}
}
return buf, nil
}
// --- PerKeyAtomicZSet (moved here) ---
// Backoff parameters for CAS retries on hot keys.
// defaults used when db or options are not available
const (
defaultPerKeyBackoffThreshold = 4
defaultPerKeyBackoffBaseMicros = 50
defaultPerKeyBackoffMaxMillis = 5
defaultPerKeyFallbackThreshold = 100
)
// PerKeyAtomicZSet stores per-key atomic pointers to SkipList so updates to a
// single zset key only affect that key's pointer. This minimizes contention
// across keys and avoids global snapshot cloning.
type PerKeyAtomicZSet struct {
// map from key to atomic pointer to SkipList. Protected by map-level
// synchronization when keys are inserted; we rely on callers to create
// the PerKeyAtomicZSet under bucket lock when needed. For simplicity
// here we lazily create entries with a small sync.Once-like approach.
M map[string]*atomic.Pointer[SkipList]
db *DB
// mu protects creation of entries in M and retries map
mu sync.Mutex
// per-key retry counters (pointer to int64 so we can atomic.Add on them)
retries map[string]*int64
// total number of CAS retries across all keys
totalRetries int64
// adaptive fallback mutexes for hot keys
fallback map[string]*sync.Mutex
}
func NewPerKeyAtomicZSet(db *DB) *PerKeyAtomicZSet {
return &PerKeyAtomicZSet{M: make(map[string]*atomic.Pointer[SkipList]), db: db}
}
// AtomicZSet is the public type used by the rest of the codebase. For now
// it's an alias to PerKeyAtomicZSet to preserve existing constructors.
type AtomicZSet = PerKeyAtomicZSet
// NewAtomicZSet constructs an AtomicZSet from an optional existing SortedSet.
// If zs is non-nil, we initialize per-key pointers by shallow-cloning each
// SkipList (copying nodes) so the atomic snapshots start with the same data.
func NewAtomicZSet(zs *SortedSet) *AtomicZSet {
var db *DB
if zs != nil {
db = zs.db
}
az := NewPerKeyAtomicZSet(db)
if zs != nil {
// copy existing keys
for key, sl := range zs.M {
ptr := az.ensurePtrForKey(key)
nb := newSkipList(db)
for _, node := range sl.dict {
// derive the value bytes for hashing from the record when possible.
// Passing nil above caused getFnv32 to hash an empty slice and
// produced identical hashes for all nodes, collapsing the dict.
var val []byte
if db != nil && node.record != nil {
if v, err := db.getValueByRecord(node.record); err == nil {
val = v
}
}
_ = nb.Put(node.score, val, node.record)
}
ptr.Store(nb)
}
}
return (*AtomicZSet)(az)
}
func (p *PerKeyAtomicZSet) ensurePtrForKey(key string) *atomic.Pointer[SkipList] {
// fast path: try without lock
if ptr, ok := p.M[key]; ok {
return ptr
}
// need to create, lock
p.mu.Lock()
defer p.mu.Unlock()
if ptr, ok := p.M[key]; ok {
return ptr
}
ptr := &atomic.Pointer[SkipList]{}
// initialize with an empty skiplist
ptr.Store(newSkipList(p.db))
p.M[key] = ptr
if p.retries == nil {
p.retries = make(map[string]*int64)
}
if _, ok := p.retries[key]; !ok {
p.retries[key] = new(int64)
}
if p.fallback == nil {
p.fallback = make(map[string]*sync.Mutex)
}
if _, ok := p.fallback[key]; !ok {
p.fallback[key] = &sync.Mutex{}
}
return ptr
}
// getPtrIfExists returns the pointer for key if present in the map without
// creating a new entry. The boolean return indicates presence.
func (p *PerKeyAtomicZSet) getPtrIfExists(key string) (*atomic.Pointer[SkipList], bool) {
// fast path without lock
if ptr, ok := p.M[key]; ok {
return ptr, true
}
// slow path: lock and check again
p.mu.Lock()
defer p.mu.Unlock()
ptr, ok := p.M[key]
return ptr, ok
}
// ZAdd performs lock-free per-key update by loading the SkipList pointer,
// cloning the SkipList for mutation and CAS-swapping the pointer.
func (p *PerKeyAtomicZSet) ZAdd(key string, score SCORE, val []byte, record *Record) error {
ptr := p.ensurePtrForKey(key)
// determine thresholds from options or defaults
fallbackThreshold := defaultPerKeyFallbackThreshold
backoffThreshold := defaultPerKeyBackoffThreshold
backoffBaseMicros := defaultPerKeyBackoffBaseMicros
backoffMaxMillis := defaultPerKeyBackoffMaxMillis
if p.db != nil {
backoffThreshold = p.db.opt.PerKeyBackoffThreshold
backoffBaseMicros = p.db.opt.PerKeyBackoffBaseMicros
backoffMaxMillis = p.db.opt.PerKeyBackoffMaxMillis
if p.db.opt.PerKeyFallbackThreshold > 0 {
fallbackThreshold = int(p.db.opt.PerKeyFallbackThreshold)
}
}
// fast path: if this key has crossed fallback threshold, use per-key mutex
if cntPtr, ok := p.retries[key]; ok && atomic.LoadInt64(cntPtr) >= int64(fallbackThreshold) {
mu := p.fallback[key]
mu.Lock()
defer mu.Unlock()
old := ptr.Load()
nb := newSkipList(p.db)
for _, node := range old.dict {
_ = nb.Put(node.score, nil, node.record)
}
_ = nb.Put(score, val, record)
ptr.Store(nb)
return nil
}
var localRetries int64
for {
old := ptr.Load()
// clone skiplist by creating a new one and copying nodes
nb := newSkipList(p.db)
for _, node := range old.dict {
_ = nb.Put(node.score, nil, node.record)
}
if p.db != nil && p.db.opt.DebugLogs {
existed := old.length > 0
_ = nb.Put(score, val, record)
log.Printf("perkey_atomic_zset: ZAdd key=%s score=%v existed=%v", key, float64(score), existed)
} else {
_ = nb.Put(score, val, record)
}
if ptr.CompareAndSwap(old, nb) {
if localRetries > 0 && p.db != nil && p.db.opt.DebugLogs {
log.Printf("perkey_atomic_zset: ZAdd key=%s CAS retries=%d", key, localRetries)
}
return nil
}
// CAS failed: record retry and loop
localRetries++
p.incrementRetry(key)
// apply small per-key backoff for hot keys
if localRetries >= int64(backoffThreshold) {
backoffUnits := localRetries - int64(backoffThreshold) + 1
baseDelay := time.Duration(backoffUnits*int64(backoffBaseMicros)) * time.Microsecond
maxDelay := time.Duration(backoffMaxMillis) * time.Millisecond
if baseDelay > maxDelay {
baseDelay = maxDelay
}
// add small jitter to reduce synchronized wakeups
jitter := time.Duration((backoffUnits % 5)) * time.Microsecond
delay := baseDelay + jitter
time.Sleep(delay)
}
}
}
func (p *PerKeyAtomicZSet) ZRem(key string, val []byte) (*Record, error) {
ptr := p.ensurePtrForKey(key)
// determine thresholds from options or defaults
fallbackThreshold := defaultPerKeyFallbackThreshold
if p.db != nil && p.db.opt.PerKeyFallbackThreshold > 0 {
fallbackThreshold = int(p.db.opt.PerKeyFallbackThreshold)
}
// fallback path for hot keys
if cntPtr, ok := p.retries[key]; ok && atomic.LoadInt64(cntPtr) >= int64(fallbackThreshold) {
mu := p.fallback[key]
mu.Lock()
defer mu.Unlock()
old := ptr.Load()
nb := newSkipList(p.db)
for _, node := range old.dict {
_ = nb.Put(node.score, nil, node.record)
}
rec := nb.RemoveFromValue(val)
ptr.Store(nb)
if rec == nil {
return nil, ErrSortedSetMemberNotExist
}
return rec, nil
}
var localRetries int64
for {
old := ptr.Load()
nb := newSkipList(p.db)
for _, node := range old.dict {
_ = nb.Put(node.score, nil, node.record)
}
rec := nb.RemoveFromValue(val)
if ptr.CompareAndSwap(old, nb) {
if localRetries > 0 && p.db != nil && p.db.opt.DebugLogs {
log.Printf("perkey_atomic_zset: ZRem key=%s CAS retries=%d", key, localRetries)
}
if rec == nil {
return nil, ErrSortedSetMemberNotExist
}
return rec, nil
}
// record retry and loop
localRetries++
p.incrementRetry(key)
}
}
// --- Read helpers for PerKeyAtomicZSet ---
// ZRangeByRank returns records and scores for rank range on the snapshot.
func (p *PerKeyAtomicZSet) ZRangeByRank(key string, start, end int) ([]*Record, []float64, error) {
ptr, ok := p.getPtrIfExists(key)
if !ok {
return nil, nil, ErrSortedSetNotFound
}
sl := ptr.Load()
nodes := sl.GetByRankRange(start, end, false)
records := make([]*Record, len(nodes))
scores := make([]float64, len(nodes))
for i, node := range nodes {
records[i] = node.record
scores[i] = float64(node.score)
}
return records, scores, nil
}
// ZRangeByScore returns records and scores by score range on the snapshot.
func (p *PerKeyAtomicZSet) ZRangeByScore(key string, start SCORE, end SCORE, opts *GetByScoreRangeOptions) ([]*Record, []float64, error) {
ptr, ok := p.getPtrIfExists(key)
if !ok {
return nil, nil, ErrSortedSetNotFound
}
sl := ptr.Load()
nodes := sl.GetByScoreRange(start, end, opts)
records := make([]*Record, len(nodes))
scores := make([]float64, len(nodes))
for i, node := range nodes {
records[i] = node.record
scores[i] = float64(node.score)
}
return records, scores, nil
}
// ZPeekMax returns the max record and score.
func (p *PerKeyAtomicZSet) ZPeekMax(key string) (*Record, SCORE, error) {
ptr, ok := p.getPtrIfExists(key)
if !ok {
return nil, 0, ErrSortedSetNotFound
}
sl := ptr.Load()
node := sl.PeekMax()
if node == nil {
return nil, 0, ErrSortedSetIsEmpty
}
return node.record, node.score, nil
}
// ZPeekMin returns the min record and score.
func (p *PerKeyAtomicZSet) ZPeekMin(key string) (*Record, SCORE, error) {
ptr, ok := p.getPtrIfExists(key)
if !ok {
return nil, 0, ErrSortedSetNotFound
}
sl := ptr.Load()
node := sl.PeekMin()
if node == nil {
return nil, 0, ErrSortedSetIsEmpty
}
return node.record, node.score, nil
}
// ZCard returns the number of elements in the skiplist for key.
func (p *PerKeyAtomicZSet) ZCard(key string) (int, error) {
ptr, ok := p.getPtrIfExists(key)
if !ok {
return 0, ErrSortedSetNotFound
}
sl := ptr.Load()
return int(sl.length), nil
}
// ZCount counts elements between scores on the snapshot.
func (p *PerKeyAtomicZSet) ZCount(key string, start SCORE, end SCORE, opts *GetByScoreRangeOptions) (int, error) {
ptr, ok := p.getPtrIfExists(key)
if !ok {
return 0, ErrSortedSetNotFound
}
sl := ptr.Load()
return len(sl.GetByScoreRange(start, end, opts)), nil
}
// incrementRetry atomically increments per-key and total retry counters.
func (p *PerKeyAtomicZSet) incrementRetry(key string) {
// ensure counter exists
p.mu.Lock()
if p.retries == nil {
p.retries = make(map[string]*int64)
}
if _, ok := p.retries[key]; !ok {
p.retries[key] = new(int64)
}
cntPtr := p.retries[key]
p.mu.Unlock()
atomic.AddInt64(cntPtr, 1)
atomic.AddInt64(&p.totalRetries, 1)
}
// GetRetryMetrics returns a snapshot of per-key retry counts and the total retries.
func (p *PerKeyAtomicZSet) GetRetryMetrics() (map[string]int64, int64) {
p.mu.Lock()
defer p.mu.Unlock()
res := make(map[string]int64, len(p.retries))
for k, ptr := range p.retries {
res[k] = atomic.LoadInt64(ptr)
}
total := atomic.LoadInt64(&p.totalRetries)
return res, total
}
// LogRetryMetrics logs non-zero retry metrics when DebugLogs is enabled.
func (p *PerKeyAtomicZSet) LogRetryMetrics() {
if p.db == nil || !p.db.opt.DebugLogs {
return
}
metrics, total := p.GetRetryMetrics()
if total == 0 {
return
}
log.Printf("perkey_atomic_zset: total CAS retries=%d", total)
for k, v := range metrics {
if v > 0 {
log.Printf("perkey_atomic_zset: key=%s CAS retries=%d", k, v)
}
}
}
// --- AtomicFulltext ---
// AtomicFulltext provides lock-free reads for a fulltext inverted index by
// storing a snapshot of map[string]*roaring.Bitmap in an atomic.Value. Writes
// perform copy-on-write and are serialized by a mutex.
type AtomicFulltext struct {
mu sync.Mutex
v atomic.Value // stores map[string]*roaring.Bitmap
}
// NewAtomicFulltext constructs an AtomicFulltext from an optional initial map.
func NewAtomicFulltext(initial map[string]*roaring.Bitmap) *AtomicFulltext {
a := &AtomicFulltext{}
if initial == nil {
a.v.Store(make(map[string]*roaring.Bitmap))
return a
}
// shallow-clone bitmaps
cp := make(map[string]*roaring.Bitmap, len(initial))
for k, bm := range initial {
if bm == nil {
continue
}
cp[k] = roaring.BitmapOf(bm.ToArray()...)
}
a.v.Store(cp)
return a
}
func (a *AtomicFulltext) load() map[string]*roaring.Bitmap {
return a.v.Load().(map[string]*roaring.Bitmap)
}
// GetPosting returns a clone of the posting list for term (nil if missing).
func (a *AtomicFulltext) GetPosting(term string) *roaring.Bitmap {
snap := a.load()
if bm, ok := snap[term]; ok {
return roaring.BitmapOf(bm.ToArray()...)
}
return nil
}
// SearchAnd returns the intersection of postings for the provided terms.
func (a *AtomicFulltext) SearchAnd(terms []string) *roaring.Bitmap {
if len(terms) == 0 {
return roaring.New()
}
snap := a.load()
var res *roaring.Bitmap
for _, t := range terms {
bm, ok := snap[t]
if !ok {
return roaring.New()
}
if res == nil {
res = roaring.BitmapOf(bm.ToArray()...)
} else {
res.And(bm)
}
}
if res == nil {
return roaring.New()
}
return res
}
// Add inserts docID into the posting list for term (COW + atomic swap).
func (a *AtomicFulltext) Add(term string, docID uint32) {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
nb := make(map[string]*roaring.Bitmap, len(old)+1)
for k, bm := range old {
nb[k] = roaring.BitmapOf(bm.ToArray()...)
}
bm, ok := nb[term]
if !ok || bm == nil {
bm = roaring.New()
nb[term] = bm
}
bm.Add(docID)
a.v.Store(nb)
}
// Remove deletes docID from the posting list for term (COW + atomic swap).
func (a *AtomicFulltext) Remove(term string, docID uint32) {
a.mu.Lock()
defer a.mu.Unlock()
old := a.load()
nb := make(map[string]*roaring.Bitmap, len(old))
for k, bm := range old {
nb[k] = roaring.BitmapOf(bm.ToArray()...)
}
if bm, ok := nb[term]; ok {
bm.Remove(docID)
if bm.IsEmpty() {
delete(nb, term)
}
}
a.v.Store(nb)
}