/
apply_map_edits.go
428 lines (337 loc) · 10.5 KB
/
apply_map_edits.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
// Copyright 2019 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"context"
"io"
"github.com/dolthub/dolt/go/store/atomicerr"
)
// EditProvider is an interface which provides map edits as KVPs where each edit is a key and the new value
// associated with the key for inserts and updates. deletes are modeled as a key with no value
type EditProvider interface {
// Next returns the next KVP representing the next edit to be applied. Next will always return KVPs
// in key sorted order. Once all KVPs have been read io.EOF will be returned.
Next() (*KVP, error)
// ReachedEOF returns true once all data is exhausted. If ReachedEOF returns false that does not mean that there
// is more data, only that io.EOF has not been returned previously. If ReachedEOF returns true then all edits have
// been read
ReachedEOF() bool
Close(ctx context.Context) error
}
// EmptyEditProvider is an EditProvider implementation that has no edits
type EmptyEditProvider struct{}
// Next will always return nil, io.EOF
func (eep EmptyEditProvider) Next() (*KVP, error) {
return nil, io.EOF
}
// ReachedEOF returns true once all data is exhausted. If ReachedEOF returns false that does not mean that there
// is more data, only that io.EOF has not been returned previously. If ReachedEOF returns true then all edits have
// been read
func (eep EmptyEditProvider) ReachedEOF() bool {
return true
}
func (eep EmptyEditProvider) Close(ctx context.Context) error {
return nil
}
// Before edits can be applied th cursor position for each edit must be found. mapWork represents a piece of work to be
// done by the worker threads which are executing the prepWorker function. Each piece of work will be a batch of edits
// whose cursor needs to be found, and a chan where results should be written.
type mapWork struct {
resChan chan mapWorkResult
kvps []*KVP
}
// mapWorkResult is the result of a single mapWork instance being processed.
type mapWorkResult struct {
seqCurs []*sequenceCursor
cursorEntries [][]mapEntry
}
const (
workerCount = 7
// batch sizes start small in order to get the sequenceChunker work to do quickly. Batches will grow to a maximum
// size at a given multiplier
batchSizeStart = 10
batchMult = 1.25
batchSizeMax = 5000
)
// AppliedEditStats contains statistics on what edits were applied in types.ApplyEdits
type AppliedEditStats struct {
// Additions counts the number of elements added to the map
Additions int64
// Modifications counts the number of map entries that were modified
Modifications int64
// SamVal counts the number of edits that had no impact because a value was set to the same value that is already
// stored in the map
SameVal int64
// Deletions counts the number of items deleted from the map
Deletions int64
// NonexistantDeletes counts the number of items where a deletion was attempted, but the key didn't exist in the map
// so there was no impact
NonExistentDeletes int64
}
// Add adds two AppliedEditStats structures member by member.
func (stats AppliedEditStats) Add(other AppliedEditStats) AppliedEditStats {
return AppliedEditStats{
Additions: stats.Additions + other.Additions,
Modifications: stats.Modifications + other.Modifications,
SameVal: stats.SameVal + other.SameVal,
Deletions: stats.Deletions + other.Deletions,
NonExistentDeletes: stats.NonExistentDeletes + other.NonExistentDeletes,
}
}
// ApplyEdits applies all the edits to a given Map and returns the resulting map, and some statistics about the edits
// that were applied.
func ApplyEdits(ctx context.Context, edits EditProvider, m Map) (Map, AppliedEditStats, error) {
return ApplyNEdits(ctx, edits, m, -1)
}
func ApplyNEdits(ctx context.Context, edits EditProvider, m Map, numEdits int64) (Map, AppliedEditStats, error) {
var stats AppliedEditStats
if edits.ReachedEOF() {
return m, stats, nil // no edits
}
var seq sequence = m.orderedSequence
vrw := seq.valueReadWriter()
ae := atomicerr.New()
rc := make(chan chan mapWorkResult, 128)
wc := make(chan mapWork, 128)
// start worker threads
for i := 0; i < workerCount; i++ {
go prepWorker(ctx, ae, seq.(orderedSequence), wc)
}
// asynchronously add mapWork to be done by the workers
go buildBatches(m.Format(), ae, rc, wc, edits, numEdits)
// wait for workers to return results and then process them
var ch *sequenceChunker
for {
wrc, ok := <-rc
if ok {
workRes, workResOk := <-wrc
if !workResOk || ae.IsSet() {
// drain
continue
}
for i, cur := range workRes.seqCurs {
for _, kv := range workRes.cursorEntries[i] {
var existingValue Value
if cur.idx < cur.seq.seqLen() {
currEnt, err := cur.current()
if ae.SetIfErrAndCheck(err) {
continue
}
ckv := currEnt.(mapEntry)
if ckv.key.Equals(kv.key) {
existingValue = ckv.value
}
}
if existingValue == nil && kv.value == nil {
stats.NonExistentDeletes++
continue // already non-present
}
if existingValue != nil && kv.value != nil && existingValue.Equals(kv.value) {
stats.SameVal++
continue // same value
}
if ch == nil {
var err error
ch, err = newMapLeafChunkerFromCursor(ctx, cur, vrw)
if ae.SetIfError(err) {
continue
}
} else {
err := ch.advanceTo(ctx, cur)
if ae.SetIfError(err) {
continue
}
}
if existingValue != nil {
stats.Modifications++
err := ch.Skip(ctx)
if ae.SetIfError(err) {
continue
}
} else {
stats.Additions++
}
if kv.value != nil {
_, err := ch.Append(ctx, kv)
if ae.SetIfError(err) {
continue
}
}
}
}
} else {
break
}
}
if ae.IsSet() {
return EmptyMap, AppliedEditStats{}, ae.Get()
}
if ch == nil {
return m, stats, nil // no edits required application
}
seq, err := ch.Done(ctx)
if err != nil {
return EmptyMap, AppliedEditStats{}, err
}
return newMap(seq.(orderedSequence)), stats, nil
}
// prepWorker will wait for work to be read from a channel, then iterate over all of the edits finding the appropriate
// cursor where the insertion should happen. It attempts to reuse cursors when consecutive keys share the same
// insertion point
func prepWorker(ctx context.Context, ae *atomicerr.AtomicError, seq orderedSequence, wc chan mapWork) {
for work := range wc {
// In the case of an error drain wc
if !ae.IsSet() {
wRes, err := doWork(ctx, seq, work)
if err != nil {
ae.SetIfError(err)
} else {
work.resChan <- wRes
}
}
close(work.resChan)
}
}
func doWork(ctx context.Context, seq orderedSequence, work mapWork) (mapWorkResult, error) {
wRes := mapWorkResult{}
var cur *sequenceCursor
var curKey orderedKey
i := 0
for ; i < len(work.kvps); i++ {
edit := work.kvps[i]
key, err := edit.Key.Value(ctx)
if err != nil {
return mapWorkResult{}, err
}
ordKey, err := newOrderedKey(key, seq.format())
if err != nil {
return mapWorkResult{}, err
}
createCur := cur == nil
if cur != nil {
isLess, err := ordKey.Less(seq.format(), curKey)
if err != nil {
return mapWorkResult{}, err
}
createCur = !isLess
}
if createCur {
cur, err = newCursorAt(ctx, seq, ordKey, true, false)
if err != nil {
return mapWorkResult{}, err
}
if cur.valid() {
curKey, err = getCurrentKey(cur)
if err != nil {
return mapWorkResult{}, err
}
} else {
break
}
}
err = appendToWRes(ctx, &wRes, cur, key, edit.Val)
if err != nil {
return mapWorkResult{}, err
}
}
// All remaining edits get added at the end
for ; i < len(work.kvps); i++ {
edit := work.kvps[i]
key, err := edit.Key.Value(ctx)
if err != nil {
return mapWorkResult{}, err
}
err = appendToWRes(ctx, &wRes, cur, key, edit.Val)
if err != nil {
return mapWorkResult{}, err
}
}
return wRes, nil
}
// buildBatches iterates over the sorted edits building batches of work to be completed by the worker threads.
func buildBatches(nbf *NomsBinFormat, ae *atomicerr.AtomicError, rc chan chan mapWorkResult, wc chan mapWork, edits EditProvider, numEdits int64) {
defer close(rc)
defer close(wc)
batchSize := batchSizeStart
nextEdit, err := edits.Next()
if err == io.EOF {
return
} else if ae.SetIfError(err) {
return
}
var editsRead int64
for {
batch := make([]*KVP, 0, batchSize)
for len(batch) < batchSize {
edit := nextEdit
nextEdit, err = edits.Next()
if err == io.EOF {
if edit != nil {
batch = append(batch, edit)
}
break
} else if ae.SetIfError(err) {
return
}
isLess, err := edit.Key.Less(nbf, nextEdit.Key)
if ae.SetIfError(err) {
return
}
// keys are sorted, so if this key is not less than the next key then they are equal and the next
// value will take precedence
if !isLess {
continue
}
batch = append(batch, edit)
editsRead++
if editsRead == numEdits {
break
}
}
if len(batch) > 0 {
workResChan := make(chan mapWorkResult)
work := mapWork{workResChan, batch}
rc <- workResChan
wc <- work
} else {
break
}
batchSize = int(float32(batchSize) * batchMult)
if batchSize > batchSizeMax {
batchSize = batchSizeMax
}
}
}
func appendToWRes(ctx context.Context, wRes *mapWorkResult, cur *sequenceCursor, key Value, val Valuable) error {
var mEnt mapEntry
if val == nil {
mEnt = mapEntry{key, nil}
} else if v, ok := val.(Value); ok {
mEnt = mapEntry{key, v}
} else {
sv, err := val.Value(ctx)
if err != nil {
return err
}
mEnt = mapEntry{key, sv}
}
wRes.seqCurs = append(wRes.seqCurs, cur)
wRes.cursorEntries = append(wRes.cursorEntries, []mapEntry{mEnt})
return nil
}
func newMapLeafChunkerFromCursor(ctx context.Context, cur *sequenceCursor, vrw ValueReadWriter) (*sequenceChunker, error) {
makeChunk := makeMapLeafChunkFn(vrw)
makeParentChunk := newOrderedMetaSequenceChunkFn(MapKind, vrw)
return newSequenceChunker(ctx, cur, 0, vrw, makeChunk, makeParentChunk, newMapChunker, mapHashValueBytes)
}