/
writer.go
2450 lines (2218 loc) · 84.5 KB
/
writer.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 2011 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 sstable
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"runtime"
"sort"
"sync"
"github.com/cespare/xxhash/v2"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/bytealloc"
"github.com/cockroachdb/pebble/internal/cache"
"github.com/cockroachdb/pebble/internal/crc"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/private"
"github.com/cockroachdb/pebble/internal/rangekey"
"github.com/cockroachdb/pebble/objstorage"
)
// encodedBHPEstimatedSize estimates the size of the encoded BlockHandleWithProperties.
// It would also be nice to account for the length of the data block properties here,
// but isn't necessary since this is an estimate.
const encodedBHPEstimatedSize = binary.MaxVarintLen64 * 2
var errWriterClosed = errors.New("pebble: writer is closed")
// WriterMetadata holds info about a finished sstable.
type WriterMetadata struct {
Size uint64
SmallestPoint InternalKey
// LargestPoint, LargestRangeKey, LargestRangeDel should not be accessed
// before Writer.Close is called, because they may only be set on
// Writer.Close.
LargestPoint InternalKey
SmallestRangeDel InternalKey
LargestRangeDel InternalKey
SmallestRangeKey InternalKey
LargestRangeKey InternalKey
HasPointKeys bool
HasRangeDelKeys bool
HasRangeKeys bool
SmallestSeqNum uint64
LargestSeqNum uint64
Properties Properties
}
// SetSmallestPointKey sets the smallest point key to the given key.
// NB: this method set the "absolute" smallest point key. Any existing key is
// overridden.
func (m *WriterMetadata) SetSmallestPointKey(k InternalKey) {
m.SmallestPoint = k
m.HasPointKeys = true
}
// SetSmallestRangeDelKey sets the smallest rangedel key to the given key.
// NB: this method set the "absolute" smallest rangedel key. Any existing key is
// overridden.
func (m *WriterMetadata) SetSmallestRangeDelKey(k InternalKey) {
m.SmallestRangeDel = k
m.HasRangeDelKeys = true
}
// SetSmallestRangeKey sets the smallest range key to the given key.
// NB: this method set the "absolute" smallest range key. Any existing key is
// overridden.
func (m *WriterMetadata) SetSmallestRangeKey(k InternalKey) {
m.SmallestRangeKey = k
m.HasRangeKeys = true
}
// SetLargestPointKey sets the largest point key to the given key.
// NB: this method set the "absolute" largest point key. Any existing key is
// overridden.
func (m *WriterMetadata) SetLargestPointKey(k InternalKey) {
m.LargestPoint = k
m.HasPointKeys = true
}
// SetLargestRangeDelKey sets the largest rangedel key to the given key.
// NB: this method set the "absolute" largest rangedel key. Any existing key is
// overridden.
func (m *WriterMetadata) SetLargestRangeDelKey(k InternalKey) {
m.LargestRangeDel = k
m.HasRangeDelKeys = true
}
// SetLargestRangeKey sets the largest range key to the given key.
// NB: this method set the "absolute" largest range key. Any existing key is
// overridden.
func (m *WriterMetadata) SetLargestRangeKey(k InternalKey) {
m.LargestRangeKey = k
m.HasRangeKeys = true
}
func (m *WriterMetadata) updateSeqNum(seqNum uint64) {
if m.SmallestSeqNum > seqNum {
m.SmallestSeqNum = seqNum
}
if m.LargestSeqNum < seqNum {
m.LargestSeqNum = seqNum
}
}
// Writer is a table writer.
type Writer struct {
writable objstorage.Writable
meta WriterMetadata
err error
// cacheID and fileNum are used to remove blocks written to the sstable from
// the cache, providing a defense in depth against bugs which cause cache
// collisions.
cacheID uint64
fileNum base.DiskFileNum
// The following fields are copied from Options.
blockSize int
blockSizeThreshold int
indexBlockSize int
indexBlockSizeThreshold int
compare Compare
split Split
formatKey base.FormatKey
compression Compression
separator Separator
successor Successor
tableFormat TableFormat
isStrictObsolete bool
writingToLowestLevel bool
cache *cache.Cache
restartInterval int
checksumType ChecksumType
// disableKeyOrderChecks disables the checks that keys are added to an
// sstable in order. It is intended for internal use only in the construction
// of invalid sstables for testing. See tool/make_test_sstables.go.
disableKeyOrderChecks bool
// With two level indexes, the index/filter of a SST file is partitioned into
// smaller blocks with an additional top-level index on them. When reading an
// index/filter, only the top-level index is loaded into memory. The two level
// index/filter then uses the top-level index to load on demand into the block
// cache the partitions that are required to perform the index/filter query.
//
// Two level indexes are enabled automatically when there is more than one
// index block.
//
// This is useful when there are very large index blocks, which generally occurs
// with the usage of large keys. With large index blocks, the index blocks fight
// the data blocks for block cache space and the index blocks are likely to be
// re-read many times from the disk. The top level index, which has a much
// smaller memory footprint, can be used to prevent the entire index block from
// being loaded into the block cache.
twoLevelIndex bool
// Internal flag to allow creation of range-del-v1 format blocks. Only used
// for testing. Note that v2 format blocks are backwards compatible with v1
// format blocks.
rangeDelV1Format bool
indexBlock *indexBlockBuf
rangeDelBlock blockWriter
rangeKeyBlock blockWriter
topLevelIndexBlock blockWriter
props Properties
propCollectors []TablePropertyCollector
blockPropCollectors []BlockPropertyCollector
obsoleteCollector obsoleteKeyBlockPropertyCollector
blockPropsEncoder blockPropertiesEncoder
// filter accumulates the filter block. If populated, the filter ingests
// either the output of w.split (i.e. a prefix extractor) if w.split is not
// nil, or the full keys otherwise.
filter filterWriter
indexPartitions []indexBlockAndBlockProperties
// indexBlockAlloc is used to bulk-allocate byte slices used to store index
// blocks in indexPartitions. These live until the index finishes.
indexBlockAlloc []byte
// indexSepAlloc is used to bulk-allocate index block separator slices stored
// in indexPartitions. These live until the index finishes.
indexSepAlloc bytealloc.A
// To allow potentially overlapping (i.e. un-fragmented) range keys spans to
// be added to the Writer, a keyspan.Fragmenter is used to retain the keys
// and values, emitting fragmented, coalesced spans as appropriate. Range
// keys must be added in order of their start user-key.
fragmenter keyspan.Fragmenter
rangeKeyEncoder rangekey.Encoder
rangeKeysBySuffix keyspan.KeysBySuffix
rangeKeySpan keyspan.Span
rkBuf []byte
// dataBlockBuf consists of the state which is currently owned by and used by
// the Writer client goroutine. This state can be handed off to other goroutines.
dataBlockBuf *dataBlockBuf
// blockBuf consists of the state which is owned by and used by the Writer client
// goroutine.
blockBuf blockBuf
coordination coordinationState
// Information (other than the byte slice) about the last point key, to
// avoid extracting it again.
lastPointKeyInfo pointKeyInfo
// For value blocks.
shortAttributeExtractor base.ShortAttributeExtractor
requiredInPlaceValueBound UserKeyPrefixBound
valueBlockWriter *valueBlockWriter
}
type pointKeyInfo struct {
trailer uint64
// Only computed when w.valueBlockWriter is not nil.
userKeyLen int
// prefixLen uses w.split, if not nil. Only computed when w.valueBlockWriter
// is not nil.
prefixLen int
// True iff the point was marked obsolete.
isObsolete bool
}
type coordinationState struct {
parallelismEnabled bool
// writeQueue is used to write data blocks to disk. The writeQueue is primarily
// used to maintain the order in which data blocks must be written to disk. For
// this reason, every single data block write must be done through the writeQueue.
writeQueue *writeQueue
sizeEstimate dataBlockEstimates
}
func (c *coordinationState) init(parallelismEnabled bool, writer *Writer) {
c.parallelismEnabled = parallelismEnabled
// useMutex is false regardless of parallelismEnabled, because we do not do
// parallel compression yet.
c.sizeEstimate.useMutex = false
// writeQueueSize determines the size of the write queue, or the number
// of items which can be added to the queue without blocking. By default, we
// use a writeQueue size of 0, since we won't be doing any block writes in
// parallel.
writeQueueSize := 0
if parallelismEnabled {
writeQueueSize = runtime.GOMAXPROCS(0)
}
c.writeQueue = newWriteQueue(writeQueueSize, writer)
}
// sizeEstimate is a general purpose helper for estimating two kinds of sizes:
// A. The compressed sstable size, which is useful for deciding when to start
//
// a new sstable during flushes or compactions. In practice, we use this in
// estimating the data size (excluding the index).
//
// B. The size of index blocks to decide when to start a new index block.
//
// There are some terminology peculiarities which are due to the origin of
// sizeEstimate for use case A with parallel compression enabled (for which
// the code has not been merged). Specifically this relates to the terms
// "written" and "compressed".
// - The notion of "written" for case A is sufficiently defined by saying that
// the data block is compressed. Waiting for the actual data block write to
// happen can result in unnecessary estimation, when we already know how big
// it will be in compressed form. Additionally, with the forthcoming value
// blocks containing older MVCC values, these compressed block will be held
// in-memory until late in the sstable writing, and we do want to accurately
// account for them without waiting for the actual write.
// For case B, "written" means that the index entry has been fully
// generated, and has been added to the uncompressed block buffer for that
// index block. It does not include actually writing a potentially
// compressed index block.
// - The notion of "compressed" is to differentiate between a "inflight" size
// and the actual size, and is handled via computing a compression ratio
// observed so far (defaults to 1).
// For case A, this is actual data block compression, so the "inflight" size
// is uncompressed blocks (that are no longer being written to) and the
// "compressed" size is after they have been compressed.
// For case B the inflight size is for a key-value pair in the index for
// which the value size (the encoded size of the BlockHandleWithProperties)
// is not accurately known, while the compressed size is the size of that
// entry when it has been added to the (in-progress) index ssblock.
//
// Usage: To update state, one can optionally provide an inflight write value
// using addInflight (used for case B). When something is "written" the state
// can be updated using either writtenWithDelta or writtenWithTotal, which
// provide the actual delta size or the total size (latter must be
// monotonically non-decreasing). If there were no calls to addInflight, there
// isn't any real estimation happening here. So case A does not do any real
// estimation. However, when we introduce parallel compression, there will be
// estimation in that the client goroutine will call addInFlight and the
// compression goroutines will call writtenWithDelta.
type sizeEstimate struct {
// emptySize is the size when there is no inflight data, and numEntries is 0.
// emptySize is constant once set.
emptySize uint64
// inflightSize is the estimated size of some inflight data which hasn't
// been written yet.
inflightSize uint64
// totalSize is the total size of the data which has already been written.
totalSize uint64
// numWrittenEntries is the total number of entries which have already been
// written.
numWrittenEntries uint64
// numInflightEntries is the total number of entries which are inflight, and
// haven't been written.
numInflightEntries uint64
// maxEstimatedSize stores the maximum result returned from sizeEstimate.size.
// It ensures that values returned from subsequent calls to Writer.EstimatedSize
// never decrease.
maxEstimatedSize uint64
// We assume that the entries added to the sizeEstimate can be compressed.
// For this reason, we keep track of a compressedSize and an uncompressedSize
// to compute a compression ratio for the inflight entries. If the entries
// aren't being compressed, then compressedSize and uncompressedSize must be
// equal.
compressedSize uint64
uncompressedSize uint64
}
func (s *sizeEstimate) init(emptySize uint64) {
s.emptySize = emptySize
}
func (s *sizeEstimate) size() uint64 {
ratio := float64(1)
if s.uncompressedSize > 0 {
ratio = float64(s.compressedSize) / float64(s.uncompressedSize)
}
estimatedInflightSize := uint64(float64(s.inflightSize) * ratio)
total := s.totalSize + estimatedInflightSize
if total > s.maxEstimatedSize {
s.maxEstimatedSize = total
} else {
total = s.maxEstimatedSize
}
if total == 0 {
return s.emptySize
}
return total
}
func (s *sizeEstimate) numTotalEntries() uint64 {
return s.numWrittenEntries + s.numInflightEntries
}
func (s *sizeEstimate) addInflight(size int) {
s.numInflightEntries++
s.inflightSize += uint64(size)
}
func (s *sizeEstimate) writtenWithTotal(newTotalSize uint64, inflightSize int) {
finalEntrySize := int(newTotalSize - s.totalSize)
s.writtenWithDelta(finalEntrySize, inflightSize)
}
func (s *sizeEstimate) writtenWithDelta(finalEntrySize int, inflightSize int) {
if inflightSize > 0 {
// This entry was previously inflight, so we should decrement inflight
// entries and update the "compression" stats for future estimation.
s.numInflightEntries--
s.inflightSize -= uint64(inflightSize)
s.uncompressedSize += uint64(inflightSize)
s.compressedSize += uint64(finalEntrySize)
}
s.numWrittenEntries++
s.totalSize += uint64(finalEntrySize)
}
func (s *sizeEstimate) clear() {
*s = sizeEstimate{emptySize: s.emptySize}
}
type indexBlockBuf struct {
// block will only be accessed from the writeQueue.
block blockWriter
size struct {
useMutex bool
mu sync.Mutex
estimate sizeEstimate
}
// restartInterval matches indexBlockBuf.block.restartInterval. We store it twice, because the `block`
// must only be accessed from the writeQueue goroutine.
restartInterval int
}
func (i *indexBlockBuf) clear() {
i.block.clear()
if i.size.useMutex {
i.size.mu.Lock()
defer i.size.mu.Unlock()
}
i.size.estimate.clear()
i.restartInterval = 0
}
var indexBlockBufPool = sync.Pool{
New: func() interface{} {
return &indexBlockBuf{}
},
}
const indexBlockRestartInterval = 1
func newIndexBlockBuf(useMutex bool) *indexBlockBuf {
i := indexBlockBufPool.Get().(*indexBlockBuf)
i.size.useMutex = useMutex
i.restartInterval = indexBlockRestartInterval
i.block.restartInterval = indexBlockRestartInterval
i.size.estimate.init(emptyBlockSize)
return i
}
func (i *indexBlockBuf) shouldFlush(
sep InternalKey, valueLen, targetBlockSize, sizeThreshold int,
) bool {
if i.size.useMutex {
i.size.mu.Lock()
defer i.size.mu.Unlock()
}
nEntries := i.size.estimate.numTotalEntries()
return shouldFlush(
sep, valueLen, i.restartInterval, int(i.size.estimate.size()),
int(nEntries), targetBlockSize, sizeThreshold)
}
func (i *indexBlockBuf) add(key InternalKey, value []byte, inflightSize int) {
i.block.add(key, value)
size := i.block.estimatedSize()
if i.size.useMutex {
i.size.mu.Lock()
defer i.size.mu.Unlock()
}
i.size.estimate.writtenWithTotal(uint64(size), inflightSize)
}
func (i *indexBlockBuf) finish() []byte {
b := i.block.finish()
return b
}
func (i *indexBlockBuf) addInflight(inflightSize int) {
if i.size.useMutex {
i.size.mu.Lock()
defer i.size.mu.Unlock()
}
i.size.estimate.addInflight(inflightSize)
}
func (i *indexBlockBuf) estimatedSize() uint64 {
if i.size.useMutex {
i.size.mu.Lock()
defer i.size.mu.Unlock()
}
// Make sure that the size estimation works as expected when parallelism
// is disabled.
if invariants.Enabled && !i.size.useMutex {
if i.size.estimate.inflightSize != 0 {
panic("unexpected inflight entry in index block size estimation")
}
// NB: The i.block should only be accessed from the writeQueue goroutine,
// when parallelism is enabled. We break that invariant here, but that's
// okay since parallelism is disabled.
if i.size.estimate.size() != uint64(i.block.estimatedSize()) {
panic("index block size estimation sans parallelism is incorrect")
}
}
return i.size.estimate.size()
}
// sizeEstimate is used for sstable size estimation. sizeEstimate can be
// accessed by the Writer client and compressionQueue goroutines. Fields
// should only be read/updated through the functions defined on the
// *sizeEstimate type.
type dataBlockEstimates struct {
// If we don't do block compression in parallel, then we don't need to take
// the performance hit of synchronizing using this mutex.
useMutex bool
mu sync.Mutex
estimate sizeEstimate
}
// inflightSize is the uncompressed block size estimate which has been
// previously provided to addInflightDataBlock(). If addInflightDataBlock()
// has not been called, this must be set to 0. compressedSize is the
// compressed size of the block.
func (d *dataBlockEstimates) dataBlockCompressed(compressedSize int, inflightSize int) {
if d.useMutex {
d.mu.Lock()
defer d.mu.Unlock()
}
d.estimate.writtenWithDelta(compressedSize+blockTrailerLen, inflightSize)
}
// size is an estimated size of datablock data which has been written to disk.
func (d *dataBlockEstimates) size() uint64 {
if d.useMutex {
d.mu.Lock()
defer d.mu.Unlock()
}
// If there is no parallel compression, there should not be any inflight bytes.
if invariants.Enabled && !d.useMutex {
if d.estimate.inflightSize != 0 {
panic("unexpected inflight entry in data block size estimation")
}
}
return d.estimate.size()
}
// Avoid linter unused error.
var _ = (&dataBlockEstimates{}).addInflightDataBlock
// NB: unused since no parallel compression.
func (d *dataBlockEstimates) addInflightDataBlock(size int) {
if d.useMutex {
d.mu.Lock()
defer d.mu.Unlock()
}
d.estimate.addInflight(size)
}
var writeTaskPool = sync.Pool{
New: func() interface{} {
t := &writeTask{}
t.compressionDone = make(chan bool, 1)
return t
},
}
type checksummer struct {
checksumType ChecksumType
xxHasher *xxhash.Digest
}
func (c *checksummer) checksum(block []byte, blockType []byte) (checksum uint32) {
// Calculate the checksum.
switch c.checksumType {
case ChecksumTypeCRC32c:
checksum = crc.New(block).Update(blockType).Value()
case ChecksumTypeXXHash64:
if c.xxHasher == nil {
c.xxHasher = xxhash.New()
} else {
c.xxHasher.Reset()
}
c.xxHasher.Write(block)
c.xxHasher.Write(blockType)
checksum = uint32(c.xxHasher.Sum64())
default:
panic(errors.Newf("unsupported checksum type: %d", c.checksumType))
}
return checksum
}
type blockBuf struct {
// tmp is a scratch buffer, large enough to hold either footerLen bytes,
// blockTrailerLen bytes, (5 * binary.MaxVarintLen64) bytes, and most
// likely large enough for a block handle with properties.
tmp [blockHandleLikelyMaxLen]byte
// compressedBuf is the destination buffer for compression. It is re-used over the
// lifetime of the blockBuf, avoiding the allocation of a temporary buffer for each block.
compressedBuf []byte
checksummer checksummer
}
func (b *blockBuf) clear() {
// We can't assign b.compressedBuf[:0] to compressedBuf because snappy relies
// on the length of the buffer, and not the capacity to determine if it needs
// to make an allocation.
*b = blockBuf{
compressedBuf: b.compressedBuf, checksummer: b.checksummer,
}
}
// A dataBlockBuf holds all the state required to compress and write a data block to disk.
// A dataBlockBuf begins its lifecycle owned by the Writer client goroutine. The Writer
// client goroutine adds keys to the sstable, writing directly into a dataBlockBuf's blockWriter
// until the block is full. Once a dataBlockBuf's block is full, the dataBlockBuf may be passed
// to other goroutines for compression and file I/O.
type dataBlockBuf struct {
blockBuf
dataBlock blockWriter
// uncompressed is a reference to a byte slice which is owned by the dataBlockBuf. It is the
// next byte slice to be compressed. The uncompressed byte slice will be backed by the
// dataBlock.buf.
uncompressed []byte
// compressed is a reference to a byte slice which is owned by the dataBlockBuf. It is the
// compressed byte slice which must be written to disk. The compressed byte slice may be
// backed by the dataBlock.buf, or the dataBlockBuf.compressedBuf, depending on whether
// we use the result of the compression.
compressed []byte
// We're making calls to BlockPropertyCollectors from the Writer client goroutine. We need to
// pass the encoded block properties over to the write queue. To prevent copies, and allocations,
// we give each dataBlockBuf, a blockPropertiesEncoder.
blockPropsEncoder blockPropertiesEncoder
// dataBlockProps is set when Writer.finishDataBlockProps is called. The dataBlockProps slice is
// a shallow copy of the internal buffer of the dataBlockBuf.blockPropsEncoder.
dataBlockProps []byte
// sepScratch is reusable scratch space for computing separator keys.
sepScratch []byte
}
func (d *dataBlockBuf) clear() {
d.blockBuf.clear()
d.dataBlock.clear()
d.uncompressed = nil
d.compressed = nil
d.dataBlockProps = nil
d.sepScratch = d.sepScratch[:0]
}
var dataBlockBufPool = sync.Pool{
New: func() interface{} {
return &dataBlockBuf{}
},
}
func newDataBlockBuf(restartInterval int, checksumType ChecksumType) *dataBlockBuf {
d := dataBlockBufPool.Get().(*dataBlockBuf)
d.dataBlock.restartInterval = restartInterval
d.checksummer.checksumType = checksumType
return d
}
func (d *dataBlockBuf) finish() {
d.uncompressed = d.dataBlock.finish()
}
func (d *dataBlockBuf) compressAndChecksum(c Compression) {
d.compressed = compressAndChecksum(d.uncompressed, c, &d.blockBuf)
}
func (d *dataBlockBuf) shouldFlush(
key InternalKey, valueLen, targetBlockSize, sizeThreshold int,
) bool {
return shouldFlush(
key, valueLen, d.dataBlock.restartInterval, d.dataBlock.estimatedSize(),
d.dataBlock.nEntries, targetBlockSize, sizeThreshold)
}
type indexBlockAndBlockProperties struct {
nEntries int
// sep is the last key added to this block, for computing a separator later.
sep InternalKey
properties []byte
// block is the encoded block produced by blockWriter.finish.
block []byte
}
// Set sets the value for the given key. The sequence number is set to 0.
// Intended for use to externally construct an sstable before ingestion into a
// DB. For a given Writer, the keys passed to Set must be in strictly increasing
// order.
//
// TODO(peter): untested
func (w *Writer) Set(key, value []byte) error {
if w.err != nil {
return w.err
}
if w.isStrictObsolete {
return errors.Errorf("use AddWithForceObsolete")
}
// forceObsolete is false based on the assumption that no RANGEDELs in the
// sstable delete the added points.
return w.addPoint(base.MakeInternalKey(key, 0, InternalKeyKindSet), value, false)
}
// Delete deletes the value for the given key. The sequence number is set to
// 0. Intended for use to externally construct an sstable before ingestion into
// a DB.
//
// TODO(peter): untested
func (w *Writer) Delete(key []byte) error {
if w.err != nil {
return w.err
}
if w.isStrictObsolete {
return errors.Errorf("use AddWithForceObsolete")
}
// forceObsolete is false based on the assumption that no RANGEDELs in the
// sstable delete the added points.
return w.addPoint(base.MakeInternalKey(key, 0, InternalKeyKindDelete), nil, false)
}
// DeleteRange deletes all of the keys (and values) in the range [start,end)
// (inclusive on start, exclusive on end). The sequence number is set to
// 0. Intended for use to externally construct an sstable before ingestion into
// a DB.
//
// TODO(peter): untested
func (w *Writer) DeleteRange(start, end []byte) error {
if w.err != nil {
return w.err
}
return w.addTombstone(base.MakeInternalKey(start, 0, InternalKeyKindRangeDelete), end)
}
// Merge adds an action to the DB that merges the value at key with the new
// value. The details of the merge are dependent upon the configured merge
// operator. The sequence number is set to 0. Intended for use to externally
// construct an sstable before ingestion into a DB.
//
// TODO(peter): untested
func (w *Writer) Merge(key, value []byte) error {
if w.err != nil {
return w.err
}
if w.isStrictObsolete {
return errors.Errorf("use AddWithForceObsolete")
}
// forceObsolete is false based on the assumption that no RANGEDELs in the
// sstable that delete the added points. If the user configured this writer
// to be strict-obsolete, addPoint will reject the addition of this MERGE.
return w.addPoint(base.MakeInternalKey(key, 0, InternalKeyKindMerge), value, false)
}
// Add adds a key/value pair to the table being written. For a given Writer,
// the keys passed to Add must be in increasing order. The exception to this
// rule is range deletion tombstones. Range deletion tombstones need to be
// added ordered by their start key, but they can be added out of order from
// point entries. Additionally, range deletion tombstones must be fragmented
// (i.e. by keyspan.Fragmenter).
func (w *Writer) Add(key InternalKey, value []byte) error {
if w.isStrictObsolete {
return errors.Errorf("use AddWithForceObsolete")
}
return w.AddWithForceObsolete(key, value, false)
}
// AddWithForceObsolete must be used when writing a strict-obsolete sstable.
//
// forceObsolete indicates whether the caller has determined that this key is
// obsolete even though it may be the latest point key for this userkey. This
// should be set to true for keys obsoleted by RANGEDELs, and is required for
// strict-obsolete sstables.
//
// Note that there are two properties, S1 and S2 (see comment in format.go)
// that strict-obsolete ssts must satisfy. S2, due to RANGEDELs, is solely the
// responsibility of the caller. S1 is solely the responsibility of the
// callee.
func (w *Writer) AddWithForceObsolete(key InternalKey, value []byte, forceObsolete bool) error {
if w.err != nil {
return w.err
}
switch key.Kind() {
case InternalKeyKindRangeDelete:
return w.addTombstone(key, value)
case base.InternalKeyKindRangeKeyDelete,
base.InternalKeyKindRangeKeySet,
base.InternalKeyKindRangeKeyUnset:
w.err = errors.Errorf(
"pebble: range keys must be added via one of the RangeKey* functions")
return w.err
}
return w.addPoint(key, value, forceObsolete)
}
func (w *Writer) makeAddPointDecisionV2(key InternalKey) error {
prevTrailer := w.lastPointKeyInfo.trailer
w.lastPointKeyInfo.trailer = key.Trailer
if w.dataBlockBuf.dataBlock.nEntries == 0 {
return nil
}
if !w.disableKeyOrderChecks {
prevPointUserKey := w.dataBlockBuf.dataBlock.getCurUserKey()
cmpUser := w.compare(prevPointUserKey, key.UserKey)
if cmpUser > 0 || (cmpUser == 0 && prevTrailer <= key.Trailer) {
return errors.Errorf(
"pebble: keys must be added in strictly increasing order: %s, %s",
InternalKey{UserKey: prevPointUserKey, Trailer: prevTrailer}.Pretty(w.formatKey),
key.Pretty(w.formatKey))
}
}
return nil
}
// REQUIRES: at least one point has been written to the Writer.
func (w *Writer) getLastPointUserKey() []byte {
if w.dataBlockBuf.dataBlock.nEntries == 0 {
panic(errors.AssertionFailedf("no point keys added to writer"))
}
return w.dataBlockBuf.dataBlock.getCurUserKey()
}
func (w *Writer) makeAddPointDecisionV3(
key InternalKey, valueLen int,
) (setHasSamePrefix bool, writeToValueBlock bool, isObsolete bool, err error) {
prevPointKeyInfo := w.lastPointKeyInfo
w.lastPointKeyInfo.userKeyLen = len(key.UserKey)
w.lastPointKeyInfo.prefixLen = w.lastPointKeyInfo.userKeyLen
if w.split != nil {
w.lastPointKeyInfo.prefixLen = w.split(key.UserKey)
}
w.lastPointKeyInfo.trailer = key.Trailer
w.lastPointKeyInfo.isObsolete = false
if !w.meta.HasPointKeys {
return false, false, false, nil
}
keyKind := base.TrailerKind(key.Trailer)
prevPointUserKey := w.getLastPointUserKey()
prevPointKey := InternalKey{UserKey: prevPointUserKey, Trailer: prevPointKeyInfo.trailer}
prevKeyKind := base.TrailerKind(prevPointKeyInfo.trailer)
considerWriteToValueBlock := prevKeyKind == InternalKeyKindSet &&
keyKind == InternalKeyKindSet
if considerWriteToValueBlock && !w.requiredInPlaceValueBound.IsEmpty() {
keyPrefix := key.UserKey[:w.lastPointKeyInfo.prefixLen]
cmpUpper := w.compare(
w.requiredInPlaceValueBound.Upper, keyPrefix)
if cmpUpper <= 0 {
// Common case for CockroachDB. Make it empty since all future keys in
// this sstable will also have cmpUpper <= 0.
w.requiredInPlaceValueBound = UserKeyPrefixBound{}
} else if w.compare(keyPrefix, w.requiredInPlaceValueBound.Lower) >= 0 {
considerWriteToValueBlock = false
}
}
// cmpPrefix is initialized iff considerWriteToValueBlock.
var cmpPrefix int
var cmpUser int
if considerWriteToValueBlock {
// Compare the prefixes.
cmpPrefix = w.compare(prevPointUserKey[:prevPointKeyInfo.prefixLen],
key.UserKey[:w.lastPointKeyInfo.prefixLen])
cmpUser = cmpPrefix
if cmpPrefix == 0 {
// Need to compare suffixes to compute cmpUser.
cmpUser = w.compare(prevPointUserKey[prevPointKeyInfo.prefixLen:],
key.UserKey[w.lastPointKeyInfo.prefixLen:])
}
} else {
cmpUser = w.compare(prevPointUserKey, key.UserKey)
}
// Ensure that no one adds a point key kind without considering the obsolete
// handling for that kind.
switch keyKind {
case InternalKeyKindSet, InternalKeyKindSetWithDelete, InternalKeyKindMerge,
InternalKeyKindDelete, InternalKeyKindSingleDelete, InternalKeyKindDeleteSized:
default:
panic(errors.AssertionFailedf("unexpected key kind %s", keyKind.String()))
}
// If same user key, then the current key is obsolete if any of the
// following is true:
// C1 The prev key was obsolete.
// C2 The prev key was not a MERGE. When the previous key is a MERGE we must
// preserve SET* and MERGE since their values will be merged into the
// previous key. We also must preserve DEL* since there may be an older
// SET*/MERGE in a lower level that must not be merged with the MERGE --
// if we omit the DEL* that lower SET*/MERGE will become visible.
//
// Regardless of whether it is the same user key or not
// C3 The current key is some kind of point delete, and we are writing to
// the lowest level, then it is also obsolete. The correctness of this
// relies on the same user key not spanning multiple sstables in a level.
//
// C1 ensures that for a user key there is at most one transition from
// !obsolete to obsolete. Consider a user key k, for which the first n keys
// are not obsolete. We consider the various value of n:
//
// n = 0: This happens due to forceObsolete being set by the caller, or due
// to C3. forceObsolete must only be set due a RANGEDEL, and that RANGEDEL
// must also delete all the lower seqnums for the same user key. C3 triggers
// due to a point delete and that deletes all the lower seqnums for the same
// user key.
//
// n = 1: This is the common case. It happens when the first key is not a
// MERGE, or the current key is some kind of point delete.
//
// n > 1: This is due to a sequence of MERGE keys, potentially followed by a
// single non-MERGE key.
isObsoleteC1AndC2 := cmpUser == 0 &&
(prevPointKeyInfo.isObsolete || prevKeyKind != InternalKeyKindMerge)
isObsoleteC3 := w.writingToLowestLevel &&
(keyKind == InternalKeyKindDelete || keyKind == InternalKeyKindSingleDelete ||
keyKind == InternalKeyKindDeleteSized)
isObsolete = isObsoleteC1AndC2 || isObsoleteC3
// TODO(sumeer): storing isObsolete SET and SETWITHDEL in value blocks is
// possible, but requires some care in documenting and checking invariants.
// There is code that assumes nothing in value blocks because of single MVCC
// version (those should be ok). We have to ensure setHasSamePrefix is
// correctly initialized here etc.
if !w.disableKeyOrderChecks &&
(cmpUser > 0 || (cmpUser == 0 && prevPointKeyInfo.trailer <= key.Trailer)) {
return false, false, false, errors.Errorf(
"pebble: keys must be added in strictly increasing order: %s, %s",
prevPointKey.Pretty(w.formatKey), key.Pretty(w.formatKey))
}
if !considerWriteToValueBlock {
return false, false, isObsolete, nil
}
// NB: it is possible that cmpUser == 0, i.e., these two SETs have identical
// user keys (because of an open snapshot). This should be the rare case.
setHasSamePrefix = cmpPrefix == 0
considerWriteToValueBlock = setHasSamePrefix
// Use of 0 here is somewhat arbitrary. Given the minimum 3 byte encoding of
// valueHandle, this should be > 3. But tiny values are common in test and
// unlikely in production, so we use 0 here for better test coverage.
const tinyValueThreshold = 0
if considerWriteToValueBlock && valueLen <= tinyValueThreshold {
considerWriteToValueBlock = false
}
return setHasSamePrefix, considerWriteToValueBlock, isObsolete, nil
}
func (w *Writer) addPoint(key InternalKey, value []byte, forceObsolete bool) error {
if w.isStrictObsolete && key.Kind() == InternalKeyKindMerge {
return errors.Errorf("MERGE not supported in a strict-obsolete sstable")
}
var err error
var setHasSameKeyPrefix, writeToValueBlock, addPrefixToValueStoredWithKey bool
var isObsolete bool
maxSharedKeyLen := len(key.UserKey)
if w.valueBlockWriter != nil {
// maxSharedKeyLen is limited to the prefix of the preceding key. If the
// preceding key was in a different block, then the blockWriter will
// ignore this maxSharedKeyLen.
maxSharedKeyLen = w.lastPointKeyInfo.prefixLen
setHasSameKeyPrefix, writeToValueBlock, isObsolete, err =
w.makeAddPointDecisionV3(key, len(value))
addPrefixToValueStoredWithKey = base.TrailerKind(key.Trailer) == InternalKeyKindSet
} else {
err = w.makeAddPointDecisionV2(key)
}
if err != nil {
return err
}
isObsolete = w.tableFormat >= TableFormatPebblev4 && (isObsolete || forceObsolete)
w.lastPointKeyInfo.isObsolete = isObsolete
var valueStoredWithKey []byte
var prefix valuePrefix
var valueStoredWithKeyLen int
if writeToValueBlock {
vh, err := w.valueBlockWriter.addValue(value)
if err != nil {
return err
}
n := encodeValueHandle(w.blockBuf.tmp[:], vh)
valueStoredWithKey = w.blockBuf.tmp[:n]
valueStoredWithKeyLen = len(valueStoredWithKey) + 1
var attribute base.ShortAttribute
if w.shortAttributeExtractor != nil {
// TODO(sumeer): for compactions, it is possible that the input sstable
// already has this value in the value section and so we have already
// extracted the ShortAttribute. Avoid extracting it again. This will
// require changing the Writer.Add interface.
if attribute, err = w.shortAttributeExtractor(
key.UserKey, w.lastPointKeyInfo.prefixLen, value); err != nil {
return err
}
}
prefix = makePrefixForValueHandle(setHasSameKeyPrefix, attribute)
} else {
valueStoredWithKey = value
valueStoredWithKeyLen = len(value)
if addPrefixToValueStoredWithKey {
valueStoredWithKeyLen++
}
prefix = makePrefixForInPlaceValue(setHasSameKeyPrefix)
}
if err := w.maybeFlush(key, valueStoredWithKeyLen); err != nil {
return err
}
for i := range w.propCollectors {
if err := w.propCollectors[i].Add(key, value); err != nil {
w.err = err
return err
}
}
for i := range w.blockPropCollectors {
v := value
if addPrefixToValueStoredWithKey {
// Values for SET are not required to be in-place, and in the future may
// not even be read by the compaction, so pass nil values. Block
// property collectors in such Pebble DB's must not look at the value.
v = nil
}