-
Notifications
You must be signed in to change notification settings - Fork 460
/
batch.go
2486 lines (2268 loc) · 85.3 KB
/
batch.go
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
// Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"math"
"sort"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/cockroachdb/crlib/crtime"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/batchrepr"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/batchskl"
"github.com/cockroachdb/pebble/internal/humanize"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/private"
"github.com/cockroachdb/pebble/internal/rangedel"
"github.com/cockroachdb/pebble/internal/rangekey"
"github.com/cockroachdb/pebble/internal/rawalloc"
"github.com/cockroachdb/pebble/internal/treeprinter"
)
const (
invalidBatchCount = 1<<32 - 1
maxVarintLen32 = 5
defaultBatchInitialSize = 1 << 10 // 1 KB
defaultBatchMaxRetainedSize = 1 << 20 // 1 MB
)
// ErrNotIndexed means that a read operation on a batch failed because the
// batch is not indexed and thus doesn't support reads.
var ErrNotIndexed = errors.New("pebble: batch not indexed")
// ErrInvalidBatch indicates that a batch is invalid or otherwise corrupted.
var ErrInvalidBatch = batchrepr.ErrInvalidBatch
// ErrBatchTooLarge indicates that a batch is invalid or otherwise corrupted.
var ErrBatchTooLarge = base.MarkCorruptionError(errors.Newf("pebble: batch too large: >= %s", humanize.Bytes.Uint64(maxBatchSize)))
// DeferredBatchOp represents a batch operation (eg. set, merge, delete) that is
// being inserted into the batch. Indexing is not performed on the specified key
// until Finish is called, hence the name deferred. This struct lets the caller
// copy or encode keys/values directly into the batch representation instead of
// copying into an intermediary buffer then having pebble.Batch copy off of it.
type DeferredBatchOp struct {
index *batchskl.Skiplist
// Key and Value point to parts of the binary batch representation where
// keys and values should be encoded/copied into. len(Key) and len(Value)
// bytes must be copied into these slices respectively before calling
// Finish(). Changing where these slices point to is not allowed.
Key, Value []byte
offset uint32
}
// Finish completes the addition of this batch operation, and adds it to the
// index if necessary. Must be called once (and exactly once) keys/values
// have been filled into Key and Value. Not calling Finish or not
// copying/encoding keys will result in an incomplete index, and calling Finish
// twice may result in a panic.
func (d DeferredBatchOp) Finish() error {
if d.index != nil {
if err := d.index.Add(d.offset); err != nil {
return err
}
}
return nil
}
// A Batch is a sequence of Sets, Merges, Deletes, DeleteRanges, RangeKeySets,
// RangeKeyUnsets, and/or RangeKeyDeletes that are applied atomically. Batch
// implements the Reader interface, but only an indexed batch supports reading
// (without error) via Get or NewIter. A non-indexed batch will return
// ErrNotIndexed when read from. A batch is not safe for concurrent use, and
// consumers should use a batch per goroutine or provide their own
// synchronization.
//
// # Indexing
//
// Batches can be optionally indexed (see DB.NewIndexedBatch). An indexed batch
// allows iteration via an Iterator (see Batch.NewIter). The iterator provides
// a merged view of the operations in the batch and the underlying
// database. This is implemented by treating the batch as an additional layer
// in the LSM where every entry in the batch is considered newer than any entry
// in the underlying database (batch entries have the InternalKeySeqNumBatch
// bit set). By treating the batch as an additional layer in the LSM, iteration
// supports all batch operations (i.e. Set, Merge, Delete, DeleteRange,
// RangeKeySet, RangeKeyUnset, RangeKeyDelete) with minimal effort.
//
// The same key can be operated on multiple times in a batch, though only the
// latest operation will be visible. For example, Put("a", "b"), Delete("a")
// will cause the key "a" to not be visible in the batch. Put("a", "b"),
// Put("a", "c") will cause a read of "a" to return the value "c".
//
// The batch index is implemented via an skiplist (internal/batchskl). While
// the skiplist implementation is very fast, inserting into an indexed batch is
// significantly slower than inserting into a non-indexed batch. Only use an
// indexed batch if you require reading from it.
//
// # Atomic commit
//
// The operations in a batch are persisted by calling Batch.Commit which is
// equivalent to calling DB.Apply(batch). A batch is committed atomically by
// writing the internal batch representation to the WAL, adding all of the
// batch operations to the memtable associated with the WAL, and then
// incrementing the visible sequence number so that subsequent reads can see
// the effects of the batch operations. If WriteOptions.Sync is true, a call to
// Batch.Commit will guarantee that the batch is persisted to disk before
// returning. See commitPipeline for more on the implementation details.
//
// # Large batches
//
// The size of a batch is limited only by available memory (be aware that
// indexed batches require considerably additional memory for the skiplist
// structure). A given WAL file has a single memtable associated with it (this
// restriction could be removed, but doing so is onerous and complex). And a
// memtable has a fixed size due to the underlying fixed size arena. Note that
// this differs from RocksDB where a memtable can grow arbitrarily large using
// a list of arena chunks. In RocksDB this is accomplished by storing pointers
// in the arena memory, but that isn't possible in Go.
//
// During Batch.Commit, a batch which is larger than a threshold (>
// MemTableSize/2) is wrapped in a flushableBatch and inserted into the queue
// of memtables. A flushableBatch forces WAL to be rotated, but that happens
// anyways when the memtable becomes full so this does not cause significant
// WAL churn. Because the flushableBatch is readable as another layer in the
// LSM, Batch.Commit returns as soon as the flushableBatch has been added to
// the queue of memtables.
//
// Internally, a flushableBatch provides Iterator support by sorting the batch
// contents (the batch is sorted once, when it is added to the memtable
// queue). Sorting the batch contents and insertion of the contents into a
// memtable have the same big-O time, but the constant factor dominates
// here. Sorting is significantly faster and uses significantly less memory.
//
// # Internal representation
//
// The internal batch representation is a contiguous byte buffer with a fixed
// 12-byte header, followed by a series of records.
//
// +-------------+------------+--- ... ---+
// | SeqNum (8B) | Count (4B) | Entries |
// +-------------+------------+--- ... ---+
//
// Each record has a 1-byte kind tag prefix, followed by 1 or 2 length prefixed
// strings (varstring):
//
// +-----------+-----------------+-------------------+
// | Kind (1B) | Key (varstring) | Value (varstring) |
// +-----------+-----------------+-------------------+
//
// A varstring is a varint32 followed by N bytes of data. The Kind tags are
// exactly those specified by InternalKeyKind. The following table shows the
// format for records of each kind:
//
// InternalKeyKindDelete varstring
// InternalKeyKindLogData varstring
// InternalKeyKindIngestSST varstring
// InternalKeyKindSet varstring varstring
// InternalKeyKindMerge varstring varstring
// InternalKeyKindRangeDelete varstring varstring
// InternalKeyKindRangeKeySet varstring varstring
// InternalKeyKindRangeKeyUnset varstring varstring
// InternalKeyKindRangeKeyDelete varstring varstring
//
// The intuitive understanding here are that the arguments to Delete, Set,
// Merge, DeleteRange and RangeKeyDelete are encoded into the batch. The
// RangeKeySet and RangeKeyUnset operations are slightly more complicated,
// encoding their end key, suffix and value [in the case of RangeKeySet] within
// the Value varstring. For more information on the value encoding for
// RangeKeySet and RangeKeyUnset, see the internal/rangekey package.
//
// The internal batch representation is the on disk format for a batch in the
// WAL, and thus stable. New record kinds may be added, but the existing ones
// will not be modified.
type Batch struct {
batchInternal
applied atomic.Bool
// lifecycle is used to negotiate the lifecycle of a Batch. A Batch and its
// underlying batchInternal.data byte slice may be reused. There are two
// mechanisms for reuse:
//
// 1. The caller may explicitly call [Batch.Reset] to reset the batch to be
// empty (while retaining the underlying repr's buffer).
// 2. The caller may call [Batch.Close], passing ownership off to Pebble,
// which may reuse the batch's memory to service new callers to
// [DB.NewBatch].
//
// There's a complication to reuse: When WAL failover is configured, the
// Pebble commit pipeline may retain a pointer to the batch.data beyond the
// return of [Batch.Commit]. The user of the Batch may commit their batch
// and call Close or Reset before the commit pipeline is finished reading
// the data slice. Recycling immediately would cause a data race.
//
// To resolve this data race, this [lifecycle] atomic is used to determine
// safety and responsibility of reusing a batch. The low bits of the atomic
// are used as a reference count (really just the lowest bit—in practice
// there's only 1 code path that references). The [Batch] is passed into
// [wal.Writer]'s WriteRecord method as a [RefCount] implementation. The
// wal.Writer guarantees that if it will read [Batch.data] after the call to
// WriteRecord returns, it will increment the reference count. When it's
// complete, it'll unreference through invoking [Batch.Unref].
//
// When the committer of a batch indicates intent to recycle a Batch through
// calling [Batch.Reset] or [Batch.Close], the lifecycle atomic is read. If
// an outstanding reference remains, it's unsafe to reuse Batch.data yet. In
// [Batch.Reset] the caller wants to reuse the [Batch] immediately, so we
// discard b.data to recycle the struct but not the underlying byte slice.
// In [Batch.Close], we set a special high bit [batchClosedBit] on lifecycle
// that indicates that the user will not use [Batch] again and we're free to
// recycle it when safe. When the commit pipeline eventually calls
// [Batch.Unref], the [batchClosedBit] is noticed and the batch is
// recycled.
lifecycle atomic.Int32
}
// batchClosedBit is a bit stored on Batch.lifecycle to indicate that the user
// called [Batch.Close] to release a Batch, but an open reference count
// prevented immediate recycling.
const batchClosedBit = 1 << 30
// TODO(jackson): Hide the wal.RefCount implementation from the public Batch interface.
// Ref implements wal.RefCount. If the WAL writer may need to read b.data after
// it returns, it invokes Ref to increment the lifecycle's reference count. When
// it's finished, it invokes Unref.
func (b *Batch) Ref() {
b.lifecycle.Add(+1)
}
// Unref implemets wal.RefCount.
func (b *Batch) Unref() {
if v := b.lifecycle.Add(-1); (v ^ batchClosedBit) == 0 {
// The [batchClosedBit] high bit is set, and there are no outstanding
// references. The user of the Batch called [Batch.Close], expecting the
// batch to be recycled. However, our outstanding reference count
// prevented recycling. As the last to dereference, we're now
// responsible for releasing the batch.
b.lifecycle.Store(0)
b.release()
}
}
// batchInternal contains the set of fields within Batch that are non-atomic and
// capable of being reset using a *b = batchInternal{} struct copy.
type batchInternal struct {
// Data is the wire format of a batch's log entry:
// - 8 bytes for a sequence number of the first batch element,
// or zeroes if the batch has not yet been applied,
// - 4 bytes for the count: the number of elements in the batch,
// or "\xff\xff\xff\xff" if the batch is invalid,
// - count elements, being:
// - one byte for the kind
// - the varint-string user key,
// - the varint-string value (if kind != delete).
// The sequence number and count are stored in little-endian order.
//
// The data field can be (but is not guaranteed to be) nil for new
// batches. Large batches will set the data field to nil when committed as
// the data has been moved to a flushableBatch and inserted into the queue of
// memtables.
data []byte
comparer *base.Comparer
opts batchOptions
// An upper bound on required space to add this batch to a memtable.
// Note that although batches are limited to 4 GiB in size, that limit
// applies to len(data), not the memtable size. The upper bound on the
// size of a memtable node is larger than the overhead of the batch's log
// encoding, so memTableSize is larger than len(data) and may overflow a
// uint32.
memTableSize uint64
// The db to which the batch will be committed. Do not change this field
// after the batch has been created as it might invalidate internal state.
// Batch.memTableSize is only refreshed if Batch.db is set. Setting db to
// nil once it has been set implies that the Batch has encountered an error.
db *DB
// The count of records in the batch. This count will be stored in the batch
// data whenever Repr() is called.
count uint64
// The count of range deletions in the batch. Updated every time a range
// deletion is added.
countRangeDels uint64
// The count of range key sets, unsets and deletes in the batch. Updated
// every time a RANGEKEYSET, RANGEKEYUNSET or RANGEKEYDEL key is added.
countRangeKeys uint64
// A deferredOp struct, stored in the Batch so that a pointer can be returned
// from the *Deferred() methods rather than a value.
deferredOp DeferredBatchOp
// An optional skiplist keyed by offset into data of the entry.
index *batchskl.Skiplist
rangeDelIndex *batchskl.Skiplist
rangeKeyIndex *batchskl.Skiplist
// Fragmented range deletion tombstones. Cached the first time a range
// deletion iterator is requested. The cache is invalidated whenever a new
// range deletion is added to the batch. This cache can only be used when
// opening an iterator to read at a batch sequence number >=
// tombstonesSeqNum. This is the case for all new iterators created over a
// batch but it's not the case for all cloned iterators.
tombstones []keyspan.Span
tombstonesSeqNum base.SeqNum
// Fragmented range key spans. Cached the first time a range key iterator is
// requested. The cache is invalidated whenever a new range key
// (RangeKey{Set,Unset,Del}) is added to the batch. This cache can only be
// used when opening an iterator to read at a batch sequence number >=
// tombstonesSeqNum. This is the case for all new iterators created over a
// batch but it's not the case for all cloned iterators.
rangeKeys []keyspan.Span
rangeKeysSeqNum base.SeqNum
// The flushableBatch wrapper if the batch is too large to fit in the
// memtable.
flushable *flushableBatch
// minimumFormatMajorVersion indicates the format major version required in
// order to commit this batch. If an operation requires a particular format
// major version, it ratchets the batch's minimumFormatMajorVersion. When
// the batch is committed, this is validated against the database's current
// format major version.
minimumFormatMajorVersion FormatMajorVersion
// Synchronous Apply uses the commit WaitGroup for both publishing the
// seqnum and waiting for the WAL fsync (if needed). Asynchronous
// ApplyNoSyncWait, which implies WriteOptions.Sync is true, uses the commit
// WaitGroup for publishing the seqnum and the fsyncWait WaitGroup for
// waiting for the WAL fsync.
//
// TODO(sumeer): if we find that ApplyNoSyncWait in conjunction with
// SyncWait is causing higher memory usage because of the time duration
// between when the sync is already done, and a goroutine calls SyncWait
// (followed by Batch.Close), we could separate out {fsyncWait, commitErr}
// into a separate struct that is allocated separately (using another
// sync.Pool), and only that struct needs to outlive Batch.Close (which
// could then be called immediately after ApplyNoSyncWait). commitStats
// will also need to be in this separate struct.
commit sync.WaitGroup
fsyncWait sync.WaitGroup
commitStats BatchCommitStats
commitErr error
// Position bools together to reduce the sizeof the struct.
// ingestedSSTBatch indicates that the batch contains one or more key kinds
// of InternalKeyKindIngestSST. If the batch contains key kinds of IngestSST
// then it will only contain key kinds of IngestSST.
ingestedSSTBatch bool
// committing is set to true when a batch begins to commit. It's used to
// ensure the batch is not mutated concurrently. It is not an atomic
// deliberately, so as to avoid the overhead on batch mutations. This is
// okay, because under correct usage this field will never be accessed
// concurrently. It's only under incorrect usage the memory accesses of this
// variable may violate memory safety. Since we don't use atomics here,
// false negatives are possible.
committing bool
}
// BatchCommitStats exposes stats related to committing a batch.
//
// NB: there is no Pebble internal tracing (using LoggerAndTracer) of slow
// batch commits. The caller can use these stats to do their own tracing as
// needed.
type BatchCommitStats struct {
// TotalDuration is the time spent in DB.{Apply,ApplyNoSyncWait} or
// Batch.Commit, plus the time waiting in Batch.SyncWait. If there is a gap
// between calling ApplyNoSyncWait and calling SyncWait, that gap could
// include some duration in which real work was being done for the commit
// and will not be included here. This missing time is considered acceptable
// since the goal of these stats is to understand user-facing latency.
//
// TotalDuration includes time spent in various queues both inside Pebble
// and outside Pebble (I/O queues, goroutine scheduler queue, mutex wait
// etc.). For some of these queues (which we consider important) the wait
// times are included below -- these expose low-level implementation detail
// and are meant for expert diagnosis and subject to change. There may be
// unaccounted time after subtracting those values from TotalDuration.
TotalDuration time.Duration
// SemaphoreWaitDuration is the wait time for semaphores in
// commitPipeline.Commit.
SemaphoreWaitDuration time.Duration
// WALQueueWaitDuration is the wait time for allocating memory blocks in the
// LogWriter (due to the LogWriter not writing fast enough). At the moment
// this is duration is always zero because a single WAL will allow
// allocating memory blocks up to the entire memtable size. In the future,
// we may pipeline WALs and bound the WAL queued blocks separately, so this
// field is preserved for that possibility.
WALQueueWaitDuration time.Duration
// MemTableWriteStallDuration is the wait caused by a write stall due to too
// many memtables (due to not flushing fast enough).
MemTableWriteStallDuration time.Duration
// L0ReadAmpWriteStallDuration is the wait caused by a write stall due to
// high read amplification in L0 (due to not compacting fast enough out of
// L0).
L0ReadAmpWriteStallDuration time.Duration
// WALRotationDuration is the wait time for WAL rotation, which includes
// syncing and closing the old WAL and creating (or reusing) a new one.
WALRotationDuration time.Duration
// CommitWaitDuration is the wait for publishing the seqnum plus the
// duration for the WAL sync (if requested). The former should be tiny and
// one can assume that this is all due to the WAL sync.
CommitWaitDuration time.Duration
}
var _ Reader = (*Batch)(nil)
var _ Writer = (*Batch)(nil)
var batchPool = sync.Pool{
New: func() interface{} {
return &Batch{}
},
}
type indexedBatch struct {
batch Batch
index batchskl.Skiplist
}
var indexedBatchPool = sync.Pool{
New: func() interface{} {
return &indexedBatch{}
},
}
func newBatch(db *DB, opts ...BatchOption) *Batch {
b := batchPool.Get().(*Batch)
b.db = db
b.opts.ensureDefaults()
for _, opt := range opts {
opt(&b.opts)
}
return b
}
func newBatchWithSize(db *DB, size int, opts ...BatchOption) *Batch {
b := newBatch(db, opts...)
if cap(b.data) < size {
b.data = rawalloc.New(0, size)
}
return b
}
func newIndexedBatch(db *DB, comparer *Comparer) *Batch {
i := indexedBatchPool.Get().(*indexedBatch)
i.batch.comparer = comparer
i.batch.db = db
i.batch.index = &i.index
i.batch.index.Init(&i.batch.data, comparer.Compare, comparer.AbbreviatedKey)
i.batch.opts.ensureDefaults()
return &i.batch
}
func newIndexedBatchWithSize(db *DB, comparer *Comparer, size int) *Batch {
b := newIndexedBatch(db, comparer)
if cap(b.data) < size {
b.data = rawalloc.New(0, size)
}
return b
}
// nextSeqNum returns the batch "sequence number" that will be given to the next
// key written to the batch. During iteration keys within an indexed batch are
// given a sequence number consisting of their offset within the batch combined
// with the base.SeqNumBatchBit bit. These sequence numbers are only
// used during iteration, and the keys are assigned ordinary sequence numbers
// when the batch is committed.
func (b *Batch) nextSeqNum() base.SeqNum {
return base.SeqNum(len(b.data)) | base.SeqNumBatchBit
}
func (b *Batch) release() {
if b.db == nil {
// The batch was not created using newBatch or newIndexedBatch, or an error
// was encountered. We don't try to reuse batches that encountered an error
// because they might be stuck somewhere in the system and attempting to
// reuse such batches is a recipe for onerous debugging sessions. Instead,
// let the GC do its job.
return
}
b.db = nil
// NB: This is ugly (it would be cleaner if we could just assign a Batch{}),
// but necessary so that we can use atomic.StoreUint32 for the Batch.applied
// field. Without using an atomic to clear that field the Go race detector
// complains.
b.reset()
b.comparer = nil
if b.index == nil {
batchPool.Put(b)
} else {
b.index, b.rangeDelIndex, b.rangeKeyIndex = nil, nil, nil
indexedBatchPool.Put((*indexedBatch)(unsafe.Pointer(b)))
}
}
func (b *Batch) refreshMemTableSize() error {
b.memTableSize = 0
if len(b.data) < batchrepr.HeaderLen {
return nil
}
b.countRangeDels = 0
b.countRangeKeys = 0
b.minimumFormatMajorVersion = 0
for r := b.Reader(); ; {
kind, key, value, ok, err := r.Next()
if !ok {
if err != nil {
return err
}
break
}
switch kind {
case InternalKeyKindRangeDelete:
b.countRangeDels++
case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
b.countRangeKeys++
case InternalKeyKindSet, InternalKeyKindDelete, InternalKeyKindMerge, InternalKeyKindSingleDelete, InternalKeyKindSetWithDelete:
// fallthrough
case InternalKeyKindDeleteSized:
if b.minimumFormatMajorVersion < FormatDeleteSizedAndObsolete {
b.minimumFormatMajorVersion = FormatDeleteSizedAndObsolete
}
case InternalKeyKindLogData:
// LogData does not contribute to memtable size.
continue
case InternalKeyKindIngestSST:
if b.minimumFormatMajorVersion < FormatFlushableIngest {
b.minimumFormatMajorVersion = FormatFlushableIngest
}
// This key kind doesn't contribute to the memtable size.
continue
case InternalKeyKindExcise:
if b.minimumFormatMajorVersion < FormatFlushableIngestExcises {
b.minimumFormatMajorVersion = FormatFlushableIngestExcises
}
// This key kind doesn't contribute to the memtable size.
continue
default:
// Note In some circumstances this might be temporary memory
// corruption that can be recovered by discarding the batch and
// trying again. In other cases, the batch repr might've been
// already persisted elsewhere, and we'll loop continuously trying
// to commit the same corrupted batch. The caller is responsible for
// distinguishing.
return errors.Wrapf(ErrInvalidBatch, "unrecognized kind %v", kind)
}
b.memTableSize += memTableEntrySize(len(key), len(value))
}
return nil
}
// Apply the operations contained in the batch to the receiver batch.
//
// It is safe to modify the contents of the arguments after Apply returns.
//
// Apply returns ErrInvalidBatch if the provided batch is invalid in any way.
func (b *Batch) Apply(batch *Batch, _ *WriteOptions) error {
if b.ingestedSSTBatch {
panic("pebble: invalid batch application")
}
if len(batch.data) == 0 {
return nil
}
if len(batch.data) < batchrepr.HeaderLen {
return ErrInvalidBatch
}
offset := len(b.data)
if offset == 0 {
b.init(offset)
offset = batchrepr.HeaderLen
}
b.data = append(b.data, batch.data[batchrepr.HeaderLen:]...)
b.setCount(b.Count() + batch.Count())
if b.db != nil || b.index != nil {
// Only iterate over the new entries if we need to track memTableSize or in
// order to update the index.
for iter := batchrepr.Reader(b.data[offset:]); len(iter) > 0; {
offset := uintptr(unsafe.Pointer(&iter[0])) - uintptr(unsafe.Pointer(&b.data[0]))
kind, key, value, ok, err := iter.Next()
if !ok {
if err != nil {
return err
}
break
}
switch kind {
case InternalKeyKindRangeDelete:
b.countRangeDels++
case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
b.countRangeKeys++
case InternalKeyKindIngestSST, InternalKeyKindExcise:
panic("pebble: invalid key kind for batch")
case InternalKeyKindLogData:
// LogData does not contribute to memtable size.
continue
case InternalKeyKindSet, InternalKeyKindDelete, InternalKeyKindMerge,
InternalKeyKindSingleDelete, InternalKeyKindSetWithDelete, InternalKeyKindDeleteSized:
// fallthrough
default:
// Note In some circumstances this might be temporary memory
// corruption that can be recovered by discarding the batch and
// trying again. In other cases, the batch repr might've been
// already persisted elsewhere, and we'll loop continuously
// trying to commit the same corrupted batch. The caller is
// responsible for distinguishing.
return errors.Wrapf(ErrInvalidBatch, "unrecognized kind %v", kind)
}
if b.index != nil {
var err error
switch kind {
case InternalKeyKindRangeDelete:
b.tombstones = nil
b.tombstonesSeqNum = 0
if b.rangeDelIndex == nil {
b.rangeDelIndex = batchskl.NewSkiplist(&b.data, b.comparer.Compare, b.comparer.AbbreviatedKey)
}
err = b.rangeDelIndex.Add(uint32(offset))
case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
b.rangeKeys = nil
b.rangeKeysSeqNum = 0
if b.rangeKeyIndex == nil {
b.rangeKeyIndex = batchskl.NewSkiplist(&b.data, b.comparer.Compare, b.comparer.AbbreviatedKey)
}
err = b.rangeKeyIndex.Add(uint32(offset))
default:
err = b.index.Add(uint32(offset))
}
if err != nil {
return err
}
}
b.memTableSize += memTableEntrySize(len(key), len(value))
}
}
return nil
}
// Get gets the value for the given key. It returns ErrNotFound if the Batch
// does not contain the key.
//
// The caller should not modify the contents of the returned slice, but it is
// safe to modify the contents of the argument after Get returns. The returned
// slice will remain valid until the returned Closer is closed. On success, the
// caller MUST call closer.Close() or a memory leak will occur.
func (b *Batch) Get(key []byte) ([]byte, io.Closer, error) {
if b.index == nil {
return nil, nil, ErrNotIndexed
}
return b.db.getInternal(key, b, nil /* snapshot */)
}
func (b *Batch) prepareDeferredKeyValueRecord(keyLen, valueLen int, kind InternalKeyKind) {
if b.committing {
panic("pebble: batch already committing")
}
if len(b.data) == 0 {
b.init(keyLen + valueLen + 2*binary.MaxVarintLen64 + batchrepr.HeaderLen)
}
b.count++
b.memTableSize += memTableEntrySize(keyLen, valueLen)
pos := len(b.data)
b.deferredOp.offset = uint32(pos)
b.grow(1 + 2*maxVarintLen32 + keyLen + valueLen)
b.data[pos] = byte(kind)
pos++
{
// TODO(peter): Manually inlined version binary.PutUvarint(). This is 20%
// faster on BenchmarkBatchSet on go1.13. Remove if go1.14 or future
// versions show this to not be a performance win.
x := uint32(keyLen)
for x >= 0x80 {
b.data[pos] = byte(x) | 0x80
x >>= 7
pos++
}
b.data[pos] = byte(x)
pos++
}
b.deferredOp.Key = b.data[pos : pos+keyLen]
pos += keyLen
{
// TODO(peter): Manually inlined version binary.PutUvarint(). This is 20%
// faster on BenchmarkBatchSet on go1.13. Remove if go1.14 or future
// versions show this to not be a performance win.
x := uint32(valueLen)
for x >= 0x80 {
b.data[pos] = byte(x) | 0x80
x >>= 7
pos++
}
b.data[pos] = byte(x)
pos++
}
b.deferredOp.Value = b.data[pos : pos+valueLen]
// Shrink data since varints may be shorter than the upper bound.
b.data = b.data[:pos+valueLen]
}
func (b *Batch) prepareDeferredKeyRecord(keyLen int, kind InternalKeyKind) {
if b.committing {
panic("pebble: batch already committing")
}
if len(b.data) == 0 {
b.init(keyLen + binary.MaxVarintLen64 + batchrepr.HeaderLen)
}
b.count++
b.memTableSize += memTableEntrySize(keyLen, 0)
pos := len(b.data)
b.deferredOp.offset = uint32(pos)
b.grow(1 + maxVarintLen32 + keyLen)
b.data[pos] = byte(kind)
pos++
{
// TODO(peter): Manually inlined version binary.PutUvarint(). Remove if
// go1.13 or future versions show this to not be a performance win. See
// BenchmarkBatchSet.
x := uint32(keyLen)
for x >= 0x80 {
b.data[pos] = byte(x) | 0x80
x >>= 7
pos++
}
b.data[pos] = byte(x)
pos++
}
b.deferredOp.Key = b.data[pos : pos+keyLen]
b.deferredOp.Value = nil
// Shrink data since varint may be shorter than the upper bound.
b.data = b.data[:pos+keyLen]
}
// AddInternalKey allows the caller to add an internal key of point key or range
// key kinds (but not RangeDelete) to a batch. Passing in an internal key of
// kind RangeDelete will result in a panic. Note that the seqnum in the internal
// key is effectively ignored, even though the Kind is preserved. This is
// because the batch format does not allow for a per-key seqnum to be specified,
// only a batch-wide one.
//
// Note that non-indexed keys (IngestKeyKind{LogData,IngestSST}) are not
// supported with this method as they require specialized logic.
func (b *Batch) AddInternalKey(key *base.InternalKey, value []byte, _ *WriteOptions) error {
keyLen := len(key.UserKey)
hasValue := false
switch kind := key.Kind(); kind {
case InternalKeyKindRangeDelete:
panic("unexpected range delete in AddInternalKey")
case InternalKeyKindSingleDelete, InternalKeyKindDelete:
b.prepareDeferredKeyRecord(keyLen, kind)
b.deferredOp.index = b.index
case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
b.prepareDeferredKeyValueRecord(keyLen, len(value), kind)
hasValue = true
b.incrementRangeKeysCount()
default:
b.prepareDeferredKeyValueRecord(keyLen, len(value), kind)
hasValue = true
b.deferredOp.index = b.index
}
copy(b.deferredOp.Key, key.UserKey)
if hasValue {
copy(b.deferredOp.Value, value)
}
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
// in go1.13 will remove the need for this.
if b.index != nil {
if err := b.index.Add(b.deferredOp.offset); err != nil {
return err
}
}
return nil
}
// Set adds an action to the batch that sets the key to map to the value.
//
// It is safe to modify the contents of the arguments after Set returns.
func (b *Batch) Set(key, value []byte, _ *WriteOptions) error {
deferredOp := b.SetDeferred(len(key), len(value))
copy(deferredOp.Key, key)
copy(deferredOp.Value, value)
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
// in go1.13 will remove the need for this.
if b.index != nil {
if err := b.index.Add(deferredOp.offset); err != nil {
return err
}
}
return nil
}
// SetDeferred is similar to Set in that it adds a set operation to the batch,
// except it only takes in key/value lengths instead of complete slices,
// letting the caller encode into those objects and then call Finish() on the
// returned object.
func (b *Batch) SetDeferred(keyLen, valueLen int) *DeferredBatchOp {
b.prepareDeferredKeyValueRecord(keyLen, valueLen, InternalKeyKindSet)
b.deferredOp.index = b.index
return &b.deferredOp
}
// Merge adds an action to the batch that merges the value at key with the new
// value. The details of the merge are dependent upon the configured merge
// operator.
//
// It is safe to modify the contents of the arguments after Merge returns.
func (b *Batch) Merge(key, value []byte, _ *WriteOptions) error {
deferredOp := b.MergeDeferred(len(key), len(value))
copy(deferredOp.Key, key)
copy(deferredOp.Value, value)
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
// in go1.13 will remove the need for this.
if b.index != nil {
if err := b.index.Add(deferredOp.offset); err != nil {
return err
}
}
return nil
}
// MergeDeferred is similar to Merge in that it adds a merge operation to the
// batch, except it only takes in key/value lengths instead of complete slices,
// letting the caller encode into those objects and then call Finish() on the
// returned object.
func (b *Batch) MergeDeferred(keyLen, valueLen int) *DeferredBatchOp {
b.prepareDeferredKeyValueRecord(keyLen, valueLen, InternalKeyKindMerge)
b.deferredOp.index = b.index
return &b.deferredOp
}
// Delete adds an action to the batch that deletes the entry for key.
//
// It is safe to modify the contents of the arguments after Delete returns.
func (b *Batch) Delete(key []byte, _ *WriteOptions) error {
deferredOp := b.DeleteDeferred(len(key))
copy(deferredOp.Key, key)
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
// in go1.13 will remove the need for this.
if b.index != nil {
if err := b.index.Add(deferredOp.offset); err != nil {
return err
}
}
return nil
}
// DeleteDeferred is similar to Delete in that it adds a delete operation to
// the batch, except it only takes in key/value lengths instead of complete
// slices, letting the caller encode into those objects and then call Finish()
// on the returned object.
func (b *Batch) DeleteDeferred(keyLen int) *DeferredBatchOp {
b.prepareDeferredKeyRecord(keyLen, InternalKeyKindDelete)
b.deferredOp.index = b.index
return &b.deferredOp
}
// DeleteSized behaves identically to Delete, but takes an additional
// argument indicating the size of the value being deleted. DeleteSized
// should be preferred when the caller has the expectation that there exists
// a single internal KV pair for the key (eg, the key has not been
// overwritten recently), and the caller knows the size of its value.
//
// DeleteSized will record the value size within the tombstone and use it to
// inform compaction-picking heuristics which strive to reduce space
// amplification in the LSM. This "calling your shot" mechanic allows the
// storage engine to more accurately estimate and reduce space amplification.
//
// It is safe to modify the contents of the arguments after DeleteSized
// returns.
func (b *Batch) DeleteSized(key []byte, deletedValueSize uint32, _ *WriteOptions) error {
deferredOp := b.DeleteSizedDeferred(len(key), deletedValueSize)
copy(b.deferredOp.Key, key)
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Check if in a
// later Go release this is unnecessary.
if b.index != nil {
if err := b.index.Add(deferredOp.offset); err != nil {
return err
}
}
return nil
}
// DeleteSizedDeferred is similar to DeleteSized in that it adds a sized delete
// operation to the batch, except it only takes in key length instead of a
// complete key slice, letting the caller encode into the DeferredBatchOp.Key
// slice and then call Finish() on the returned object.
func (b *Batch) DeleteSizedDeferred(keyLen int, deletedValueSize uint32) *DeferredBatchOp {
if b.minimumFormatMajorVersion < FormatDeleteSizedAndObsolete {
b.minimumFormatMajorVersion = FormatDeleteSizedAndObsolete
}
// Encode the sum of the key length and the value in the value.
v := uint64(deletedValueSize) + uint64(keyLen)
// Encode `v` as a varint.
var buf [binary.MaxVarintLen64]byte
n := 0
{
x := v
for x >= 0x80 {
buf[n] = byte(x) | 0x80
x >>= 7
n++
}
buf[n] = byte(x)
n++
}
// NB: In batch entries and sstable entries, values are stored as
// varstrings. Here, the value is itself a simple varint. This results in an
// unnecessary double layer of encoding:
// varint(n) varint(deletedValueSize)
// The first varint will always be 1-byte, since a varint-encoded uint64
// will never exceed 128 bytes. This unnecessary extra byte and wrapping is
// preserved to avoid special casing across the database, and in particular
// in sstable block decoding which is performance sensitive.
b.prepareDeferredKeyValueRecord(keyLen, n, InternalKeyKindDeleteSized)
b.deferredOp.index = b.index
copy(b.deferredOp.Value, buf[:n])
return &b.deferredOp
}
// SingleDelete adds an action to the batch that single deletes the entry for key.
// See Writer.SingleDelete for more details on the semantics of SingleDelete.
//
// It is safe to modify the contents of the arguments after SingleDelete returns.
func (b *Batch) SingleDelete(key []byte, _ *WriteOptions) error {
deferredOp := b.SingleDeleteDeferred(len(key))
copy(deferredOp.Key, key)
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
// in go1.13 will remove the need for this.
if b.index != nil {
if err := b.index.Add(deferredOp.offset); err != nil {
return err
}
}
return nil
}
// SingleDeleteDeferred is similar to SingleDelete in that it adds a single delete
// operation to the batch, except it only takes in key/value lengths instead of
// complete slices, letting the caller encode into those objects and then call
// Finish() on the returned object.
func (b *Batch) SingleDeleteDeferred(keyLen int) *DeferredBatchOp {
b.prepareDeferredKeyRecord(keyLen, InternalKeyKindSingleDelete)
b.deferredOp.index = b.index
return &b.deferredOp
}
// DeleteRange deletes all of the point keys (and values) in the range
// [start,end) (inclusive on start, exclusive on end). DeleteRange does NOT
// delete overlapping range keys (eg, keys set via RangeKeySet).
//
// It is safe to modify the contents of the arguments after DeleteRange
// returns.
func (b *Batch) DeleteRange(start, end []byte, _ *WriteOptions) error {
deferredOp := b.DeleteRangeDeferred(len(start), len(end))
copy(deferredOp.Key, start)
copy(deferredOp.Value, end)
// TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
// in go1.13 will remove the need for this.
if deferredOp.index != nil {
if err := deferredOp.index.Add(deferredOp.offset); err != nil {
return err
}