Line data Source code
1 : // Copyright 2024 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package metamorphic
6 :
7 : import (
8 : "context"
9 : "fmt"
10 : "slices"
11 :
12 : "github.com/cockroachdb/pebble"
13 : "github.com/cockroachdb/pebble/internal/base"
14 : "github.com/cockroachdb/pebble/internal/keyspan"
15 : "github.com/cockroachdb/pebble/internal/private"
16 : "github.com/cockroachdb/pebble/internal/rangekey"
17 : "github.com/cockroachdb/pebble/objstorage"
18 : "github.com/cockroachdb/pebble/objstorage/objstorageprovider"
19 : "github.com/cockroachdb/pebble/sstable"
20 : "github.com/cockroachdb/pebble/vfs"
21 : )
22 :
23 : // writeSSTForIngestion writes an SST that is to be ingested, either directly or
24 : // as an external file. Returns the sstable metadata.
25 : //
26 : // Closes the iterators in all cases.
27 : func writeSSTForIngestion(
28 : t *Test,
29 : pointIter base.InternalIterator,
30 : rangeDelIter keyspan.FragmentIterator,
31 : rangeKeyIter keyspan.FragmentIterator,
32 : uniquePrefixes bool,
33 : syntheticSuffix sstable.SyntheticSuffix,
34 : syntheticPrefix sstable.SyntheticPrefix,
35 : writable objstorage.Writable,
36 : targetFMV pebble.FormatMajorVersion,
37 2 : ) (*sstable.WriterMetadata, error) {
38 2 : writerOpts := t.opts.MakeWriterOptions(0, targetFMV.MaxTableFormat())
39 2 : if t.testOpts.disableValueBlocksForIngestSSTables {
40 2 : writerOpts.DisableValueBlocks = true
41 2 : }
42 2 : w := sstable.NewWriter(writable, writerOpts)
43 2 : pointIterCloser := base.CloseHelper(pointIter)
44 2 : defer func() {
45 2 : _ = pointIterCloser.Close()
46 2 : if rangeDelIter != nil {
47 0 : rangeDelIter.Close()
48 0 : }
49 2 : if rangeKeyIter != nil {
50 0 : rangeKeyIter.Close()
51 0 : }
52 : }()
53 :
54 2 : outputKey := func(key []byte) []byte {
55 2 : if !syntheticPrefix.IsSet() && !syntheticSuffix.IsSet() {
56 2 : return slices.Clone(key)
57 2 : }
58 2 : if syntheticPrefix.IsSet() {
59 2 : key = syntheticPrefix.Apply(key)
60 2 : }
61 2 : if syntheticSuffix.IsSet() {
62 2 : n := t.opts.Comparer.Split(key)
63 2 : key = append(key[:n:n], syntheticSuffix...)
64 2 : }
65 2 : return key
66 : }
67 :
68 2 : var lastUserKey []byte
69 2 : for kv := pointIter.First(); kv != nil; kv = pointIter.Next() {
70 2 : // Ignore duplicate keys.
71 2 : if lastUserKey != nil {
72 2 : last := lastUserKey
73 2 : this := kv.K.UserKey
74 2 : if uniquePrefixes {
75 2 : last = last[:t.opts.Comparer.Split(last)]
76 2 : this = this[:t.opts.Comparer.Split(this)]
77 2 : }
78 2 : if t.opts.Comparer.Equal(last, this) {
79 2 : continue
80 : }
81 : }
82 2 : lastUserKey = append(lastUserKey[:0], kv.K.UserKey...)
83 2 :
84 2 : k := *kv
85 2 : k.K.SetSeqNum(base.SeqNumZero)
86 2 : k.K.UserKey = outputKey(k.K.UserKey)
87 2 : value := kv.V
88 2 : // It's possible that we wrote the key on a batch from a db that supported
89 2 : // DeleteSized, but will be ingesting into a db that does not. Detect this
90 2 : // case and translate the key to an InternalKeyKindDelete.
91 2 : if targetFMV < pebble.FormatDeleteSizedAndObsolete && kv.Kind() == pebble.InternalKeyKindDeleteSized {
92 1 : value = pebble.LazyValue{}
93 1 : k.K.SetKind(pebble.InternalKeyKindDelete)
94 1 : }
95 2 : valBytes, _, err := value.Value(nil)
96 2 : if err != nil {
97 0 : return nil, err
98 0 : }
99 2 : if err := w.Add(k.K, valBytes); err != nil {
100 0 : return nil, err
101 0 : }
102 : }
103 2 : if err := pointIterCloser.Close(); err != nil {
104 0 : return nil, err
105 0 : }
106 :
107 2 : if rangeDelIter != nil {
108 2 : span, err := rangeDelIter.First()
109 2 : for ; span != nil; span, err = rangeDelIter.Next() {
110 2 : if err := w.DeleteRange(outputKey(span.Start), outputKey(span.End)); err != nil {
111 0 : return nil, err
112 0 : }
113 : }
114 2 : if err != nil {
115 0 : return nil, err
116 0 : }
117 2 : rangeDelIter.Close()
118 2 : rangeDelIter = nil
119 : }
120 :
121 2 : if rangeKeyIter != nil {
122 2 : span, err := rangeKeyIter.First()
123 2 : for ; span != nil; span, err = rangeKeyIter.Next() {
124 2 : // Coalesce the keys of this span and then zero the sequence
125 2 : // numbers. This is necessary in order to make the range keys within
126 2 : // the ingested sstable internally consistent at the sequence number
127 2 : // it's ingested at. The individual keys within a batch are
128 2 : // committed at unique sequence numbers, whereas all the keys of an
129 2 : // ingested sstable are given the same sequence number. A span
130 2 : // containing keys that both set and unset the same suffix at the
131 2 : // same sequence number is nonsensical, so we "coalesce" or collapse
132 2 : // the keys.
133 2 : collapsed := keyspan.Span{
134 2 : Start: outputKey(span.Start),
135 2 : End: outputKey(span.End),
136 2 : Keys: make([]keyspan.Key, 0, len(span.Keys)),
137 2 : }
138 2 : rangekey.Coalesce(
139 2 : t.opts.Comparer.Compare, t.opts.Comparer.Equal, span.Keys, &collapsed.Keys,
140 2 : )
141 2 : for i := range collapsed.Keys {
142 2 : collapsed.Keys[i].Trailer = base.MakeTrailer(0, collapsed.Keys[i].Kind())
143 2 : }
144 2 : keyspan.SortKeysByTrailer(&collapsed.Keys)
145 2 : if err := rangekey.Encode(&collapsed, w.AddRangeKey); err != nil {
146 0 : return nil, err
147 0 : }
148 : }
149 2 : if err != nil {
150 0 : return nil, err
151 0 : }
152 2 : rangeKeyIter.Close()
153 2 : rangeKeyIter = nil
154 : }
155 :
156 2 : if err := w.Close(); err != nil {
157 0 : return nil, err
158 0 : }
159 2 : sstMeta, err := w.Metadata()
160 2 : if err != nil {
161 0 : return nil, err
162 0 : }
163 2 : return sstMeta, nil
164 : }
165 :
166 : // buildForIngest builds a local SST file containing the keys in the given batch
167 : // and returns its path and metadata.
168 : func buildForIngest(
169 : t *Test, dbID objID, b *pebble.Batch, i int,
170 2 : ) (path string, _ *sstable.WriterMetadata, _ error) {
171 2 : path = t.opts.FS.PathJoin(t.tmpDir, fmt.Sprintf("ext%d-%d", dbID.slot(), i))
172 2 : f, err := t.opts.FS.Create(path, vfs.WriteCategoryUnspecified)
173 2 : if err != nil {
174 0 : return "", nil, err
175 0 : }
176 2 : db := t.getDB(dbID)
177 2 :
178 2 : iter, rangeDelIter, rangeKeyIter := private.BatchSort(b)
179 2 :
180 2 : writable := objstorageprovider.NewFileWritable(f)
181 2 : meta, err := writeSSTForIngestion(
182 2 : t,
183 2 : iter, rangeDelIter, rangeKeyIter,
184 2 : false, /* uniquePrefixes */
185 2 : nil, /* syntheticSuffix */
186 2 : nil, /* syntheticPrefix */
187 2 : writable,
188 2 : db.FormatMajorVersion(),
189 2 : )
190 2 : return path, meta, err
191 : }
192 :
193 : // buildForIngest builds a local SST file containing the keys in the given
194 : // external object (truncated to the given bounds) and returns its path and
195 : // metadata.
196 : func buildForIngestExternalEmulation(
197 : t *Test,
198 : dbID objID,
199 : externalObjID objID,
200 : bounds pebble.KeyRange,
201 : syntheticSuffix sstable.SyntheticSuffix,
202 : syntheticPrefix sstable.SyntheticPrefix,
203 : i int,
204 2 : ) (path string, _ *sstable.WriterMetadata) {
205 2 : path = t.opts.FS.PathJoin(t.tmpDir, fmt.Sprintf("ext%d-%d", dbID.slot(), i))
206 2 : f, err := t.opts.FS.Create(path, vfs.WriteCategoryUnspecified)
207 2 : panicIfErr(err)
208 2 :
209 2 : reader, pointIter, rangeDelIter, rangeKeyIter := openExternalObj(t, externalObjID, bounds, syntheticPrefix)
210 2 : defer reader.Close()
211 2 :
212 2 : writable := objstorageprovider.NewFileWritable(f)
213 2 : // The underlying file should already have unique prefixes. Plus we are
214 2 : // emulating the external ingestion path which won't remove duplicate prefixes
215 2 : // if they exist.
216 2 : const uniquePrefixes = false
217 2 : meta, err := writeSSTForIngestion(
218 2 : t,
219 2 : pointIter, rangeDelIter, rangeKeyIter,
220 2 : uniquePrefixes,
221 2 : syntheticSuffix,
222 2 : syntheticPrefix,
223 2 : writable,
224 2 : t.minFMV(),
225 2 : )
226 2 : if err != nil {
227 0 : panic(err)
228 : }
229 2 : return path, meta
230 : }
231 :
232 : func openExternalObj(
233 : t *Test, externalObjID objID, bounds pebble.KeyRange, syntheticPrefix sstable.SyntheticPrefix,
234 : ) (
235 : reader *sstable.Reader,
236 : pointIter base.InternalIterator,
237 : rangeDelIter keyspan.FragmentIterator,
238 : rangeKeyIter keyspan.FragmentIterator,
239 2 : ) {
240 2 : objReader, objSize, err := t.externalStorage.ReadObject(context.Background(), externalObjName(externalObjID))
241 2 : panicIfErr(err)
242 2 : opts := sstable.ReaderOptions{
243 2 : Comparer: t.opts.Comparer,
244 2 : }
245 2 : reader, err = sstable.NewReader(objstorageprovider.NewRemoteReadable(objReader, objSize), opts)
246 2 : panicIfErr(err)
247 2 :
248 2 : start := bounds.Start
249 2 : end := bounds.End
250 2 : if syntheticPrefix.IsSet() {
251 2 : start = syntheticPrefix.Invert(start)
252 2 : end = syntheticPrefix.Invert(end)
253 2 : }
254 2 : pointIter, err = reader.NewIter(sstable.NoTransforms, start, end)
255 2 : panicIfErr(err)
256 2 :
257 2 : rangeDelIter, err = reader.NewRawRangeDelIter(sstable.NoFragmentTransforms)
258 2 : panicIfErr(err)
259 2 : if rangeDelIter != nil {
260 1 : rangeDelIter = keyspan.Truncate(
261 1 : t.opts.Comparer.Compare,
262 1 : rangeDelIter,
263 1 : base.UserKeyBoundsEndExclusive(start, end),
264 1 : )
265 1 : }
266 :
267 2 : rangeKeyIter, err = reader.NewRawRangeKeyIter(sstable.NoFragmentTransforms)
268 2 : panicIfErr(err)
269 2 : if rangeKeyIter != nil {
270 0 : rangeKeyIter = keyspan.Truncate(
271 0 : t.opts.Comparer.Compare,
272 0 : rangeKeyIter,
273 0 : base.UserKeyBoundsEndExclusive(start, end),
274 0 : )
275 0 : }
276 2 : return reader, pointIter, rangeDelIter, rangeKeyIter
277 : }
278 :
279 2 : func panicIfErr(err error) {
280 2 : if err != nil {
281 0 : panic(err)
282 : }
283 : }
|