-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathlist.go
More file actions
2437 lines (2143 loc) · 71.8 KB
/
list.go
File metadata and controls
2437 lines (2143 loc) · 71.8 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
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
/*
* SPDX-FileCopyrightText: © Hypermode Inc. <[email protected]>
* SPDX-License-Identifier: Apache-2.0
*/
package posting
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"log"
"math"
"sort"
"github.com/dgryski/go-farm"
"github.com/golang/glog"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
bpb "github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
"github.com/hypermodeinc/dgraph/v25/algo"
"github.com/hypermodeinc/dgraph/v25/codec"
"github.com/hypermodeinc/dgraph/v25/protos/pb"
"github.com/hypermodeinc/dgraph/v25/schema"
"github.com/hypermodeinc/dgraph/v25/tok/index"
"github.com/hypermodeinc/dgraph/v25/types"
"github.com/hypermodeinc/dgraph/v25/types/facets"
"github.com/hypermodeinc/dgraph/v25/x"
)
var (
// ErrRetry can be triggered if the posting list got deleted from memory due to a hard commit.
// In such a case, retry.
ErrRetry = errors.New("Temporary error. Please retry")
// ErrNoValue would be returned if no value was found in the posting list.
ErrNoValue = errors.New("No value found")
// ErrStopIteration is returned when an iteration is terminated early.
ErrStopIteration = errors.New("Stop iteration")
emptyPosting = &pb.Posting{}
maxListSize = mb / 2
)
const (
// Set means set in mutation layer. It contributes 1 in Length.
Set uint32 = 0x01
// Del means delete in mutation layer. It contributes -1 in Length.
Del uint32 = 0x02
// Ovr means overwrite in mutation layer. It contributes 0 in Length.
Ovr uint32 = 0x03
// BitSchemaPosting signals that the value stores a schema or type.
BitSchemaPosting byte = 0x01
// BitDeltaPosting signals that the value stores the delta of a posting list.
BitDeltaPosting byte = 0x04
// BitCompletePosting signals that the values stores a complete posting list.
BitCompletePosting byte = 0x08
// BitEmptyPosting signals that the value stores an empty posting list.
BitEmptyPosting byte = 0x10
)
// List stores the in-memory representation of a posting list.
type List struct {
x.SafeMutex
key []byte
plist *pb.PostingList
mutationMap *MutableLayer
minTs uint64 // commit timestamp of immutable layer, reject reads before this ts.
maxTs uint64 // max commit timestamp seen for this list.
cache []byte
}
// MutableLayer is the structure that will store mutable layer of the posting list. Every posting list has an immutable
// layer and a mutable layer. Whenever posting is added into a list, it's added as deltas into the posting list. Once
// this list of deltas keep piling up, they are converted into a complete posting list through rollup and stored as
// immutable layer. Mutable layer contains all the deltas after the last complete posting list.
// Mutable Layer used to be a map from commitTs to PostingList.
// Every transaction that starts, gets its own copy of a posting list that it stores in the local cache of the txn.
// Everytime we make a copy of the postling list, we had to deep clone the map. If we give the same map by reference
// we start seeing concurrent writes and reads into the map causing issues. With this new MutableLayer struct, we
// know that committedEntries will not get changed and this can be copied by reference without any issues.
// This structure, makes it much faster to clone the Mutable Layer and be faster.
type MutableLayer struct {
committedEntries map[uint64]*pb.PostingList
currentEntries *pb.PostingList
readTs uint64
// Since we are storing the committedEntries and currentEntries separately. We can cache things that are
// going to be used repeatedly.
deleteAllMarker uint64 // Stores the latest deleteAllMarker found in the posting list
// including currentEntries.
committedUids map[uint64]*pb.Posting // Stores the uid to posting mapping in committedEntries.
committedUidsTime uint64 // Stores the latest commitTs in the committedEntries.
length int // Stores the length of the posting list until committedEntries.
lastEntry *pb.PostingList // Stores the last entry stored in committedUids
// We also cache some things required for us to update currentEntries faster
currentUids map[uint64]int // Stores the uid to index mapping in the currentEntries posting list
// Cache for calculated UIDS
isUidsCalculated bool
calculatedUids []uint64
}
func newMutableLayer() *MutableLayer {
return &MutableLayer{
committedEntries: make(map[uint64]*pb.PostingList),
readTs: 0,
deleteAllMarker: math.MaxUint64,
length: math.MaxInt,
committedUids: make(map[uint64]*pb.Posting),
committedUidsTime: math.MaxUint64,
isUidsCalculated: false,
calculatedUids: []uint64{},
}
}
func (mm *MutableLayer) setTs(readTs uint64) {
if mm == nil {
return
}
mm.readTs = readTs
}
// This function clones an existing mutable layer for the new transactions. This function makes sure we copy the right
// things from the existing mutable layer for the new list. It basically copies committedEntries using reference and
// ignores currentEntires and readTs. Similarly, all the cache items related to currentEntries are ignored and
// committedEntries are presevred for the new list.
func (mm *MutableLayer) clone() *MutableLayer {
if mm == nil {
return nil
}
return &MutableLayer{
committedEntries: mm.committedEntries,
readTs: 0,
deleteAllMarker: mm.deleteAllMarker,
committedUids: mm.committedUids,
length: mm.length,
lastEntry: mm.lastEntry,
committedUidsTime: mm.committedUidsTime,
isUidsCalculated: mm.isUidsCalculated,
calculatedUids: mm.calculatedUids,
}
}
// setCurrentEntires() sets the posting in currentEntries. It's used to overwrite the currentEntires. It empties the
// currentUids and sets the readTs.
func (mm *MutableLayer) setCurrentEntries(ts uint64, pl *pb.PostingList) {
if mm == nil {
x.AssertTrue(false)
return
}
if mm.readTs != 0 {
x.AssertTrue(mm.readTs == ts)
}
mm.readTs = ts
mm.currentEntries = pl
clear(mm.currentUids)
mm.isUidsCalculated = false
mm.calculatedUids = nil
mm.deleteAllMarker = math.MaxUint64
mm.populateUidMap(pl)
}
// get() returns the posting stored in the mutable layer at any given timestamp. If the ts is the same as readTs,
// we will return the currentEntries, otherwise it should be the commitTs of old postings.
func (mm *MutableLayer) get(ts uint64) *pb.PostingList {
if mm == nil {
return nil
}
if mm.readTs == ts {
return mm.currentEntries
}
return mm.committedEntries[ts]
}
// len() returns the number of entries in the mutable layer. This should only be used to see if there's any data or
// getting the rough size of the layer. This shouldn't be used in places where accurate length is required. For those
// functions use listLen() instead.
func (mm *MutableLayer) len() int {
if mm == nil {
return 0
}
length := len(mm.committedEntries)
if mm.currentEntries != nil {
length += 1
}
return length
}
// listLen() returns the length of the mutable layer at the readTs. If the readTs changes, the list len could change.
func (mm *MutableLayer) listLen(readTs uint64) int {
if mm == nil {
return 0
}
count := 0
checkPostingForCount := func(pl *pb.PostingList) {
for _, mpost := range pl.Postings {
if hasDeleteAll(mpost) {
// We reach here via either iterating the entire mutable layer, or for just the
// current entries. For both of them we can only see the latest delete all. If a
// posting list has a delete all marker, we still need to set count for all the other
// entries. Hence we need to make sure that count = 0 before we reach here.
continue
}
count += getLengthDelta(mpost.Op)
}
}
// mm.committedUidsTime could be math.MaxUint64 or the actual value. If it's MaxUint64, we know there is no
// entry in the mm, and we can just do iterate. If value is set and readTs < committedUidsTime, we need to
// iterate.
if mm.length == math.MaxInt || readTs < mm.committedUidsTime {
mm.iterate(func(_ uint64, pl *pb.PostingList) {
checkPostingForCount(pl)
}, readTs)
return count
}
count = mm.length
if mm.currentEntries != nil && (readTs == mm.readTs) {
if mm.populateDeleteAll(readTs) == mm.readTs {
// If deleteAll is present, we don't need the count from mm.length.
count = 0
}
checkPostingForCount(mm.currentEntries)
}
return count
}
// populateDeleteAll() returns the deleteAllMarker under readTs. It also finds out and sets the global deleteAllMarker
// in hopes to cache it and use it later if required.
func (mm *MutableLayer) populateDeleteAll(readTs uint64) uint64 {
if mm == nil {
return 0
}
if mm.deleteAllMarker != math.MaxUint64 {
if readTs >= mm.deleteAllMarker {
return mm.deleteAllMarker
}
// I need to calculate deleteAllMarker again. I can't use the one from cache
}
deleteAllMarker := uint64(0)
deleteAllMarkerBelowTs := uint64(0)
mm.iterateCommittedEntries(func(ts uint64, pl *pb.PostingList) {
for _, pl := range pl.Postings {
if hasDeleteAll(pl) {
deleteAllMarker = x.Max(deleteAllMarker, ts)
if ts <= readTs {
deleteAllMarkerBelowTs = x.Max(deleteAllMarkerBelowTs, ts)
}
}
}
})
mm.deleteAllMarker = deleteAllMarker
return deleteAllMarkerBelowTs
}
// iterateCommittedEntries is an internal function that's used to calculate delete all marker and iterate. No other
// function should use this. They should use .iterate() instead.
func (mm *MutableLayer) iterateCommittedEntries(f func(uint64, *pb.PostingList)) {
if mm == nil {
return
}
for ts, pl := range mm.committedEntries {
if pl.CommitTs == ts || ts == mm.readTs {
f(ts, pl)
}
}
if mm.currentEntries != nil {
f(mm.readTs, mm.currentEntries)
}
}
// Before iterating, we have to figure out where the last delete marker is
// Then gather the posts that would be above the marker
func (mm *MutableLayer) iterate(f func(ts uint64, pl *pb.PostingList), readTs uint64) uint64 {
if mm == nil {
return 0
}
deleteAllMarker := mm.populateDeleteAll(readTs)
mm.iterateCommittedEntries(func(ts uint64, pl *pb.PostingList) {
// Note this might not be required, but just here for safety
if ts >= deleteAllMarker && ts <= readTs {
f(ts, pl)
}
})
return deleteAllMarker
}
// insertCommittedPostings inserts an old committed posting in the mutable layer. It also updates fields that are
// cached. This includes deleteAllMarker, length and committedUids map. this should be called while
// building the list only.
func (mm *MutableLayer) insertCommittedPostings(pl *pb.PostingList) {
if mm.committedUidsTime == math.MaxUint64 {
mm.committedUidsTime = 0
}
if mm.length == math.MaxInt64 {
mm.length = 0
}
if mm.deleteAllMarker == math.MaxUint64 {
mm.deleteAllMarker = 0
}
if pl.CommitTs > mm.committedUidsTime {
mm.lastEntry = pl
}
mm.committedUidsTime = x.Max(pl.CommitTs, mm.committedUidsTime)
mm.committedEntries[pl.CommitTs] = pl
for _, mpost := range pl.Postings {
mpost.CommitTs = pl.CommitTs
if hasDeleteAll(mpost) {
if mpost.CommitTs > mm.deleteAllMarker {
mm.deleteAllMarker = mpost.CommitTs
}
// No need to set the length here as we are reading the list in reverse.
continue
}
// If this posting is less than deleteAllMarker, we don't need to add it to the mutable map results.
if mpost.CommitTs >= mm.deleteAllMarker {
mm.length += getLengthDelta(mpost.Op)
}
// We insert old postings in reverse order. So we only need to read the first update to an UID.
if _, ok := mm.committedUids[mpost.Uid]; !ok {
mm.committedUids[mpost.Uid] = mpost
}
}
}
func (mm *MutableLayer) populateUidMap(pl *pb.PostingList) {
if mm.currentUids != nil {
return
}
mm.currentUids = make(map[uint64]int, len(pl.Postings))
for i, post := range pl.Postings {
mm.currentUids[post.Uid] = i
}
}
// insertPosting inserts a new posting in the mutable layers. It updates the currentUids map.
func (mm *MutableLayer) insertPosting(mpost *pb.Posting, hasCountIndex bool) {
if mm.readTs != 0 {
x.AssertTrue(mpost.StartTs == mm.readTs)
}
mm.readTs = mpost.StartTs
if hasDeleteAll(mpost) {
if mpost.CommitTs > mm.deleteAllMarker {
mm.deleteAllMarker = mpost.CommitTs
}
}
if mpost.Uid != 0 {
// If hasCountIndex, in that case while inserting uids, if there's a delete, we only delete from the
// current entries, we dont' insert the delete posting. If we insert the delete posting, there won't be
// any set posting in the list. This would mess up the count. We can do this for all types, however,
// there might be a performance hit becasue of it.
mm.populateUidMap(mm.currentEntries)
if postIndex, ok := mm.currentUids[mpost.Uid]; ok {
if hasCountIndex && mpost.Op == Del {
// If the posting was there before, just remove it from the map, and then remove it
// from the array.
post := mm.currentEntries.Postings[postIndex]
if post.Op == Del {
// No need to do anything
mm.currentEntries.Postings[postIndex] = mpost
return
}
res := mm.currentEntries.Postings[:postIndex]
if postIndex+1 <= len(mm.currentEntries.Postings) {
res = append(res,
mm.currentEntries.Postings[(postIndex+1):]...)
}
mm.currentUids = nil
mm.currentEntries.Postings = res
return
}
mm.currentEntries.Postings[postIndex] = mpost
} else {
mm.currentEntries.Postings = append(mm.currentEntries.Postings, mpost)
mm.currentUids[mpost.Uid] = len(mm.currentEntries.Postings) - 1
}
return
}
mm.currentEntries.Postings = append(mm.currentEntries.Postings, mpost)
}
func (mm *MutableLayer) print() string {
if mm == nil {
return ""
}
return fmt.Sprintf("Committed List: %+v Proposed list: %+v Delete all marker: %d \n",
mm.committedEntries,
mm.currentEntries,
mm.deleteAllMarker)
}
func (l *List) print() string {
return fmt.Sprintf("minTs: %d, plist: %+v, mutationMap: %s", l.minTs, l.plist, l.mutationMap.print())
}
// Return if piterator needs to be searched or not after mutable map and the posting if found.
func (mm *MutableLayer) findPosting(readTs, uid uint64) (bool, *pb.Posting) {
if mm == nil {
return true, nil
}
deleteAllMarker := mm.populateDeleteAll(readTs)
// To get the posting from cached values, we need to make sure that it is >= deleteAllMarker
// If we get it using mm.iterate (in getPosting), we know that we only see postings >= deleteAllMarker
getPostingFromCachedValues := func() (*pb.Posting, uint64) {
if readTs == mm.readTs {
posI, ok := mm.currentUids[uid]
if ok {
return mm.currentEntries.Postings[posI], mm.readTs
}
}
posting, ok := mm.committedUids[uid]
if ok {
return posting, posting.CommitTs
}
return nil, 0
}
// Check if readTs >= committedUidTime. It lets us figure out if we can use the cached values or not.
getPosting := func() *pb.Posting {
// If the timestamp that we are reading for is ahead of the cache map, we can check the map and return.
// Otherwise we need to iterate (slow) the entire map, and keep the latest entry per the commitTs.
if readTs >= mm.committedUidsTime {
posting, ts := getPostingFromCachedValues()
if posting == nil || ts < deleteAllMarker {
return nil
}
return posting
} else {
var posting *pb.Posting
var tsFound uint64
// Since iterate could be out of order, we need to keep a track of the time we saw the posting.
mm.iterate(func(ts uint64, pl *pb.PostingList) {
for _, mpost := range pl.Postings {
if mpost.Uid == uid {
if posting == nil {
posting = mpost
tsFound = ts
} else if tsFound <= ts {
posting = mpost
tsFound = ts
}
}
}
}, readTs)
return posting
}
}
posting := getPosting()
if posting != nil {
// If we find the posting, either we return it, or it has been deleted. Either ways, we don't search
// more in the immutable layer.
if posting.Op != Del {
return false, posting
} else {
return false, nil
}
}
// If delete all is set, immutable layer can't be read. Hence setting searchFurther as false.
if deleteAllMarker > 0 {
return false, nil
}
// No posting was found, and no delete was there. Hence we can now search in immutable layer.
return true, nil
}
func indexEdgeToPbEdge(t *index.KeyValue) *pb.DirectedEdge {
return &pb.DirectedEdge{
Entity: t.Entity,
Attr: t.Attr,
Value: t.Value,
ValueType: pb.Posting_ValType(0),
Op: pb.DirectedEdge_SET,
}
}
// NewList returns a new list with an immutable layer set to plist and the
// timestamp of the immutable layer set to minTs.
func NewList(key []byte, plist *pb.PostingList, minTs uint64) *List {
return &List{
key: key,
plist: plist,
mutationMap: newMutableLayer(),
minTs: minTs,
}
}
func (l *List) maxVersion() uint64 {
l.RLock()
defer l.RUnlock()
return l.maxTs
}
type pIterator struct {
l *List
plist *pb.PostingList
uidPosting *pb.Posting
pidx int // index of postings
plen int
dec *codec.Decoder
uids []uint64
uidx int // Offset into the uids slice
afterUid uint64
splitIdx int
// The timestamp of a delete marker in the mutable layer. If this value is greater
// than zero, then the immutable posting list should not be traversed.
deleteBelowTs uint64
}
func (it *pIterator) seek(l *List, afterUid, deleteBelowTs uint64) error {
// Because we store rollup at commitTs + 1, it could happen that a transaction has a startTs = prev commitTs
// + 1. Within that transcation if there's a delete all, deleteBelowTs (=startT) would be equal to l.minTs
// (rollup timestamp, prev commitTs + 1). So it's allowed deleteBelowTs == l.minTs
if deleteBelowTs > 0 && deleteBelowTs < l.minTs {
return errors.Errorf("deleteBelowTs (%d) must be greater than the minTs in the list (%d)",
deleteBelowTs, l.minTs)
}
it.l = l
it.splitIdx = it.selectInitialSplit(afterUid)
if len(it.l.plist.Splits) > 0 {
plist, err := l.readListPart(it.l.plist.Splits[it.splitIdx])
if err != nil {
return errors.Wrapf(err, "cannot read initial list part for list with base key %s",
hex.EncodeToString(l.key))
}
it.plist = plist
} else {
it.plist = l.plist
}
it.afterUid = afterUid
it.deleteBelowTs = deleteBelowTs
if deleteBelowTs > 0 {
// We don't need to iterate over the immutable layer if this is > 0. Returning here would
// mean it.uids is empty and valid() would return false.
return nil
}
it.uidPosting = &pb.Posting{}
it.dec = &codec.Decoder{Pack: it.plist.Pack}
it.uids = it.dec.Seek(it.afterUid, codec.SeekCurrent)
it.uidx = 0
it.plen = len(it.plist.Postings)
it.pidx = sort.Search(it.plen, func(idx int) bool {
p := it.plist.Postings[idx]
return it.afterUid < p.Uid
})
return nil
}
func (it *pIterator) selectInitialSplit(afterUid uint64) int {
if afterUid == 0 {
return 0
}
for i, startUid := range it.l.plist.Splits {
// If startUid == afterUid, the current block should be selected.
if startUid == afterUid {
return i
}
// If this split starts at an UID greater than afterUid, there might be
// elements in the previous split that need to be checked.
if startUid > afterUid {
return i - 1
}
}
// In case no split's startUid is greater or equal than afterUid, start the
// iteration at the start of the last split.
return len(it.l.plist.Splits) - 1
}
// moveToNextPart re-initializes the iterator at the start of the next list part.
func (it *pIterator) moveToNextPart() error {
it.splitIdx++
plist, err := it.l.readListPart(it.l.plist.Splits[it.splitIdx])
if err != nil {
return errors.Wrapf(err, "cannot move to next list part in iterator for list with key %s",
hex.EncodeToString(it.l.key))
}
it.plist = plist
it.uidPosting = &pb.Posting{}
it.dec = &codec.Decoder{Pack: it.plist.Pack}
// codec.SeekCurrent makes sure we skip returning afterUid during seek.
it.uids = it.dec.Seek(it.afterUid, codec.SeekCurrent)
it.uidx = 0
it.plen = len(it.plist.Postings)
it.pidx = sort.Search(it.plen, func(idx int) bool {
p := it.plist.Postings[idx]
return it.afterUid < p.Uid
})
return nil
}
// moveToNextValidPart moves the iterator to the next part that contains valid data.
// This is used to skip over parts of the list that might not contain postings.
func (it *pIterator) moveToNextValidPart() error {
// Not a multi-part list, the iterator has reached the end of the list.
if len(it.l.plist.Splits) == 0 {
return nil
}
// Iterate while there are no UIDs, and while we have more splits to iterate over.
for len(it.uids) == 0 && it.splitIdx < len(it.l.plist.Splits)-1 {
// moveToNextPart will increment it.splitIdx. Therefore, the for loop must only
// continue until len(splits)-1.
if err := it.moveToNextPart(); err != nil {
return err
}
}
return nil
}
// next advances pIterator to the next valid part.
func (it *pIterator) next() error {
if it.deleteBelowTs > 0 {
it.uids = nil
return nil
}
it.uidx++
if it.uidx < len(it.uids) {
return nil
}
it.uidx = 0
it.uids = it.dec.Next()
return errors.Wrapf(it.moveToNextValidPart(), "cannot advance iterator for list with key %s",
hex.EncodeToString(it.l.key))
}
// valid asserts that pIterator has valid uids, or advances it to the next valid part.
// It returns false if there are no more valid parts.
func (it *pIterator) valid() (bool, error) {
if it.deleteBelowTs > 0 {
it.uids = nil
return false, nil
}
if len(it.uids) > 0 {
return true, nil
}
err := it.moveToNextValidPart()
switch {
case err != nil:
return false, errors.Wrapf(err, "cannot advance iterator when calling pIterator.valid")
case len(it.uids) > 0:
return true, nil
default:
return false, nil
}
}
func (it *pIterator) posting() *pb.Posting {
uid := it.uids[it.uidx]
for it.pidx < it.plen {
p := it.plist.Postings[it.pidx]
if p.Uid > uid {
break
}
if p.Uid == uid {
return p
}
it.pidx++
}
it.uidPosting.Uid = uid
return it.uidPosting
}
// ListOptions is used in List.Uids (in posting) to customize our output list of
// UIDs, for each posting list. It should be pb.to this package.
type ListOptions struct {
ReadTs uint64
AfterUid uint64 // Any UIDs returned must be after this value.
Intersect *pb.List // Intersect results with this list of UIDs.
First int
}
func NewVectorPosting(uid uint64, vec *[]byte) *pb.Posting {
return &pb.Posting{
Value: *vec,
ValType: pb.Posting_BINARY,
Op: Set,
}
}
// NewPosting takes the given edge and returns its equivalent representation as a posting.
func NewPosting(t *pb.DirectedEdge) *pb.Posting {
var op uint32
switch t.Op {
case pb.DirectedEdge_SET:
op = Set
case pb.DirectedEdge_OVR:
op = Ovr
case pb.DirectedEdge_DEL:
op = Del
default:
x.Fatalf("Unhandled operation: %+v", t)
}
var postingType pb.Posting_PostingType
switch {
case len(t.Lang) > 0:
postingType = pb.Posting_VALUE_LANG
case t.ValueId == 0:
postingType = pb.Posting_VALUE
default:
postingType = pb.Posting_REF
}
p := &pb.Posting{
Uid: t.ValueId,
Value: t.Value,
ValType: t.ValueType,
PostingType: postingType,
LangTag: []byte(t.Lang),
Op: op,
Facets: t.Facets,
}
return p
}
func createDeleteAllPosting() *pb.Posting {
return &pb.Posting{
Op: Del,
Value: []byte(x.Star),
Uid: math.MaxUint64,
}
}
func hasDeleteAll(mpost *pb.Posting) bool {
return mpost.Op == Del && bytes.Equal(mpost.Value, []byte(x.Star)) && len(mpost.LangTag) == 0
}
// Ensure that you either abort the uncommitted postings or commit them before calling me.
func (l *List) updateMutationLayer(mpost *pb.Posting, singleUidUpdate, hasCountIndex bool) error {
l.AssertLock()
x.AssertTrue(mpost.Op == Set || mpost.Op == Del || mpost.Op == Ovr)
if l.mutationMap == nil {
l.mutationMap = newMutableLayer()
}
// If we have a delete all, then we replace the map entry with just one.
if hasDeleteAll(mpost) {
plist := &pb.PostingList{}
plist.Postings = append(plist.Postings, mpost)
l.mutationMap.setCurrentEntries(mpost.StartTs, plist)
return nil
}
if l.mutationMap.currentEntries == nil {
l.mutationMap.currentEntries = &pb.PostingList{}
}
l.mutationMap.isUidsCalculated = false
l.mutationMap.calculatedUids = nil
if singleUidUpdate {
// This handles the special case when adding a value to predicates of type uid.
// The current value should be deleted in favor of this value. This needs to
// be done because the fingerprint for the value is not math.MaxUint64 as is
// the case with the rest of the scalar predicates.
newPlist := &pb.PostingList{}
if mpost.Op != Del {
// If we are setting a new value then we can just delete all the older values.
newPlist.Postings = append(newPlist.Postings, createDeleteAllPosting())
}
newPlist.Postings = append(newPlist.Postings, mpost)
l.mutationMap.setCurrentEntries(mpost.StartTs, newPlist)
return nil
}
l.mutationMap.insertPosting(mpost, hasCountIndex)
return nil
}
// TypeID returns the typeid of destination vertex
func TypeID(edge *pb.DirectedEdge) types.TypeID {
if edge.ValueId != 0 {
return types.UidID
}
return types.TypeID(edge.ValueType)
}
func fingerprintEdge(t *pb.DirectedEdge) uint64 {
// There could be a collision if the user gives us a value with Lang = "en" and later gives
// us a value = "en" for the same predicate. We would end up overwriting his older lang
// value.
// All edges with a value without LANGTAG, have the same UID. In other words,
// an (entity, attribute) can only have one untagged value.
var id uint64 = math.MaxUint64
// Value with a lang type.
switch {
case len(t.Lang) > 0:
id = farm.Fingerprint64([]byte(t.Lang))
case schema.State().IsList(t.Attr):
// TODO - When values are deleted for list type, then we should only delete the UID from
// index if no other values produces that index token.
// Value for list type.
id = farm.Fingerprint64(t.Value)
}
return id
}
func (l *List) addMutation(ctx context.Context, txn *Txn, t *pb.DirectedEdge) error {
l.Lock()
defer l.Unlock()
return l.addMutationInternal(ctx, txn, t)
}
func GetConflictKey(pk x.ParsedKey, key []byte, t *pb.DirectedEdge) uint64 {
getKey := func(key []byte, uid uint64) uint64 {
// Instead of creating a string first and then doing a fingerprint, let's do a fingerprint
// here to save memory allocations.
// Not entirely sure about effect on collision chances due to this simple XOR with uid.
return farm.Fingerprint64(key) ^ uid
}
var conflictKey uint64
switch {
case schema.State().HasNoConflict(t.Attr):
break
case schema.State().HasUpsert(t.Attr):
// Consider checking to see if a email id is unique. A user adds:
// <uid> <email> "[email protected]", and there's a string equal tokenizer
// and upsert directive on the schema.
// Then keys are "<email> <uid>" and "<email> [email protected]"
// The first key won't conflict, because two different UIDs can try to
// get the same email id. But, the second key would. Thus, we ensure
// that two users don't set the same email id.
conflictKey = getKey(key, 0)
case pk.IsData() && schema.State().IsList(t.Attr):
// Data keys, irrespective of whether they are UID or values, should be judged based on
// whether they are lists or not. For UID, t.ValueId = UID. For value, t.ValueId =
// fingerprint(value) or could be fingerprint(lang) or something else.
//
// For singular uid predicate, like partner: uid // no list.
// a -> b
// a -> c
// Run concurrently, only one of them should succeed.
// But for friend: [uid], both should succeed.
//
// Similarly, name: string
// a -> "x"
// a -> "y"
// This should definitely have a conflict.
// But, if name: [string], then they can both succeed.
conflictKey = getKey(key, t.ValueId)
case pk.IsData(): // NOT a list. This case must happen after the above case.
conflictKey = getKey(key, 0)
case pk.IsIndex() || pk.IsCountOrCountRev():
// Index keys are by default of type [uid].
conflictKey = getKey(key, t.ValueId)
default:
// Don't assign a conflictKey.
}
return conflictKey
}
// SetTs allows us to set the transaction timestamp in mutation map. Should be used before the posting list is passed
// on to the functions that would read the data.
func (l *List) SetTs(readTs uint64) {
l.mutationMap.setTs(readTs)
}
func (l *List) addMutationInternal(ctx context.Context, txn *Txn, t *pb.DirectedEdge) error {
l.cache = nil
l.AssertLock()
if txn.ShouldAbort() {
return x.ErrConflict
}
mpost := NewPosting(t)
mpost.StartTs = txn.StartTs
if mpost.PostingType != pb.Posting_REF {
t.ValueId = fingerprintEdge(t)
mpost.Uid = t.ValueId
}
// Check whether this mutation is an update for a predicate of type uid.
pk, err := x.Parse(l.key)
if err != nil {
return errors.Wrapf(err, "cannot parse key when adding mutation to list with key %s",
hex.EncodeToString(l.key))
}
pred, ok := schema.State().Get(ctx, t.Attr)
isSingleUidUpdate := ok && !pred.GetList() && pred.GetValueType() == pb.Posting_UID &&
pk.IsData() && mpost.Op != Del && mpost.PostingType == pb.Posting_REF
if err != l.updateMutationLayer(mpost, isSingleUidUpdate, pred.GetCount() && (pk.IsData() || pk.IsReverse())) {
return errors.Wrapf(err, "cannot update mutation layer of key %s with value %+v",
hex.EncodeToString(l.key), mpost)
}
x.PrintMutationEdge(t, pk, txn.StartTs)
// We ensure that commit marks are applied to posting lists in the right
// order. We can do so by proposing them in the same order as received by the Oracle delta
// stream from Zero, instead of in goroutines.
txn.addConflictKey(GetConflictKey(pk, l.key, t))
return nil
}
// getMutation returns a marshaled version of posting list mutation stored internally.
func (l *List) getPosting(startTs uint64) *pb.PostingList {
l.RLock()
defer l.RUnlock()
return l.mutationMap.get(startTs)
}
func (l *List) GetPosting(startTs uint64) *pb.PostingList {
return l.getPosting(startTs)
}
// getMutation returns a marshaled version of posting list mutation stored internally.
func (l *List) getMutation(startTs uint64) []byte {
l.RLock()
defer l.RUnlock()
if pl := l.mutationMap.get(startTs); pl != nil {
data, err := proto.Marshal(pl)
x.Check(err)
return data
}
return nil
}
func getLengthDelta(op uint32) int {
if op == Del {
return -1
} else if op == Set {
return 1
}
return 0
}
// Here we update the mutableLayer as required. If the refresh is set to true, we make a new map for committedEntries
// as it could be shared by multiple different lists. Then we update the mutableLayer to commit the data we recieved.
// We also empty out the current stuff. (currentUids, currentEntries and readTs)
func (l *List) setMutationAfterCommit(startTs, commitTs uint64, pl *pb.PostingList, refresh bool) {
pl.CommitTs = commitTs
for _, p := range pl.Postings {
p.CommitTs = commitTs
}
x.AssertTrue(pl.Pack == nil)
l.Lock()
defer l.Unlock()
if l.mutationMap == nil {
l.mutationMap = newMutableLayer()
}
if refresh {
newMap := make(map[uint64]*pb.PostingList, l.mutationMap.len())
for k, v := range l.mutationMap.committedEntries {
newMap[k] = proto.Clone(v).(*pb.PostingList)