-
Notifications
You must be signed in to change notification settings - Fork 271
/
filter.go
351 lines (289 loc) · 9.15 KB
/
filter.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
// Copyright 2023 Matrix Origin
//
// 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 fuzzyfilter
import (
"bytes"
"github.com/matrixorigin/matrixone/pkg/common/bloomfilter"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/logutil"
"github.com/matrixorigin/matrixone/pkg/sql/plan"
"github.com/matrixorigin/matrixone/pkg/vm"
"github.com/matrixorigin/matrixone/pkg/vm/process"
)
const maxCheckDupCount = 2000
/*
This operator is used to implement a way to ensure primary keys/unique keys are not duplicate in `INSERT` and `LOAD` statements,
You can think of it as a special type of join, but it saves more memory and is generally faster.
the BIG idea is to store
pk columns to be loaded
pk columns already exist
both in a bitmap-like data structure, let's say bloom filter below
if the final bloom filter claim that
case 1: have no duplicate keys
pass duplicate constraint directly
case 2: Not sure if there are duplicate keys because of hash collision
start a background SQL to double check
Note:
1. backgroud SQL may slow, so some optimizations could be applied
Using statistical information, when the data to be loaded is larger, the allowed false positive probability is lower,
avoiding too much content that needs to be checked.
manually check whether collision keys duplicate or not,
if duplicate, then return error timely
For uint[8|16|32], or int[8|16|32], use bitmap directly to avoid false positives and hashing
2. there is a corner case that no need to run background SQL
on duplicate key update
*/
const argName = "fuzzy_filter"
func (arg *Argument) String(buf *bytes.Buffer) {
buf.WriteString(argName)
buf.WriteString(": fuzzy check duplicate constraint")
}
func (arg *Argument) Prepare(proc *process.Process) (err error) {
arg.InitReceiver(proc, false)
rowCount := int64(arg.N)
if rowCount < 1000 {
rowCount = 1000
}
if err := arg.generate(proc); err != nil {
return err
}
useRoaring := IfCanUseRoaringFilter(types.T(arg.PkTyp.Id))
if useRoaring {
arg.roaringFilter = newroaringFilter(types.T(arg.PkTyp.Id))
} else {
//@see https://hur.st/bloomfilter/
var probability float64
if rowCount < 100001 {
probability = 0.00001
} else if rowCount < 1000001 {
probability = 0.000003
} else if rowCount < 10000001 {
probability = 0.000001
} else if rowCount < 100000001 {
probability = 0.0000005
} else if rowCount < 1000000001 {
probability = 0.0000002
} else {
probability = 0.0000001
}
arg.bloomFilter = bloomfilter.New(rowCount, probability)
}
return nil
}
func (arg *Argument) Call(proc *process.Process) (vm.CallResult, error) {
anal := proc.GetAnalyze(arg.GetIdx(), arg.GetParallelIdx(), arg.GetParallelMajor())
anal.Start()
defer anal.Stop()
if arg.roaringFilter != nil {
return arg.filterByRoaring(proc, anal)
} else {
return arg.filterByBloom(proc, anal)
}
}
func (arg *Argument) filterByBloom(proc *process.Process, anal process.Analyze) (vm.CallResult, error) {
result := vm.NewCallResult()
for {
switch arg.state {
case Build:
bat, _, err := arg.ReceiveFromSingleReg(1, anal)
if err != nil {
return result, err
}
if bat == nil {
arg.state = HandleRuntimeFilter
continue
}
if bat.IsEmpty() {
proc.PutBatch(bat)
continue
}
pkCol := bat.GetVector(0)
arg.appendPassToRuntimeFilter(pkCol, proc)
arg.bloomFilter.TestAndAdd(pkCol, func(exist bool, i int) {
if exist {
if arg.collisionCnt < maxCheckDupCount {
arg.appendCollisionKey(proc, i, bat)
return
}
logutil.Warnf("too many collision for fuzzy filter")
}
})
proc.PutBatch(bat)
continue
case HandleRuntimeFilter:
if err := arg.handleRuntimeFilter(proc); err != nil {
return result, err
}
arg.state = Probe
case Probe:
bat, _, err := arg.ReceiveFromSingleReg(0, anal)
if err != nil {
return result, err
}
if bat == nil {
// fmt.Println("probe cnt = ", arg.probeCnt)
// this will happen in such case:create unique index from a table that unique col have no data
if arg.rbat == nil || arg.collisionCnt == 0 {
result.Status = vm.ExecStop
return result, nil
}
// send collisionKeys to output operator to run background SQL
arg.rbat.SetRowCount(arg.rbat.Vecs[0].Length())
result.Batch = arg.rbat
result.Status = vm.ExecStop
arg.state = End
return result, nil
}
if bat.IsEmpty() {
proc.PutBatch(bat)
continue
}
pkCol := bat.GetVector(0)
// arg.probeCnt += pkCol.Length()
arg.bloomFilter.Test(pkCol, func(exist bool, i int) {
if exist {
if arg.collisionCnt < maxCheckDupCount {
arg.appendCollisionKey(proc, i, bat)
}
}
})
proc.PutBatch(bat)
continue
case End:
result.Status = vm.ExecStop
return result, nil
}
}
}
func (arg *Argument) filterByRoaring(proc *process.Process, anal process.Analyze) (vm.CallResult, error) {
result := vm.NewCallResult()
for {
switch arg.state {
case Build:
bat, _, err := arg.ReceiveFromSingleReg(1, anal)
if err != nil {
return result, err
}
if bat == nil {
arg.state = HandleRuntimeFilter
continue
}
if bat.IsEmpty() {
proc.PutBatch(bat)
continue
}
pkCol := bat.GetVector(0)
arg.appendPassToRuntimeFilter(pkCol, proc)
idx, dupVal := arg.roaringFilter.testAndAddFunc(arg.roaringFilter, pkCol)
proc.PutBatch(bat)
if idx == -1 {
continue
} else {
return result, moerr.NewDuplicateEntry(proc.Ctx, valueToString(dupVal), arg.PkName)
}
case HandleRuntimeFilter:
if err := arg.handleRuntimeFilter(proc); err != nil {
return result, err
}
arg.state = Probe
case Probe:
bat, _, err := arg.ReceiveFromSingleReg(0, anal)
if err != nil {
return result, err
}
if bat == nil {
// fmt.Println("probe cnt = ", arg.probeCnt)
result.Batch = arg.rbat
result.Status = vm.ExecStop
arg.state = End
return result, nil
}
if bat.IsEmpty() {
proc.PutBatch(bat)
continue
}
pkCol := bat.GetVector(0)
// arg.probeCnt += pkCol.Length()
idx, dupVal := arg.roaringFilter.testFunc(arg.roaringFilter, pkCol)
proc.PutBatch(bat)
if idx == -1 {
continue
} else {
return result, moerr.NewDuplicateEntry(proc.Ctx, valueToString(dupVal), arg.PkName)
}
case End:
result.Status = vm.ExecStop
return result, nil
}
}
}
// =========================================================================
// utils functions
func (arg *Argument) appendPassToRuntimeFilter(v *vector.Vector, proc *process.Process) {
if arg.pass2RuntimeFilter != nil && arg.RuntimeFilterSpec != nil {
el := arg.pass2RuntimeFilter.Length()
al := v.Length()
if int64(el)+int64(al) <= int64(arg.RuntimeFilterSpec.UpperLimit) {
arg.pass2RuntimeFilter.UnionMulti(v, 0, al, proc.Mp())
} else {
proc.PutVector(arg.pass2RuntimeFilter)
arg.pass2RuntimeFilter = nil
}
}
}
// appendCollisionKey will append collision key into rbat
func (arg *Argument) appendCollisionKey(proc *process.Process, idx int, bat *batch.Batch) {
pkCol := bat.GetVector(0)
arg.rbat.GetVector(0).UnionOne(pkCol, int64(idx), proc.GetMPool())
arg.collisionCnt++
}
// rbat will contain the keys that have hash collisions
func (arg *Argument) generate(proc *process.Process) error {
rbat := batch.NewWithSize(1)
rbat.SetVector(0, proc.GetVector(plan.MakeTypeByPlan2Type(arg.PkTyp)))
arg.pass2RuntimeFilter = proc.GetVector(plan.MakeTypeByPlan2Type(arg.PkTyp))
arg.rbat = rbat
return nil
}
func (arg *Argument) handleRuntimeFilter(proc *process.Process) error {
ctr := arg
if arg.RuntimeFilterSpec == nil {
return nil
}
var runtimeFilter process.RuntimeFilterMessage
runtimeFilter.Tag = arg.RuntimeFilterSpec.Tag
// the number of data insert is greater than inFilterCardLimit
if arg.RuntimeFilterSpec.Expr == nil || arg.pass2RuntimeFilter == nil {
runtimeFilter.Typ = process.RuntimeFilter_PASS
proc.SendRuntimeFilter(runtimeFilter, ctr.RuntimeFilterSpec)
return nil
}
//bloomFilterCardLimit := int64(plan.BloomFilterCardLimit)
//v, ok = runtime.ProcessLevelRuntime().GetGlobalVariables("runtime_filter_limit_bloom_filter")
//if ok {
// bloomFilterCardLimit = v.(int64)
//}
arg.pass2RuntimeFilter.InplaceSort()
data, err := arg.pass2RuntimeFilter.MarshalBinary()
if err != nil {
return err
}
runtimeFilter.Typ = process.RuntimeFilter_IN
runtimeFilter.Data = data
proc.SendRuntimeFilter(runtimeFilter, ctr.RuntimeFilterSpec)
return nil
}