ADAPT-Chase commited on
Commit
e89cd08
·
verified ·
1 Parent(s): 5ed9edf

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. platform/dbops/binaries/weaviate-src/usecases/modules/module_config_init_and_validate_test.go +492 -0
  2. platform/dbops/binaries/weaviate-src/usecases/modules/module_config_test.go +93 -0
  3. platform/dbops/binaries/weaviate-src/usecases/modules/modules.go +1151 -0
  4. platform/dbops/binaries/weaviate-src/usecases/modules/modules_generic.go +108 -0
  5. platform/dbops/binaries/weaviate-src/usecases/modules/modules_test.go +550 -0
  6. platform/dbops/binaries/weaviate-src/usecases/modules/searchers_test.go +294 -0
  7. platform/dbops/binaries/weaviate-src/usecases/modules/vectorizer.go +592 -0
  8. platform/dbops/binaries/weaviate-src/usecases/modules/vectorizer_test.go +318 -0
  9. platform/dbops/binaries/weaviate-src/usecases/monitoring/grpc.go +196 -0
  10. platform/dbops/binaries/weaviate-src/usecases/monitoring/http.go +114 -0
  11. platform/dbops/binaries/weaviate-src/usecases/monitoring/listen.go +54 -0
  12. platform/dbops/binaries/weaviate-src/usecases/monitoring/listen_test.go +87 -0
  13. platform/dbops/binaries/weaviate-src/usecases/monitoring/noop.go +25 -0
  14. platform/dbops/binaries/weaviate-src/usecases/monitoring/prometheus.go +876 -0
  15. platform/dbops/binaries/weaviate-src/usecases/monitoring/shards.go +61 -0
  16. platform/dbops/binaries/weaviate-src/usecases/monitoring/shards_test.go +118 -0
  17. platform/dbops/binaries/weaviate-src/usecases/multitenancy/extensions.go +19 -0
  18. platform/dbops/binaries/weaviate-src/usecases/multitenancy/extensions_test.go +66 -0
  19. platform/dbops/binaries/weaviate-src/usecases/nodes/handler.go +101 -0
  20. platform/dbops/binaries/weaviate-src/usecases/objects/add.go +190 -0
  21. platform/dbops/binaries/weaviate-src/usecases/objects/add_test.go +556 -0
  22. platform/dbops/binaries/weaviate-src/usecases/objects/authorization_test.go +321 -0
  23. platform/dbops/binaries/weaviate-src/usecases/objects/auto_schema.go +607 -0
  24. platform/dbops/binaries/weaviate-src/usecases/objects/auto_schema_test.go +1712 -0
  25. platform/dbops/binaries/weaviate-src/usecases/objects/batch_add.go +207 -0
  26. platform/dbops/binaries/weaviate-src/usecases/objects/batch_add_test.go +503 -0
  27. platform/dbops/binaries/weaviate-src/usecases/objects/batch_delete.go +175 -0
  28. platform/dbops/binaries/weaviate-src/usecases/objects/batch_delete_test.go +190 -0
  29. platform/dbops/binaries/weaviate-src/usecases/objects/batch_manager.go +77 -0
  30. platform/dbops/binaries/weaviate-src/usecases/objects/batch_references_add.go +380 -0
  31. platform/dbops/binaries/weaviate-src/usecases/objects/batch_types.go +97 -0
  32. platform/dbops/binaries/weaviate-src/usecases/objects/delete.go +118 -0
  33. platform/dbops/binaries/weaviate-src/usecases/objects/delete_test.go +113 -0
  34. platform/dbops/binaries/weaviate-src/usecases/objects/errors.go +174 -0
  35. platform/dbops/binaries/weaviate-src/usecases/objects/fakes_for_test.go +887 -0
  36. platform/dbops/binaries/weaviate-src/usecases/objects/get.go +274 -0
  37. platform/dbops/binaries/weaviate-src/usecases/objects/get_test.go +1099 -0
  38. platform/dbops/binaries/weaviate-src/usecases/objects/head.go +54 -0
  39. platform/dbops/binaries/weaviate-src/usecases/objects/head_test.go +82 -0
  40. platform/dbops/binaries/weaviate-src/usecases/objects/manager.go +203 -0
  41. platform/dbops/binaries/weaviate-src/usecases/objects/merge.go +285 -0
  42. platform/dbops/binaries/weaviate-src/usecases/objects/merge_test.go +525 -0
  43. platform/dbops/binaries/weaviate-src/usecases/objects/metrics.go +210 -0
  44. platform/dbops/binaries/weaviate-src/usecases/objects/models_for_test.go +26 -0
  45. platform/dbops/binaries/weaviate-src/usecases/objects/query.go +122 -0
  46. platform/dbops/binaries/weaviate-src/usecases/objects/query_test.go +156 -0
  47. platform/dbops/binaries/weaviate-src/usecases/objects/references.go +76 -0
  48. platform/dbops/binaries/weaviate-src/usecases/objects/references_add.go +199 -0
  49. platform/dbops/binaries/weaviate-src/usecases/objects/references_delete.go +190 -0
  50. platform/dbops/binaries/weaviate-src/usecases/objects/references_test.go +810 -0
platform/dbops/binaries/weaviate-src/usecases/modules/module_config_init_and_validate_test.go ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+ "testing"
17
+
18
+ "github.com/pkg/errors"
19
+ "github.com/sirupsen/logrus/hooks/test"
20
+ "github.com/stretchr/testify/assert"
21
+ "github.com/stretchr/testify/require"
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
24
+ "github.com/weaviate/weaviate/entities/moduletools"
25
+ "github.com/weaviate/weaviate/entities/schema"
26
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
27
+ "github.com/weaviate/weaviate/usecases/config"
28
+ )
29
+
30
+ func TestSetClassDefaults(t *testing.T) {
31
+ logger, _ := test.NewNullLogger()
32
+ t.Run("no modules", func(t *testing.T) {
33
+ class := &models.Class{
34
+ Class: "Foo",
35
+ Vectorizer: "none",
36
+ }
37
+
38
+ p := NewProvider(logger, config.Config{})
39
+ p.SetClassDefaults(class)
40
+
41
+ assert.Equal(t, &models.Class{Class: "Foo", Vectorizer: "none"}, class,
42
+ "the class is not changed")
43
+ })
44
+
45
+ t.Run("module is set, but does not have config capability", func(t *testing.T) {
46
+ class := &models.Class{
47
+ Class: "Foo",
48
+ Vectorizer: "my-module",
49
+ }
50
+
51
+ p := NewProvider(logger, config.Config{})
52
+ p.Register(&dummyText2VecModuleNoCapabilities{name: "my-module"})
53
+ p.SetClassDefaults(class)
54
+
55
+ assert.Equal(t, &models.Class{Class: "Foo", Vectorizer: "my-module"}, class,
56
+ "the class is not changed")
57
+ })
58
+
59
+ t.Run("without user-provided values", func(t *testing.T) {
60
+ class := &models.Class{
61
+ Class: "Foo",
62
+ Properties: []*models.Property{{
63
+ Name: "Foo",
64
+ DataType: schema.DataTypeText.PropString(),
65
+ Tokenization: models.PropertyTokenizationWhitespace,
66
+ }},
67
+ Vectorizer: "my-module",
68
+ }
69
+ expected := &models.Class{
70
+ Class: "Foo",
71
+ ModuleConfig: map[string]interface{}{
72
+ "my-module": map[string]interface{}{
73
+ "per-class-prop-1": "some default value",
74
+ "per-class-prop-2": "some default value",
75
+ },
76
+ },
77
+ Properties: []*models.Property{{
78
+ Name: "Foo",
79
+ DataType: schema.DataTypeText.PropString(),
80
+ Tokenization: models.PropertyTokenizationWhitespace,
81
+ ModuleConfig: map[string]interface{}{
82
+ "my-module": map[string]interface{}{
83
+ "per-prop-1": "prop default value",
84
+ "per-prop-2": "prop default value",
85
+ },
86
+ },
87
+ }},
88
+ Vectorizer: "my-module",
89
+ }
90
+
91
+ p := NewProvider(logger, config.Config{})
92
+ p.Register(&dummyModuleClassConfigurator{
93
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
94
+ name: "my-module",
95
+ },
96
+ })
97
+ p.SetClassDefaults(class)
98
+
99
+ assert.Equal(t, expected, class,
100
+ "the defaults were set from config")
101
+ })
102
+
103
+ t.Run("with some user-provided values", func(t *testing.T) {
104
+ class := &models.Class{
105
+ Class: "Foo",
106
+ ModuleConfig: map[string]interface{}{
107
+ "my-module": map[string]interface{}{
108
+ "per-class-prop-1": "overwritten by user",
109
+ },
110
+ },
111
+ Properties: []*models.Property{{
112
+ Name: "Foo",
113
+ DataType: schema.DataTypeText.PropString(),
114
+ Tokenization: models.PropertyTokenizationWhitespace,
115
+ ModuleConfig: map[string]interface{}{
116
+ "my-module": map[string]interface{}{
117
+ "per-prop-1": "prop overwritten by user",
118
+ },
119
+ },
120
+ }},
121
+ Vectorizer: "my-module",
122
+ }
123
+ expected := &models.Class{
124
+ Class: "Foo",
125
+ ModuleConfig: map[string]interface{}{
126
+ "my-module": map[string]interface{}{
127
+ "per-class-prop-1": "overwritten by user",
128
+ "per-class-prop-2": "some default value",
129
+ },
130
+ },
131
+ Properties: []*models.Property{{
132
+ Name: "Foo",
133
+ DataType: schema.DataTypeText.PropString(),
134
+ Tokenization: models.PropertyTokenizationWhitespace,
135
+ ModuleConfig: map[string]interface{}{
136
+ "my-module": map[string]interface{}{
137
+ "per-prop-1": "prop overwritten by user",
138
+ "per-prop-2": "prop default value",
139
+ },
140
+ },
141
+ }},
142
+ Vectorizer: "my-module",
143
+ }
144
+
145
+ p := NewProvider(logger, config.Config{})
146
+ p.Register(&dummyModuleClassConfigurator{
147
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
148
+ name: "my-module",
149
+ },
150
+ })
151
+ p.SetClassDefaults(class)
152
+
153
+ assert.Equal(t, expected, class,
154
+ "the defaults were set from config")
155
+ })
156
+
157
+ t.Run("named vector, without user-provided values", func(t *testing.T) {
158
+ class := &models.Class{
159
+ Class: "Foo",
160
+ Properties: []*models.Property{{
161
+ Name: "Foo",
162
+ DataType: schema.DataTypeText.PropString(),
163
+ Tokenization: models.PropertyTokenizationWhitespace,
164
+ }},
165
+ VectorConfig: map[string]models.VectorConfig{
166
+ "vec1": {
167
+ Vectorizer: map[string]interface{}{"my-module": map[string]interface{}{}},
168
+ },
169
+ },
170
+ }
171
+ expected := &models.Class{
172
+ Class: "Foo",
173
+ Properties: []*models.Property{{
174
+ Name: "Foo",
175
+ DataType: schema.DataTypeText.PropString(),
176
+ Tokenization: models.PropertyTokenizationWhitespace,
177
+ ModuleConfig: map[string]interface{}{
178
+ "my-module": map[string]interface{}{
179
+ "per-prop-1": "prop default value",
180
+ "per-prop-2": "prop default value",
181
+ },
182
+ },
183
+ }},
184
+ VectorConfig: map[string]models.VectorConfig{
185
+ "vec1": {
186
+ Vectorizer: map[string]interface{}{
187
+ "my-module": map[string]interface{}{
188
+ "per-class-prop-1": "some default value",
189
+ "per-class-prop-2": "some default value",
190
+ },
191
+ },
192
+ },
193
+ },
194
+ }
195
+
196
+ p := NewProvider(logger, config.Config{})
197
+ p.Register(&dummyModuleClassConfigurator{
198
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
199
+ name: "my-module",
200
+ },
201
+ })
202
+ p.SetClassDefaults(class)
203
+
204
+ assert.Equal(t, expected, class, "the defaults were set from config")
205
+ })
206
+
207
+ t.Run("mixed vector, without user-provided values", func(t *testing.T) {
208
+ class := &models.Class{
209
+ Class: "Foo",
210
+ Properties: []*models.Property{{
211
+ Name: "Foo",
212
+ DataType: schema.DataTypeText.PropString(),
213
+ Tokenization: models.PropertyTokenizationWhitespace,
214
+ }},
215
+ VectorConfig: map[string]models.VectorConfig{
216
+ "vec1": {
217
+ Vectorizer: map[string]interface{}{"my-module": map[string]interface{}{}},
218
+ },
219
+ },
220
+ Vectorizer: "my-module",
221
+ VectorIndexConfig: hnsw.NewDefaultUserConfig(),
222
+ }
223
+ expected := &models.Class{
224
+ Class: "Foo",
225
+ Properties: []*models.Property{{
226
+ Name: "Foo",
227
+ DataType: schema.DataTypeText.PropString(),
228
+ Tokenization: models.PropertyTokenizationWhitespace,
229
+ ModuleConfig: map[string]interface{}{
230
+ "my-module": map[string]interface{}{
231
+ "per-prop-1": "prop default value",
232
+ "per-prop-2": "prop default value",
233
+ },
234
+ },
235
+ }},
236
+ VectorConfig: map[string]models.VectorConfig{
237
+ "vec1": {
238
+ Vectorizer: map[string]interface{}{
239
+ "my-module": map[string]interface{}{
240
+ "per-class-prop-1": "some default value",
241
+ "per-class-prop-2": "some default value",
242
+ },
243
+ },
244
+ },
245
+ },
246
+ Vectorizer: "my-module",
247
+ ModuleConfig: map[string]interface{}{
248
+ "my-module": map[string]interface{}{
249
+ "per-class-prop-1": "some default value",
250
+ "per-class-prop-2": "some default value",
251
+ },
252
+ },
253
+ VectorIndexConfig: hnsw.NewDefaultUserConfig(),
254
+ }
255
+
256
+ p := NewProvider(logger, config.Config{})
257
+ p.Register(&dummyModuleClassConfigurator{
258
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
259
+ name: "my-module",
260
+ },
261
+ })
262
+ p.SetClassDefaults(class)
263
+
264
+ assert.Equal(t, expected, class, "the defaults were set from config")
265
+ })
266
+ }
267
+
268
+ func TestValidateClass(t *testing.T) {
269
+ ctx := context.Background()
270
+ logger, _ := test.NewNullLogger()
271
+ t.Run("when class has no vectorizer set, it does not check", func(t *testing.T) {
272
+ class := &models.Class{
273
+ Class: "Foo",
274
+ Properties: []*models.Property{{
275
+ Name: "Foo",
276
+ DataType: schema.DataTypeText.PropString(),
277
+ Tokenization: models.PropertyTokenizationWhitespace,
278
+ }},
279
+ Vectorizer: "none",
280
+ }
281
+
282
+ p := NewProvider(logger, config.Config{})
283
+ p.Register(&dummyModuleClassConfigurator{
284
+ validateError: errors.Errorf("if I was used, you'd fail"),
285
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
286
+ name: "my-module",
287
+ },
288
+ })
289
+ p.SetClassDefaults(class)
290
+
291
+ assert.Nil(t, p.ValidateClass(ctx, class))
292
+ })
293
+
294
+ t.Run("when vectorizer does not have capability, it skips validation",
295
+ func(t *testing.T) {
296
+ class := &models.Class{
297
+ Class: "Foo",
298
+ Properties: []*models.Property{{
299
+ Name: "Foo",
300
+ DataType: schema.DataTypeText.PropString(),
301
+ Tokenization: models.PropertyTokenizationWhitespace,
302
+ }},
303
+ Vectorizer: "my-module",
304
+ }
305
+
306
+ p := NewProvider(logger, config.Config{})
307
+ p.Register(&dummyText2VecModuleNoCapabilities{
308
+ name: "my-module",
309
+ })
310
+ p.SetClassDefaults(class)
311
+
312
+ assert.Nil(t, p.ValidateClass(ctx, class))
313
+ })
314
+
315
+ t.Run("the module validates if capable and configured", func(t *testing.T) {
316
+ class := &models.Class{
317
+ Class: "Foo",
318
+ Properties: []*models.Property{{
319
+ Name: "Foo",
320
+ DataType: schema.DataTypeText.PropString(),
321
+ Tokenization: models.PropertyTokenizationWhitespace,
322
+ }},
323
+ Vectorizer: "my-module",
324
+ }
325
+
326
+ p := NewProvider(logger, config.Config{})
327
+ p.Register(&dummyModuleClassConfigurator{
328
+ validateError: errors.Errorf("no can do!"),
329
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
330
+ name: "my-module",
331
+ },
332
+ })
333
+ p.SetClassDefaults(class)
334
+
335
+ err := p.ValidateClass(ctx, class)
336
+ require.NotNil(t, err)
337
+ assert.Equal(t, "module 'my-module': no can do!", err.Error())
338
+ })
339
+ }
340
+
341
+ func TestSetSinglePropertyDefaults(t *testing.T) {
342
+ class := &models.Class{
343
+ Class: "Foo",
344
+ ModuleConfig: map[string]interface{}{
345
+ "my-module": map[string]interface{}{
346
+ "per-class-prop-1": "overwritten by user",
347
+ },
348
+ },
349
+ Properties: []*models.Property{{
350
+ Name: "Foo",
351
+ DataType: schema.DataTypeText.PropString(),
352
+ Tokenization: models.PropertyTokenizationWhitespace,
353
+ ModuleConfig: map[string]interface{}{
354
+ "my-module": map[string]interface{}{
355
+ "per-prop-1": "prop overwritten by user",
356
+ },
357
+ },
358
+ }},
359
+ Vectorizer: "my-module",
360
+ }
361
+ prop := &models.Property{
362
+ DataType: []string{"boolean"},
363
+ ModuleConfig: map[string]interface{}{
364
+ "my-module": map[string]interface{}{
365
+ "per-prop-1": "overwritten by user",
366
+ },
367
+ },
368
+ Name: "newProp",
369
+ }
370
+ expected := &models.Property{
371
+ DataType: []string{"boolean"},
372
+ ModuleConfig: map[string]interface{}{
373
+ "my-module": map[string]interface{}{
374
+ "per-prop-1": "overwritten by user",
375
+ "per-prop-2": "prop default value",
376
+ },
377
+ },
378
+ Name: "newProp",
379
+ }
380
+
381
+ logger, _ := test.NewNullLogger()
382
+ p := NewProvider(logger, config.Config{})
383
+ p.Register(&dummyModuleClassConfigurator{
384
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
385
+ name: "my-module",
386
+ },
387
+ })
388
+ p.SetSinglePropertyDefaults(class, prop)
389
+
390
+ assert.Equal(t, expected, prop,
391
+ "user specified module config is used, for rest the default value is used")
392
+ }
393
+
394
+ func TestSetSinglePropertyDefaults_MixedVectors(t *testing.T) {
395
+ class := &models.Class{
396
+ Class: "Foo",
397
+ Properties: []*models.Property{{
398
+ Name: "Foo",
399
+ DataType: schema.DataTypeText.PropString(),
400
+ Tokenization: models.PropertyTokenizationWhitespace,
401
+ ModuleConfig: map[string]interface{}{
402
+ "my-module": map[string]interface{}{
403
+ "per-prop-1": "prop overwritten by user",
404
+ },
405
+ },
406
+ }},
407
+ Vectorizer: "my-module",
408
+ ModuleConfig: map[string]interface{}{
409
+ "my-module": map[string]interface{}{
410
+ "per-class-prop-1": "overwritten by user",
411
+ },
412
+ },
413
+ VectorIndexConfig: hnsw.NewDefaultUserConfig(),
414
+ VectorConfig: map[string]models.VectorConfig{
415
+ "vec1": {
416
+ Vectorizer: map[string]interface{}{
417
+ "my-module-2": map[string]interface{}{},
418
+ },
419
+ },
420
+ },
421
+ }
422
+ prop := &models.Property{
423
+ DataType: []string{"boolean"},
424
+ ModuleConfig: map[string]interface{}{
425
+ "my-module": map[string]interface{}{
426
+ "per-prop-1": "overwritten by user",
427
+ },
428
+ },
429
+ Name: "newProp",
430
+ }
431
+ expected := &models.Property{
432
+ DataType: []string{"boolean"},
433
+ ModuleConfig: map[string]interface{}{
434
+ "my-module": map[string]interface{}{
435
+ "per-prop-1": "overwritten by user",
436
+ "per-prop-2": "prop default value",
437
+ },
438
+ "my-module-2": map[string]interface{}{
439
+ "per-prop-1": "prop default value",
440
+ "per-prop-2": "prop default value",
441
+ },
442
+ },
443
+ Name: "newProp",
444
+ }
445
+
446
+ logger, _ := test.NewNullLogger()
447
+ p := NewProvider(logger, config.Config{})
448
+ p.Register(&dummyModuleClassConfigurator{
449
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
450
+ name: "my-module",
451
+ },
452
+ })
453
+ p.Register(&dummyModuleClassConfigurator{
454
+ dummyText2VecModuleNoCapabilities: dummyText2VecModuleNoCapabilities{
455
+ name: "my-module-2",
456
+ },
457
+ })
458
+ p.SetSinglePropertyDefaults(class, prop)
459
+
460
+ assert.Equal(t, expected, prop,
461
+ "user specified module config is used, for rest the default value is used")
462
+ }
463
+
464
+ type dummyModuleClassConfigurator struct {
465
+ dummyText2VecModuleNoCapabilities
466
+ validateError error
467
+ }
468
+
469
+ func (d *dummyModuleClassConfigurator) ClassConfigDefaults() map[string]interface{} {
470
+ return map[string]interface{}{
471
+ "per-class-prop-1": "some default value",
472
+ "per-class-prop-2": "some default value",
473
+ }
474
+ }
475
+
476
+ func (d *dummyModuleClassConfigurator) PropertyConfigDefaults(
477
+ dt *schema.DataType,
478
+ ) map[string]interface{} {
479
+ return map[string]interface{}{
480
+ "per-prop-1": "prop default value",
481
+ "per-prop-2": "prop default value",
482
+ }
483
+ }
484
+
485
+ func (d *dummyModuleClassConfigurator) ValidateClass(ctx context.Context,
486
+ class *models.Class, cfg moduletools.ClassConfig,
487
+ ) error {
488
+ return d.validateError
489
+ }
490
+
491
+ var _ = modulecapabilities.ClassConfigurator(
492
+ &dummyModuleClassConfigurator{})
platform/dbops/binaries/weaviate-src/usecases/modules/module_config_test.go ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/stretchr/testify/assert"
18
+ "github.com/weaviate/weaviate/entities/models"
19
+ )
20
+
21
+ func TestClassBasedModuleConfig(t *testing.T) {
22
+ t.Run("when the prop doesn't exist", func(t *testing.T) {
23
+ class := &models.Class{
24
+ Class: "Test",
25
+ }
26
+ cfg := NewClassBasedModuleConfig(class, "my-module", "tenant", "", nil)
27
+ assert.Equal(t, map[string]interface{}{}, cfg.Property("some-prop"))
28
+ })
29
+
30
+ t.Run("without any module-specific config", func(t *testing.T) {
31
+ class := &models.Class{
32
+ Class: "Test",
33
+ Properties: []*models.Property{
34
+ {
35
+ Name: "some-prop",
36
+ },
37
+ },
38
+ }
39
+ cfg := NewClassBasedModuleConfig(class, "my-module", "tenant", "", nil)
40
+ assert.Equal(t, map[string]interface{}{}, cfg.Class())
41
+ assert.Equal(t, map[string]interface{}{}, cfg.Property("some-prop"))
42
+ })
43
+
44
+ t.Run("with config for other modules set", func(t *testing.T) {
45
+ class := &models.Class{
46
+ Class: "Test",
47
+ ModuleConfig: map[string]interface{}{
48
+ "other-module": map[string]interface{}{
49
+ "classLevel": "foo",
50
+ },
51
+ },
52
+ Properties: []*models.Property{
53
+ {
54
+ Name: "some-prop",
55
+ ModuleConfig: map[string]interface{}{
56
+ "other-module": map[string]interface{}{
57
+ "propLevel": "bar",
58
+ },
59
+ },
60
+ },
61
+ },
62
+ }
63
+ cfg := NewClassBasedModuleConfig(class, "my-module", "tenant", "", nil)
64
+ assert.Equal(t, map[string]interface{}{}, cfg.Class())
65
+ assert.Equal(t, map[string]interface{}{},
66
+ cfg.Property("some-prop"))
67
+ })
68
+
69
+ t.Run("with all config set", func(t *testing.T) {
70
+ class := &models.Class{
71
+ Class: "Test",
72
+ ModuleConfig: map[string]interface{}{
73
+ "my-module": map[string]interface{}{
74
+ "classLevel": "foo",
75
+ },
76
+ },
77
+ Properties: []*models.Property{
78
+ {
79
+ Name: "some-prop",
80
+ ModuleConfig: map[string]interface{}{
81
+ "my-module": map[string]interface{}{
82
+ "propLevel": "bar",
83
+ },
84
+ },
85
+ },
86
+ },
87
+ }
88
+ cfg := NewClassBasedModuleConfig(class, "my-module", "tenant", "", nil)
89
+ assert.Equal(t, map[string]interface{}{"classLevel": "foo"}, cfg.Class())
90
+ assert.Equal(t, map[string]interface{}{"propLevel": "bar"},
91
+ cfg.Property("some-prop"))
92
+ })
93
+ }
platform/dbops/binaries/weaviate-src/usecases/modules/modules.go ADDED
@@ -0,0 +1,1151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "regexp"
18
+ "slices"
19
+ "sync"
20
+
21
+ "github.com/pkg/errors"
22
+ "github.com/sirupsen/logrus"
23
+ "github.com/tailor-inc/graphql"
24
+ "github.com/tailor-inc/graphql/language/ast"
25
+
26
+ "github.com/weaviate/weaviate/entities/dto"
27
+ "github.com/weaviate/weaviate/entities/models"
28
+ "github.com/weaviate/weaviate/entities/modelsext"
29
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
30
+ "github.com/weaviate/weaviate/entities/moduletools"
31
+ "github.com/weaviate/weaviate/entities/schema"
32
+ "github.com/weaviate/weaviate/entities/search"
33
+ "github.com/weaviate/weaviate/usecases/config"
34
+ "github.com/weaviate/weaviate/usecases/modulecomponents"
35
+ )
36
+
37
+ var (
38
+ internalSearchers = []string{
39
+ "nearObject", "nearVector", "where", "group", "limit", "offset",
40
+ "after", "groupBy", "bm25", "hybrid",
41
+ }
42
+ internalAdditionalProperties = []string{"classification", "certainty", "id", "distance", "group"}
43
+ )
44
+
45
+ type Provider struct {
46
+ vectorsLock sync.RWMutex
47
+ registered map[string]modulecapabilities.Module
48
+ altNames map[string]string
49
+ schemaGetter schemaGetter
50
+ hasMultipleVectorizers bool
51
+ targetVectorNameValidator *regexp.Regexp
52
+ logger logrus.FieldLogger
53
+ cfg config.Config
54
+ }
55
+
56
+ type schemaGetter interface {
57
+ ReadOnlyClass(name string) *models.Class
58
+ }
59
+
60
+ func NewProvider(logger logrus.FieldLogger, cfg config.Config) *Provider {
61
+ return &Provider{
62
+ registered: map[string]modulecapabilities.Module{},
63
+ altNames: map[string]string{},
64
+ targetVectorNameValidator: regexp.MustCompile(`^` + schema.TargetVectorNameRegex + `$`),
65
+ logger: logger,
66
+ cfg: cfg,
67
+ }
68
+ }
69
+
70
+ func (p *Provider) Register(mod modulecapabilities.Module) {
71
+ p.registered[mod.Name()] = mod
72
+ if modHasAltNames, ok := mod.(modulecapabilities.ModuleHasAltNames); ok {
73
+ for _, altName := range modHasAltNames.AltNames() {
74
+ p.altNames[altName] = mod.Name()
75
+ }
76
+ }
77
+ }
78
+
79
+ func (p *Provider) GetByName(name string) modulecapabilities.Module {
80
+ if mod, ok := p.registered[name]; ok {
81
+ return mod
82
+ }
83
+ if origName, ok := p.altNames[name]; ok {
84
+ return p.registered[origName]
85
+ }
86
+ return nil
87
+ }
88
+
89
+ func (p *Provider) GetAll() []modulecapabilities.Module {
90
+ out := make([]modulecapabilities.Module, len(p.registered))
91
+ i := 0
92
+ for _, mod := range p.registered {
93
+ out[i] = mod
94
+ i++
95
+ }
96
+
97
+ return out
98
+ }
99
+
100
+ func (p *Provider) GetAllWithHTTPHandlers() []modulecapabilities.ModuleWithHTTPHandlers {
101
+ out := make([]modulecapabilities.ModuleWithHTTPHandlers, 0)
102
+ for _, mod := range p.registered {
103
+ if modWithHTTPHandlers, ok := mod.(modulecapabilities.ModuleWithHTTPHandlers); ok {
104
+ out = append(out, modWithHTTPHandlers)
105
+ }
106
+ }
107
+
108
+ return out
109
+ }
110
+
111
+ func (p *Provider) GetAllExclude(module string) []modulecapabilities.Module {
112
+ filtered := []modulecapabilities.Module{}
113
+ for _, mod := range p.GetAll() {
114
+ if mod.Name() != module {
115
+ filtered = append(filtered, mod)
116
+ }
117
+ }
118
+ return filtered
119
+ }
120
+
121
+ func (p *Provider) Close() error {
122
+ for _, mod := range p.registered {
123
+ if m, ok := mod.(modulecapabilities.ModuleWithClose); ok {
124
+ if err := m.Close(); err != nil {
125
+ return err
126
+ }
127
+ }
128
+ }
129
+
130
+ return nil
131
+ }
132
+
133
+ func (p *Provider) SetSchemaGetter(sg schemaGetter) {
134
+ p.schemaGetter = sg
135
+ }
136
+
137
+ func (p *Provider) Init(ctx context.Context,
138
+ params moduletools.ModuleInitParams, logger logrus.FieldLogger,
139
+ ) error {
140
+ for i, mod := range p.GetAll() {
141
+ if err := mod.Init(ctx, params); err != nil {
142
+ return errors.Wrapf(err, "init module %d (%q)", i, mod.Name())
143
+ } else {
144
+ logger.WithField("action", "startup").
145
+ WithField("module", mod.Name()).
146
+ Debug("initialized module")
147
+ }
148
+ }
149
+ for i, mod := range p.GetAll() {
150
+ if modExtension, ok := mod.(modulecapabilities.ModuleExtension); ok {
151
+ if err := modExtension.InitExtension(p.GetAllExclude(mod.Name())); err != nil {
152
+ return errors.Wrapf(err, "init module extension %d (%q)", i, mod.Name())
153
+ } else {
154
+ logger.WithField("action", "startup").
155
+ WithField("module", mod.Name()).
156
+ Debug("initialized module extension")
157
+ }
158
+ }
159
+ }
160
+ for i, mod := range p.GetAll() {
161
+ if modDependency, ok := mod.(modulecapabilities.ModuleDependency); ok {
162
+ if err := modDependency.InitDependency(p.GetAllExclude(mod.Name())); err != nil {
163
+ return errors.Wrapf(err, "init module dependency %d (%q)", i, mod.Name())
164
+ } else {
165
+ logger.WithField("action", "startup").
166
+ WithField("module", mod.Name()).
167
+ Debug("initialized module dependency")
168
+ }
169
+ }
170
+ }
171
+ if err := p.validate(); err != nil {
172
+ return errors.Wrap(err, "validate modules")
173
+ }
174
+ if p.HasMultipleVectorizers() {
175
+ logger.Warn("Multiple vector spaces are present, GraphQL Explore and REST API list objects endpoint module include params has been disabled as a result.")
176
+ }
177
+ return nil
178
+ }
179
+
180
+ func (p *Provider) validate() error {
181
+ searchers := map[string][]string{}
182
+ additionalGraphQLProps := map[string][]string{}
183
+ additionalRestAPIProps := map[string][]string{}
184
+ for _, mod := range p.GetAll() {
185
+ if module, ok := mod.(modulecapabilities.GraphQLArguments); ok {
186
+ allArguments := []string{}
187
+ for paraName, argument := range module.Arguments() {
188
+ if argument.ExtractFunction != nil {
189
+ allArguments = append(allArguments, paraName)
190
+ }
191
+ }
192
+ searchers = p.scanProperties(searchers, allArguments, mod.Name())
193
+ }
194
+ if module, ok := mod.(modulecapabilities.AdditionalProperties); ok {
195
+ allAdditionalRestAPIProps, allAdditionalGrapQLProps := p.getAdditionalProps(module.AdditionalProperties())
196
+ additionalGraphQLProps = p.scanProperties(additionalGraphQLProps,
197
+ allAdditionalGrapQLProps, mod.Name())
198
+ additionalRestAPIProps = p.scanProperties(additionalRestAPIProps,
199
+ allAdditionalRestAPIProps, mod.Name())
200
+ }
201
+ }
202
+
203
+ var errorMessages []string
204
+ errorMessages = append(errorMessages,
205
+ p.validateModules("searcher", searchers, internalSearchers)...)
206
+ errorMessages = append(errorMessages,
207
+ p.validateModules("graphql additional property", additionalGraphQLProps, internalAdditionalProperties)...)
208
+ errorMessages = append(errorMessages,
209
+ p.validateModules("rest api additional property", additionalRestAPIProps, internalAdditionalProperties)...)
210
+ if len(errorMessages) > 0 {
211
+ return errors.Errorf("%v", errorMessages)
212
+ }
213
+
214
+ return nil
215
+ }
216
+
217
+ func (p *Provider) scanProperties(result map[string][]string, properties []string, module string) map[string][]string {
218
+ for i := range properties {
219
+ if result[properties[i]] == nil {
220
+ result[properties[i]] = []string{}
221
+ }
222
+ modules := result[properties[i]]
223
+ modules = append(modules, module)
224
+ result[properties[i]] = modules
225
+ }
226
+ return result
227
+ }
228
+
229
+ func (p *Provider) getAdditionalProps(additionalProps map[string]modulecapabilities.AdditionalProperty) ([]string, []string) {
230
+ restProps := []string{}
231
+ graphQLProps := []string{}
232
+
233
+ for _, additionalProperty := range additionalProps {
234
+ if additionalProperty.RestNames != nil {
235
+ restProps = append(restProps, additionalProperty.RestNames...)
236
+ }
237
+ if additionalProperty.GraphQLNames != nil {
238
+ graphQLProps = append(graphQLProps, additionalProperty.GraphQLNames...)
239
+ }
240
+ }
241
+ return restProps, graphQLProps
242
+ }
243
+
244
+ func (p *Provider) validateModules(name string, properties map[string][]string, internalProperties []string) []string {
245
+ errorMessages := []string{}
246
+ for propertyName, modules := range properties {
247
+ for i := range internalProperties {
248
+ if internalProperties[i] == propertyName {
249
+ errorMessages = append(errorMessages,
250
+ fmt.Sprintf("%s: %s conflicts with weaviate's internal searcher in modules: %v",
251
+ name, propertyName, modules))
252
+ }
253
+ }
254
+ if len(modules) > 1 {
255
+ p.hasMultipleVectorizers = true
256
+ }
257
+ for _, moduleName := range modules {
258
+ moduleType := p.GetByName(moduleName).Type()
259
+ if p.moduleProvidesMultipleVectorizers(moduleType) {
260
+ p.hasMultipleVectorizers = true
261
+ }
262
+ }
263
+ }
264
+ return errorMessages
265
+ }
266
+
267
+ func (p *Provider) moduleProvidesMultipleVectorizers(moduleType modulecapabilities.ModuleType) bool {
268
+ return moduleType == modulecapabilities.Text2ManyVec
269
+ }
270
+
271
+ func (p *Provider) isOnlyOneModuleEnabledOfAGivenType(moduleType modulecapabilities.ModuleType) bool {
272
+ i := 0
273
+ for _, mod := range p.registered {
274
+ if mod.Type() == moduleType {
275
+ i++
276
+ }
277
+ }
278
+ return i == 1
279
+ }
280
+
281
+ func (p *Provider) IsGenerative(modName string) bool {
282
+ mod := p.GetByName(modName)
283
+ if mod == nil {
284
+ return false
285
+ }
286
+ return mod.Type() == modulecapabilities.Text2TextGenerative
287
+ }
288
+
289
+ func (p *Provider) IsReranker(modName string) bool {
290
+ mod := p.GetByName(modName)
291
+ if mod == nil {
292
+ return false
293
+ }
294
+ return mod.Type() == modulecapabilities.Text2TextReranker
295
+ }
296
+
297
+ func (p *Provider) IsMultiVector(modName string) bool {
298
+ mod := p.GetByName(modName)
299
+ if mod == nil {
300
+ return false
301
+ }
302
+ return mod.Type() == modulecapabilities.Text2Multivec || mod.Type() == modulecapabilities.Multi2Multivec
303
+ }
304
+
305
+ func (p *Provider) isVectorizerModule(moduleType modulecapabilities.ModuleType) bool {
306
+ switch moduleType {
307
+ case modulecapabilities.Text2Vec,
308
+ modulecapabilities.Img2Vec,
309
+ modulecapabilities.Multi2Vec,
310
+ modulecapabilities.Text2ManyVec,
311
+ modulecapabilities.Ref2Vec,
312
+ modulecapabilities.Text2Multivec,
313
+ modulecapabilities.Multi2Multivec:
314
+ return true
315
+ default:
316
+ return false
317
+ }
318
+ }
319
+
320
+ func (p *Provider) isGenerativeModule(moduleType modulecapabilities.ModuleType) bool {
321
+ return moduleType == modulecapabilities.Text2TextGenerative
322
+ }
323
+
324
+ func (p *Provider) shouldIncludeClassArgument(class *models.Class, module string,
325
+ moduleType modulecapabilities.ModuleType, altNames []string,
326
+ ) bool {
327
+ if p.isVectorizerModule(moduleType) {
328
+ for _, vectorConfig := range class.VectorConfig {
329
+ if vectorizer, ok := vectorConfig.Vectorizer.(map[string]interface{}); ok {
330
+ if _, ok := vectorizer[module]; ok {
331
+ return true
332
+ } else if len(altNames) > 0 {
333
+ for _, altName := range altNames {
334
+ if _, ok := vectorizer[altName]; ok {
335
+ return true
336
+ }
337
+ }
338
+ }
339
+ }
340
+ }
341
+ for _, altName := range altNames {
342
+ if class.Vectorizer == altName {
343
+ return true
344
+ }
345
+ }
346
+ return class.Vectorizer == module
347
+ }
348
+ if moduleConfig, ok := class.ModuleConfig.(map[string]interface{}); ok {
349
+ if _, ok := moduleConfig[module]; ok {
350
+ return true
351
+ } else if len(altNames) > 0 {
352
+ for _, altName := range altNames {
353
+ if _, ok := moduleConfig[altName]; ok {
354
+ return true
355
+ }
356
+ }
357
+ }
358
+ }
359
+ // Allow Text2Text (QnA, Generative, Summarize, NER) modules to be registered to a given class
360
+ // only if there's no configuration present and there's only one module of a given type enabled
361
+ return p.isOnlyOneModuleEnabledOfAGivenType(moduleType)
362
+ }
363
+
364
+ func (p *Provider) shouldCrossClassIncludeClassArgument(class *models.Class, module string,
365
+ moduleType modulecapabilities.ModuleType, altNames []string,
366
+ ) bool {
367
+ if class == nil {
368
+ return !p.HasMultipleVectorizers()
369
+ }
370
+ return p.shouldIncludeClassArgument(class, module, moduleType, altNames)
371
+ }
372
+
373
+ func (p *Provider) shouldIncludeArgument(schema *models.Schema, module string,
374
+ moduleType modulecapabilities.ModuleType, altNames []string,
375
+ ) bool {
376
+ for _, c := range schema.Classes {
377
+ if p.shouldIncludeClassArgument(c, module, moduleType, altNames) {
378
+ return true
379
+ }
380
+ }
381
+ return false
382
+ }
383
+
384
+ func (p *Provider) shouldAddGenericArgument(class *models.Class, moduleType modulecapabilities.ModuleType) bool {
385
+ if p.isGenerativeModule(moduleType) {
386
+ return true
387
+ }
388
+ return p.hasMultipleVectorizersConfig(class) && p.isVectorizerModule(moduleType)
389
+ }
390
+
391
+ func (p *Provider) hasMultipleVectorizersConfig(class *models.Class) bool {
392
+ return len(class.VectorConfig) > 0
393
+ }
394
+
395
+ func (p *Provider) shouldCrossClassAddGenericArgument(schema *models.Schema, moduleType modulecapabilities.ModuleType) bool {
396
+ for _, c := range schema.Classes {
397
+ if p.shouldAddGenericArgument(c, moduleType) {
398
+ return true
399
+ }
400
+ }
401
+ return false
402
+ }
403
+
404
+ func (p *Provider) getGenericArgument(name, className string,
405
+ argumentType modulecomponents.ArgumentType,
406
+ ) *graphql.ArgumentConfig {
407
+ var nearTextTransformer modulecapabilities.TextTransform
408
+ if name == "nearText" {
409
+ // nearText argument might be exposed with an extension, we need to check
410
+ // if text transformers module is enabled if so then we need to init nearText
411
+ // argument with this extension
412
+ for _, mod := range p.GetAll() {
413
+ if arg, ok := mod.(modulecapabilities.TextTransformers); ok {
414
+ if arg != nil && arg.TextTransformers() != nil {
415
+ nearTextTransformer = arg.TextTransformers()["nearText"]
416
+ break
417
+ }
418
+ }
419
+ }
420
+ }
421
+ return modulecomponents.GetGenericArgument(name, className, argumentType, nearTextTransformer)
422
+ }
423
+
424
+ func (p *Provider) getGenericAdditionalProperty(name string, class *models.Class) *modulecapabilities.AdditionalProperty {
425
+ if p.hasMultipleVectorizersConfig(class) {
426
+ return modulecomponents.GetGenericAdditionalProperty(name, class.Class)
427
+ }
428
+ return nil
429
+ }
430
+
431
+ // GetArguments provides GraphQL Get arguments
432
+ func (p *Provider) GetArguments(class *models.Class) map[string]*graphql.ArgumentConfig {
433
+ arguments := map[string]*graphql.ArgumentConfig{}
434
+ for _, module := range p.GetAll() {
435
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
436
+ if arg, ok := module.(modulecapabilities.GraphQLArguments); ok {
437
+ for name, argument := range arg.Arguments() {
438
+ if argument.GetArgumentsFunction != nil {
439
+ if p.shouldAddGenericArgument(class, module.Type()) {
440
+ if _, ok := arguments[name]; !ok {
441
+ arguments[name] = p.getGenericArgument(name, class.Class, modulecomponents.Get)
442
+ }
443
+ } else {
444
+ arguments[name] = argument.GetArgumentsFunction(class.Class)
445
+ }
446
+ }
447
+ }
448
+ }
449
+ }
450
+ }
451
+
452
+ return arguments
453
+ }
454
+
455
+ func (p *Provider) getModuleAltNames(module modulecapabilities.Module) []string {
456
+ if moduleWithAltNames, ok := module.(modulecapabilities.ModuleHasAltNames); ok {
457
+ return moduleWithAltNames.AltNames()
458
+ }
459
+ return nil
460
+ }
461
+
462
+ func (p *Provider) isModuleNameEqual(module modulecapabilities.Module, targetModule string) bool {
463
+ if module.Name() == targetModule {
464
+ return true
465
+ }
466
+ if altNames := p.getModuleAltNames(module); len(altNames) > 0 {
467
+ if slices.Contains(altNames, targetModule) {
468
+ return true
469
+ }
470
+ }
471
+ return false
472
+ }
473
+
474
+ // AggregateArguments provides GraphQL Aggregate arguments
475
+ func (p *Provider) AggregateArguments(class *models.Class) map[string]*graphql.ArgumentConfig {
476
+ arguments := map[string]*graphql.ArgumentConfig{}
477
+ for _, module := range p.GetAll() {
478
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
479
+ if arg, ok := module.(modulecapabilities.GraphQLArguments); ok {
480
+ for name, argument := range arg.Arguments() {
481
+ if argument.AggregateArgumentsFunction != nil {
482
+ if p.shouldAddGenericArgument(class, module.Type()) {
483
+ if _, ok := arguments[name]; !ok {
484
+ arguments[name] = p.getGenericArgument(name, class.Class, modulecomponents.Aggregate)
485
+ }
486
+ } else {
487
+ arguments[name] = argument.AggregateArgumentsFunction(class.Class)
488
+ }
489
+ }
490
+ }
491
+ }
492
+ }
493
+ }
494
+ return arguments
495
+ }
496
+
497
+ // ExploreArguments provides GraphQL Explore arguments
498
+ func (p *Provider) ExploreArguments(schema *models.Schema) map[string]*graphql.ArgumentConfig {
499
+ arguments := map[string]*graphql.ArgumentConfig{}
500
+ for _, module := range p.GetAll() {
501
+ if p.shouldIncludeArgument(schema, module.Name(), module.Type(), p.getModuleAltNames(module)) {
502
+ if arg, ok := module.(modulecapabilities.GraphQLArguments); ok {
503
+ for name, argument := range arg.Arguments() {
504
+ if argument.ExploreArgumentsFunction != nil {
505
+ if p.shouldCrossClassAddGenericArgument(schema, module.Type()) {
506
+ if _, ok := arguments[name]; !ok {
507
+ arguments[name] = p.getGenericArgument(name, "", modulecomponents.Explore)
508
+ }
509
+ } else {
510
+ arguments[name] = argument.ExploreArgumentsFunction()
511
+ }
512
+ }
513
+ }
514
+ }
515
+ }
516
+ }
517
+ return arguments
518
+ }
519
+
520
+ // CrossClassExtractSearchParams extracts GraphQL arguments from modules without
521
+ // being specific to any one class and it's configuration. This is used in
522
+ // Explore() { } for example
523
+ func (p *Provider) CrossClassExtractSearchParams(arguments map[string]interface{}) map[string]interface{} {
524
+ // explore does not support target vectors
525
+ params, _ := p.extractSearchParams(arguments, nil)
526
+ return params
527
+ }
528
+
529
+ // ExtractSearchParams extracts GraphQL arguments
530
+ func (p *Provider) ExtractSearchParams(arguments map[string]interface{}, className string) (map[string]interface{}, map[string]*dto.TargetCombination) {
531
+ class, err := p.getClass(className)
532
+ if err != nil {
533
+ return map[string]interface{}{}, nil
534
+ }
535
+ return p.extractSearchParams(arguments, class)
536
+ }
537
+
538
+ func (p *Provider) extractSearchParams(arguments map[string]interface{}, class *models.Class) (map[string]interface{}, map[string]*dto.TargetCombination) {
539
+ exractedParams := map[string]interface{}{}
540
+ exractedCombination := map[string]*dto.TargetCombination{}
541
+ for _, module := range p.GetAll() {
542
+ if p.shouldCrossClassIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
543
+ if args, ok := module.(modulecapabilities.GraphQLArguments); ok {
544
+ for paramName, argument := range args.Arguments() {
545
+ if param, ok := arguments[paramName]; ok && argument.ExtractFunction != nil {
546
+ extracted, combination, err := argument.ExtractFunction(param.(map[string]interface{}))
547
+ if err != nil {
548
+ continue
549
+ }
550
+ exractedParams[paramName] = extracted
551
+ exractedCombination[paramName] = combination
552
+ }
553
+ }
554
+ }
555
+ }
556
+ }
557
+ return exractedParams, exractedCombination
558
+ }
559
+
560
+ // CrossClassValidateSearchParam validates module parameters without
561
+ // being specific to any one class and it's configuration. This is used in
562
+ // Explore() { } for example
563
+ func (p *Provider) CrossClassValidateSearchParam(name string, value interface{}) error {
564
+ return p.validateSearchParam(name, value, nil)
565
+ }
566
+
567
+ // ValidateSearchParam validates module parameters
568
+ func (p *Provider) ValidateSearchParam(name string, value interface{}, className string) error {
569
+ class, err := p.getClass(className)
570
+ if err != nil {
571
+ return err
572
+ }
573
+
574
+ return p.validateSearchParam(name, value, class)
575
+ }
576
+
577
+ func (p *Provider) validateSearchParam(name string, value interface{}, class *models.Class) error {
578
+ for _, module := range p.GetAll() {
579
+ if p.shouldCrossClassIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
580
+ if args, ok := module.(modulecapabilities.GraphQLArguments); ok {
581
+ for paramName, argument := range args.Arguments() {
582
+ if paramName == name && argument.ValidateFunction != nil {
583
+ return argument.ValidateFunction(value)
584
+ }
585
+ }
586
+ }
587
+ }
588
+ }
589
+
590
+ return fmt.Errorf("could not vectorize input for collection %v with search-type %v. Make sure a vectorizer module is configured for this collection", class.Class, name)
591
+ }
592
+
593
+ // GetAdditionalFields provides GraphQL Get additional fields
594
+ func (p *Provider) GetAdditionalFields(class *models.Class) map[string]*graphql.Field {
595
+ additionalProperties := map[string]*graphql.Field{}
596
+ additionalGenerativeDefaultProvider := ""
597
+ additionalGenerativeParameters := map[string]modulecapabilities.GenerativeProperty{}
598
+ for _, module := range p.GetAll() {
599
+ if p.isGenerativeModule(module.Type()) {
600
+ if arg, ok := module.(modulecapabilities.AdditionalGenerativeProperties); ok {
601
+ for name, additionalGenerativeParameter := range arg.AdditionalGenerativeProperties() {
602
+ additionalGenerativeParameters[name] = additionalGenerativeParameter
603
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
604
+ additionalGenerativeDefaultProvider = name
605
+ }
606
+ }
607
+ }
608
+ } else if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
609
+ if arg, ok := module.(modulecapabilities.AdditionalProperties); ok {
610
+ for name, additionalProperty := range arg.AdditionalProperties() {
611
+ if additionalProperty.GraphQLFieldFunction != nil {
612
+ if genericAdditionalProperty := p.getGenericAdditionalProperty(name, class); genericAdditionalProperty != nil {
613
+ if genericAdditionalProperty.GraphQLFieldFunction != nil {
614
+ if _, ok := additionalProperties[name]; !ok {
615
+ additionalProperties[name] = genericAdditionalProperty.GraphQLFieldFunction(class.Class)
616
+ }
617
+ }
618
+ } else {
619
+ additionalProperties[name] = additionalProperty.GraphQLFieldFunction(class.Class)
620
+ }
621
+ }
622
+ }
623
+ }
624
+ }
625
+ }
626
+ if len(additionalGenerativeParameters) > 0 {
627
+ if generateFn := modulecomponents.GetGenericGenerateProperty(class.Class, additionalGenerativeParameters, additionalGenerativeDefaultProvider, p.logger); generateFn != nil {
628
+ additionalProperties[modulecomponents.AdditionalPropertyGenerate] = generateFn.GraphQLFieldFunction(class.Class)
629
+ }
630
+ }
631
+ return additionalProperties
632
+ }
633
+
634
+ // ExtractAdditionalField extracts additional properties from given graphql arguments
635
+ func (p *Provider) ExtractAdditionalField(className, name string, params []*ast.Argument) interface{} {
636
+ class, err := p.getClass(className)
637
+ if err != nil {
638
+ return err
639
+ }
640
+ additionalGenerativeDefaultProvider := ""
641
+ additionalGenerativeParameters := map[string]modulecapabilities.GenerativeProperty{}
642
+ for _, module := range p.GetAll() {
643
+ if name == modulecomponents.AdditionalPropertyGenerate {
644
+ if p.isGenerativeModule(module.Type()) {
645
+ if arg, ok := module.(modulecapabilities.AdditionalGenerativeProperties); ok {
646
+ for name, additionalGenerativeParameter := range arg.AdditionalGenerativeProperties() {
647
+ additionalGenerativeParameters[name] = additionalGenerativeParameter
648
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
649
+ additionalGenerativeDefaultProvider = name
650
+ }
651
+ }
652
+ }
653
+ }
654
+ } else if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
655
+ if arg, ok := module.(modulecapabilities.AdditionalProperties); ok {
656
+ if additionalProperties := arg.AdditionalProperties(); len(additionalProperties) > 0 {
657
+ if additionalProperty, ok := additionalProperties[name]; ok {
658
+ return additionalProperty.GraphQLExtractFunction(params, class)
659
+ }
660
+ }
661
+ }
662
+ }
663
+ }
664
+ if name == modulecomponents.AdditionalPropertyGenerate {
665
+ if generateFn := modulecomponents.GetGenericGenerateProperty(class.Class, additionalGenerativeParameters, additionalGenerativeDefaultProvider, p.logger); generateFn != nil {
666
+ return generateFn.GraphQLExtractFunction(params, class)
667
+ }
668
+ }
669
+ return nil
670
+ }
671
+
672
+ // GetObjectAdditionalExtend extends rest api get queries with additional properties
673
+ func (p *Provider) GetObjectAdditionalExtend(ctx context.Context,
674
+ in *search.Result, moduleParams map[string]interface{},
675
+ ) (*search.Result, error) {
676
+ resArray, err := p.additionalExtend(ctx, search.Results{*in}, moduleParams, nil, "ObjectGet", nil)
677
+ if err != nil {
678
+ return nil, err
679
+ }
680
+ return &resArray[0], nil
681
+ }
682
+
683
+ // ListObjectsAdditionalExtend extends rest api list queries with additional properties
684
+ func (p *Provider) ListObjectsAdditionalExtend(ctx context.Context,
685
+ in search.Results, moduleParams map[string]interface{},
686
+ ) (search.Results, error) {
687
+ return p.additionalExtend(ctx, in, moduleParams, nil, "ObjectList", nil)
688
+ }
689
+
690
+ // GetExploreAdditionalExtend extends graphql api get queries with additional properties
691
+ func (p *Provider) GetExploreAdditionalExtend(ctx context.Context, in []search.Result,
692
+ moduleParams map[string]interface{}, searchVector models.Vector,
693
+ argumentModuleParams map[string]interface{},
694
+ ) ([]search.Result, error) {
695
+ return p.additionalExtend(ctx, in, moduleParams, searchVector, "ExploreGet", argumentModuleParams)
696
+ }
697
+
698
+ // ListExploreAdditionalExtend extends graphql api list queries with additional properties
699
+ func (p *Provider) ListExploreAdditionalExtend(ctx context.Context, in []search.Result, moduleParams map[string]interface{}, argumentModuleParams map[string]interface{}) ([]search.Result, error) {
700
+ return p.additionalExtend(ctx, in, moduleParams, nil, "ExploreList", argumentModuleParams)
701
+ }
702
+
703
+ func (p *Provider) additionalExtend(ctx context.Context, in []search.Result, moduleParams map[string]interface{}, searchVector models.Vector, capability string, argumentModuleParams map[string]interface{}) ([]search.Result, error) {
704
+ toBeExtended := in
705
+ if len(toBeExtended) > 0 {
706
+ class, err := p.getClassFromSearchResult(toBeExtended)
707
+ if err != nil {
708
+ return nil, err
709
+ }
710
+
711
+ additionalGenerativeDefaultProvider := ""
712
+ additionalGenerativeParameters := map[string]modulecapabilities.GenerativeProperty{}
713
+ allAdditionalProperties := map[string]modulecapabilities.AdditionalProperty{}
714
+ for _, module := range p.GetAll() {
715
+ if p.isGenerativeModule(module.Type()) {
716
+ if arg, ok := module.(modulecapabilities.AdditionalGenerativeProperties); ok {
717
+ for name, additionalGenerativeParameter := range arg.AdditionalGenerativeProperties() {
718
+ additionalGenerativeParameters[name] = additionalGenerativeParameter
719
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
720
+ additionalGenerativeDefaultProvider = name
721
+ }
722
+ }
723
+ }
724
+ } else if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
725
+ if arg, ok := module.(modulecapabilities.AdditionalProperties); ok {
726
+ if arg != nil && arg.AdditionalProperties() != nil {
727
+ for name, additionalProperty := range arg.AdditionalProperties() {
728
+ allAdditionalProperties[name] = additionalProperty
729
+ }
730
+ }
731
+ }
732
+ }
733
+ }
734
+ if len(additionalGenerativeParameters) > 0 {
735
+ if generateFn := modulecomponents.GetGenericGenerateProperty(class.Class, additionalGenerativeParameters, additionalGenerativeDefaultProvider, p.logger); generateFn != nil {
736
+ allAdditionalProperties[modulecomponents.AdditionalPropertyGenerate] = *generateFn
737
+ }
738
+ }
739
+
740
+ if len(allAdditionalProperties) > 0 {
741
+ if err := p.checkCapabilities(allAdditionalProperties, moduleParams, capability); err != nil {
742
+ return nil, err
743
+ }
744
+ cfg := NewClassBasedModuleConfig(class, "", "", "", &p.cfg)
745
+ for name, value := range moduleParams {
746
+ additionalPropertyFn := p.getAdditionalPropertyFn(allAdditionalProperties[name], capability)
747
+ if additionalPropertyFn != nil && value != nil {
748
+ searchValue := value
749
+ if searchVectorValue, ok := value.(modulecapabilities.AdditionalPropertyWithSearchVector[[]float32]); ok {
750
+ if vec, ok := searchVector.([]float32); ok {
751
+ searchVectorValue.SetSearchVector(vec)
752
+ searchValue = searchVectorValue
753
+ } else {
754
+ return nil, errors.Errorf("extend %s: set search vector unrecongnized type: %T", name, searchVector)
755
+ }
756
+ } else if searchVectorValue, ok := value.(modulecapabilities.AdditionalPropertyWithSearchVector[[][]float32]); ok {
757
+ if vec, ok := searchVector.([][]float32); ok {
758
+ searchVectorValue.SetSearchVector(vec)
759
+ searchValue = searchVectorValue
760
+ } else {
761
+ return nil, errors.Errorf("extend %s: set search multi vector unrecongnized type: %T", name, searchVector)
762
+ }
763
+ }
764
+ resArray, err := additionalPropertyFn(ctx, toBeExtended, searchValue, nil, argumentModuleParams, cfg)
765
+ if err != nil {
766
+ return nil, errors.Errorf("extend %s: %v", name, err)
767
+ }
768
+ toBeExtended = resArray
769
+ } else {
770
+ return nil, errors.Errorf("unknown capability: %s", name)
771
+ }
772
+ }
773
+ }
774
+ }
775
+ return toBeExtended, nil
776
+ }
777
+
778
+ func (p *Provider) getClassFromSearchResult(in []search.Result) (*models.Class, error) {
779
+ if len(in) > 0 {
780
+ return p.getClass(in[0].ClassName)
781
+ }
782
+ return nil, errors.Errorf("unknown class")
783
+ }
784
+
785
+ func (p *Provider) checkCapabilities(additionalProperties map[string]modulecapabilities.AdditionalProperty,
786
+ moduleParams map[string]interface{}, capability string,
787
+ ) error {
788
+ for name := range moduleParams {
789
+ additionalPropertyFn := p.getAdditionalPropertyFn(additionalProperties[name], capability)
790
+ if additionalPropertyFn == nil {
791
+ return errors.Errorf("unknown capability: %s", name)
792
+ }
793
+ }
794
+ return nil
795
+ }
796
+
797
+ func (p *Provider) getAdditionalPropertyFn(
798
+ additionalProperty modulecapabilities.AdditionalProperty,
799
+ capability string,
800
+ ) modulecapabilities.AdditionalPropertyFn {
801
+ switch capability {
802
+ case "ObjectGet":
803
+ return additionalProperty.SearchFunctions.ObjectGet
804
+ case "ObjectList":
805
+ return additionalProperty.SearchFunctions.ObjectList
806
+ case "ExploreGet":
807
+ return additionalProperty.SearchFunctions.ExploreGet
808
+ case "ExploreList":
809
+ return additionalProperty.SearchFunctions.ExploreList
810
+ default:
811
+ return nil
812
+ }
813
+ }
814
+
815
+ // GraphQLAdditionalFieldNames get's all additional field names used in graphql
816
+ func (p *Provider) GraphQLAdditionalFieldNames() []string {
817
+ additionalPropertiesNames := map[string]struct{}{}
818
+ for _, module := range p.GetAll() {
819
+ if arg, ok := module.(modulecapabilities.AdditionalProperties); ok {
820
+ for _, additionalProperty := range arg.AdditionalProperties() {
821
+ for _, gqlName := range additionalProperty.GraphQLNames {
822
+ additionalPropertiesNames[gqlName] = struct{}{}
823
+ }
824
+ }
825
+ } else if _, ok := module.(modulecapabilities.AdditionalGenerativeProperties); ok {
826
+ additionalPropertiesNames[modulecomponents.AdditionalPropertyGenerate] = struct{}{}
827
+ }
828
+ }
829
+ var availableAdditionalPropertiesNames []string
830
+ for gqlName := range additionalPropertiesNames {
831
+ availableAdditionalPropertiesNames = append(availableAdditionalPropertiesNames, gqlName)
832
+ }
833
+ return availableAdditionalPropertiesNames
834
+ }
835
+
836
+ // RestApiAdditionalProperties get's all rest specific additional properties with their
837
+ // default values
838
+ func (p *Provider) RestApiAdditionalProperties(includeProp string, class *models.Class) map[string]interface{} {
839
+ moduleParams := map[string]interface{}{}
840
+ for _, module := range p.GetAll() {
841
+ if p.shouldCrossClassIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
842
+ if arg, ok := module.(modulecapabilities.AdditionalProperties); ok {
843
+ for name, additionalProperty := range arg.AdditionalProperties() {
844
+ for _, includePropName := range additionalProperty.RestNames {
845
+ if includePropName == includeProp && moduleParams[name] == nil {
846
+ moduleParams[name] = additionalProperty.DefaultValue
847
+ }
848
+ }
849
+ }
850
+ }
851
+ }
852
+ }
853
+ return moduleParams
854
+ }
855
+
856
+ func (p *Provider) TargetsFromSearchParam(className string, params interface{}) ([]string, error) {
857
+ class, err := p.getClass(className)
858
+ if err != nil {
859
+ return nil, err
860
+ }
861
+ targetVectors, err := p.getTargetVector(class, params)
862
+ if err != nil {
863
+ return nil, err
864
+ }
865
+
866
+ return targetVectors, nil
867
+ }
868
+
869
+ func (p *Provider) IsTargetVectorMultiVector(className, targetVector string) (bool, error) {
870
+ class, err := p.getClass(className)
871
+ if err != nil {
872
+ return false, err
873
+ }
874
+ targetModule := p.getModuleNameForTargetVector(class, targetVector)
875
+ return p.IsMultiVector(targetModule), nil
876
+ }
877
+
878
+ // VectorFromSearchParam gets a vector for a given argument. This is used in
879
+ // Get { Class() } for example
880
+ func (p *Provider) VectorFromSearchParam(ctx context.Context, className, targetVector, tenant, param string, params interface{},
881
+ findVectorFn modulecapabilities.FindVectorFn[[]float32],
882
+ ) ([]float32, error) {
883
+ class, err := p.getClass(className)
884
+ if err != nil {
885
+ return nil, err
886
+ }
887
+
888
+ targetModule := p.getModuleNameForTargetVector(class, targetVector)
889
+
890
+ for _, mod := range p.GetAll() {
891
+ if found, vector, err := vectorFromSearchParam(ctx, class, mod, targetModule, targetVector, tenant, param, params, findVectorFn, p.isModuleNameEqual, &p.cfg); found {
892
+ return vector, err
893
+ }
894
+ }
895
+
896
+ return nil, fmt.Errorf("could not vectorize input for collection %v with search-type %v, targetVector %v and parameters %v. Make sure a vectorizer module is configured for this class", className, param, targetVector, params)
897
+ }
898
+
899
+ // MultiVectorFromSearchParam gets a multi vector for a given argument. This is used in
900
+ // Get { Class() } for example
901
+ func (p *Provider) MultiVectorFromSearchParam(ctx context.Context, className, targetVector, tenant, param string, params interface{},
902
+ findVectorFn modulecapabilities.FindVectorFn[[][]float32],
903
+ ) ([][]float32, error) {
904
+ class, err := p.getClass(className)
905
+ if err != nil {
906
+ return nil, err
907
+ }
908
+
909
+ targetModule := p.getModuleNameForTargetVector(class, targetVector)
910
+
911
+ for _, mod := range p.GetAll() {
912
+ if found, vector, err := vectorFromSearchParam(ctx, class, mod, targetModule, targetVector, tenant, param, params, findVectorFn, p.isModuleNameEqual, &p.cfg); found {
913
+ return vector, err
914
+ }
915
+ }
916
+
917
+ return nil, fmt.Errorf("could not vectorize input for collection %v with search-type %v, targetVector %v and parameters %v. Make sure a vectorizer module is configured for this class", className, param, targetVector, params)
918
+ }
919
+
920
+ // CrossClassVectorFromSearchParam gets a vector for a given argument without
921
+ // being specific to any one class and it's configuration. This is used in
922
+ // Explore() { } for example
923
+ func (p *Provider) CrossClassVectorFromSearchParam(ctx context.Context,
924
+ param string, params interface{},
925
+ findVectorFn modulecapabilities.FindVectorFn[[]float32],
926
+ ) ([]float32, string, error) {
927
+ for _, mod := range p.GetAll() {
928
+ if found, vector, targetVector, err := crossClassVectorFromSearchParam(ctx, mod, param, params, findVectorFn, p.getTargetVector, p.cfg); found {
929
+ return vector, targetVector, err
930
+ }
931
+ }
932
+
933
+ return nil, "", fmt.Errorf("could not vectorize input for Explore with search-type %v and parameters %v. Make sure a vectorizer module is configured", param, params)
934
+ }
935
+
936
+ // MultiCrossClassVectorFromSearchParam gets a multi vector for a given argument without
937
+ // being specific to any one class and it's configuration. This is used in
938
+ // Explore() { } for example
939
+ func (p *Provider) MultiCrossClassVectorFromSearchParam(ctx context.Context,
940
+ param string, params interface{},
941
+ findVectorFn modulecapabilities.FindVectorFn[[][]float32],
942
+ ) ([][]float32, string, error) {
943
+ for _, mod := range p.GetAll() {
944
+ if found, vector, targetVector, err := crossClassVectorFromSearchParam(ctx, mod, param, params, findVectorFn, p.getTargetVector, p.cfg); found {
945
+ return vector, targetVector, err
946
+ }
947
+ }
948
+
949
+ return nil, "", fmt.Errorf("could not vectorize input for Explore with search-type %v and parameters %v. Make sure a vectorizer module is configured", param, params)
950
+ }
951
+
952
+ func (p *Provider) getTargetVector(class *models.Class, params interface{}) ([]string, error) {
953
+ if nearParam, ok := params.(modulecapabilities.NearParam); ok && len(nearParam.GetTargetVectors()) >= 1 {
954
+ return nearParam.GetTargetVectors(), nil
955
+ }
956
+ if class != nil {
957
+ if modelsext.ClassHasLegacyVectorIndex(class) {
958
+ return []string{""}, nil
959
+ }
960
+
961
+ if len(class.VectorConfig) > 1 {
962
+ return nil, fmt.Errorf("multiple vectorizers configuration found, please specify target vector name")
963
+ }
964
+
965
+ if len(class.VectorConfig) == 1 {
966
+ for name := range class.VectorConfig {
967
+ return []string{name}, nil
968
+ }
969
+ }
970
+ }
971
+ return []string{""}, nil
972
+ }
973
+
974
+ func (p *Provider) getModuleNameForTargetVector(class *models.Class, targetVector string) string {
975
+ if len(class.VectorConfig) > 0 {
976
+ if vectorConfig, ok := class.VectorConfig[targetVector]; ok {
977
+ if vectorizer, ok := vectorConfig.Vectorizer.(map[string]interface{}); ok && len(vectorizer) == 1 {
978
+ for moduleName := range vectorizer {
979
+ return moduleName
980
+ }
981
+ }
982
+ }
983
+ }
984
+ return class.Vectorizer
985
+ }
986
+
987
+ func (p *Provider) VectorFromInput(ctx context.Context,
988
+ className, input, targetVector string,
989
+ ) ([]float32, error) {
990
+ class, err := p.getClass(className)
991
+ if err != nil {
992
+ return nil, err
993
+ }
994
+ targetModule := p.getModuleNameForTargetVector(class, targetVector)
995
+
996
+ for _, mod := range p.GetAll() {
997
+ if p.isModuleNameEqual(mod, targetModule) {
998
+ if p.shouldIncludeClassArgument(class, mod.Name(), mod.Type(), p.getModuleAltNames(mod)) {
999
+ if found, vector, err := vectorFromInput[[]float32](ctx, mod, class, input, targetVector, &p.cfg); found {
1000
+ return vector, err
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ return nil, fmt.Errorf("VectorFromInput was called without vectorizer on class %v for input %v", className, input)
1007
+ }
1008
+
1009
+ func (p *Provider) MultiVectorFromInput(ctx context.Context,
1010
+ className, input, targetVector string,
1011
+ ) ([][]float32, error) {
1012
+ class, err := p.getClass(className)
1013
+ if err != nil {
1014
+ return nil, err
1015
+ }
1016
+ targetModule := p.getModuleNameForTargetVector(class, targetVector)
1017
+
1018
+ for _, mod := range p.GetAll() {
1019
+ if p.isModuleNameEqual(mod, targetModule) {
1020
+ if p.shouldIncludeClassArgument(class, mod.Name(), mod.Type(), p.getModuleAltNames(mod)) {
1021
+ if found, vector, err := vectorFromInput[[][]float32](ctx, mod, class, input, targetVector, &p.cfg); found {
1022
+ return vector, err
1023
+ }
1024
+ }
1025
+ }
1026
+ }
1027
+
1028
+ return nil, fmt.Errorf("MultiVectorFromInput was called without vectorizer on class %v for input %v", className, input)
1029
+ }
1030
+
1031
+ // ParseClassifierSettings parses and adds classifier specific settings
1032
+ func (p *Provider) ParseClassifierSettings(name string,
1033
+ params *models.Classification,
1034
+ ) error {
1035
+ class, err := p.getClass(params.Class)
1036
+ if err != nil {
1037
+ return err
1038
+ }
1039
+ for _, module := range p.GetAll() {
1040
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
1041
+ if c, ok := module.(modulecapabilities.ClassificationProvider); ok {
1042
+ for _, classifier := range c.Classifiers() {
1043
+ if classifier != nil && classifier.Name() == name {
1044
+ return classifier.ParseClassifierSettings(params)
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ }
1050
+ return nil
1051
+ }
1052
+
1053
+ // GetClassificationFn returns given module's classification
1054
+ func (p *Provider) GetClassificationFn(className, name string,
1055
+ params modulecapabilities.ClassifyParams,
1056
+ ) (modulecapabilities.ClassifyItemFn, error) {
1057
+ class, err := p.getClass(className)
1058
+ if err != nil {
1059
+ return nil, err
1060
+ }
1061
+ for _, module := range p.GetAll() {
1062
+ if p.shouldIncludeClassArgument(class, module.Name(), module.Type(), p.getModuleAltNames(module)) {
1063
+ if c, ok := module.(modulecapabilities.ClassificationProvider); ok {
1064
+ for _, classifier := range c.Classifiers() {
1065
+ if classifier != nil && classifier.Name() == name {
1066
+ return classifier.ClassifyFn(params)
1067
+ }
1068
+ }
1069
+ }
1070
+ }
1071
+ }
1072
+ return nil, errors.Errorf("classifier %s not found", name)
1073
+ }
1074
+
1075
+ // GetMeta returns meta information about modules
1076
+ func (p *Provider) GetMeta() (map[string]interface{}, error) {
1077
+ metaInfos := map[string]interface{}{}
1078
+ for _, module := range p.GetAll() {
1079
+ if c, ok := module.(modulecapabilities.MetaProvider); ok {
1080
+ meta, err := c.MetaInfo()
1081
+ if err != nil {
1082
+ metaInfos[module.Name()] = map[string]interface{}{
1083
+ "error": err.Error(),
1084
+ }
1085
+ } else {
1086
+ metaInfos[module.Name()] = meta
1087
+ }
1088
+ }
1089
+ }
1090
+ return metaInfos, nil
1091
+ }
1092
+
1093
+ func (p *Provider) getClass(className string) (*models.Class, error) {
1094
+ class := p.schemaGetter.ReadOnlyClass(className)
1095
+ if class == nil {
1096
+ return nil, errors.Errorf("class %q not found in schema", className)
1097
+ }
1098
+ return class, nil
1099
+ }
1100
+
1101
+ func (p *Provider) HasMultipleVectorizers() bool {
1102
+ return p.hasMultipleVectorizers
1103
+ }
1104
+
1105
+ func (p *Provider) BackupBackend(backend string) (modulecapabilities.BackupBackend, error) {
1106
+ module := p.GetByName(backend)
1107
+ if module != nil {
1108
+ if module.Type() == modulecapabilities.Backup {
1109
+ module_backend, ok := module.(modulecapabilities.BackupBackend)
1110
+ if ok {
1111
+ return module_backend, nil
1112
+ } else {
1113
+ return nil, errors.Errorf("backup: %s is not a backup backend (actual type: %T)", backend, module)
1114
+ }
1115
+ } else {
1116
+ return nil, errors.Errorf("backup: %s is not a backup backend type", backend)
1117
+ }
1118
+ }
1119
+ return nil, errors.Errorf("backup: %s not found", backend)
1120
+ }
1121
+
1122
+ func (p *Provider) OffloadBackend(backend string) (modulecapabilities.OffloadCloud, bool) {
1123
+ if module := p.GetByName(backend); module != nil {
1124
+ if module.Type() == modulecapabilities.Offload {
1125
+ if backend, ok := module.(modulecapabilities.OffloadCloud); ok {
1126
+ return backend, true
1127
+ }
1128
+ }
1129
+ }
1130
+ return nil, false
1131
+ }
1132
+
1133
+ func (p *Provider) EnabledBackupBackends() []modulecapabilities.BackupBackend {
1134
+ var backends []modulecapabilities.BackupBackend
1135
+ for _, mod := range p.GetAll() {
1136
+ if backend, ok := mod.(modulecapabilities.BackupBackend); ok &&
1137
+ mod.Type() == modulecapabilities.Backup {
1138
+ backends = append(backends, backend)
1139
+ }
1140
+ }
1141
+ return backends
1142
+ }
1143
+
1144
+ func (p *Provider) UsageEnabled() bool {
1145
+ for _, module := range p.GetAll() {
1146
+ if module.Type() == modulecapabilities.Usage {
1147
+ return true
1148
+ }
1149
+ }
1150
+ return false
1151
+ }
platform/dbops/binaries/weaviate-src/usecases/modules/modules_generic.go ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+
17
+ "github.com/pkg/errors"
18
+ "github.com/weaviate/weaviate/entities/dto"
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
21
+ "github.com/weaviate/weaviate/usecases/config"
22
+ )
23
+
24
+ func vectorFromSearchParam[T dto.Embedding](
25
+ ctx context.Context,
26
+ class *models.Class,
27
+ mod modulecapabilities.Module,
28
+ targetModule, targetVector, tenant, param string,
29
+ params interface{},
30
+ findVectorFn modulecapabilities.FindVectorFn[T],
31
+ isModuleNameEqualFn func(module modulecapabilities.Module, targetModule string) bool,
32
+ dbConfig *config.Config,
33
+ ) (bool, T, error) {
34
+ var moduleName string
35
+ var vectorSearches map[string]modulecapabilities.VectorForParams[T]
36
+
37
+ if searcher, ok := mod.(modulecapabilities.Searcher[T]); ok {
38
+ if isModuleNameEqualFn(mod, targetModule) {
39
+ moduleName = mod.Name()
40
+ vectorSearches = searcher.VectorSearches()
41
+ }
42
+ } else if searchers, ok := mod.(modulecapabilities.DependencySearcher[T]); ok {
43
+ if dependencySearchers := searchers.VectorSearches(); dependencySearchers != nil {
44
+ moduleName = targetModule
45
+ vectorSearches = dependencySearchers[targetModule]
46
+ }
47
+ }
48
+ if vectorSearches != nil {
49
+ if searchVectorFn := vectorSearches[param]; searchVectorFn != nil {
50
+ cfg := NewClassBasedModuleConfig(class, moduleName, tenant, targetVector, dbConfig)
51
+ vector, err := searchVectorFn.VectorForParams(ctx, params, class.Class, findVectorFn, cfg)
52
+ if err != nil {
53
+ return true, nil, errors.Errorf("vectorize params: %v", err)
54
+ }
55
+ return true, vector, nil
56
+ }
57
+ }
58
+
59
+ return false, nil, nil
60
+ }
61
+
62
+ func crossClassVectorFromSearchParam[T dto.Embedding](
63
+ ctx context.Context,
64
+ mod modulecapabilities.Module,
65
+ param string,
66
+ params interface{},
67
+ findVectorFn modulecapabilities.FindVectorFn[T],
68
+ getTargetVectorFn func(class *models.Class, params interface{}) ([]string, error),
69
+ dbConfig config.Config,
70
+ ) (bool, T, string, error) {
71
+ if searcher, ok := mod.(modulecapabilities.Searcher[T]); ok {
72
+ if vectorSearches := searcher.VectorSearches(); vectorSearches != nil {
73
+ if searchVectorFn := vectorSearches[param]; searchVectorFn != nil {
74
+ cfg := NewCrossClassModuleConfig()
75
+ vector, err := searchVectorFn.VectorForParams(ctx, params, "", findVectorFn, cfg)
76
+ if err != nil {
77
+ return true, nil, "", errors.Errorf("vectorize params: %v", err)
78
+ }
79
+ targetVector, err := getTargetVectorFn(nil, params)
80
+ if err != nil {
81
+ return true, nil, "", errors.Errorf("get target vector: %v", err)
82
+ }
83
+ if len(targetVector) > 0 {
84
+ return true, vector, targetVector[0], nil
85
+ }
86
+ return true, vector, "", nil
87
+ }
88
+ }
89
+ }
90
+
91
+ return false, nil, "", nil
92
+ }
93
+
94
+ func vectorFromInput[T dto.Embedding](
95
+ ctx context.Context,
96
+ mod modulecapabilities.Module,
97
+ class *models.Class,
98
+ input, targetVector string,
99
+ dbConfig *config.Config,
100
+ ) (bool, T, error) {
101
+ if vectorizer, ok := mod.(modulecapabilities.InputVectorizer[T]); ok {
102
+ // does not access any objects, therefore tenant is irrelevant
103
+ cfg := NewClassBasedModuleConfig(class, mod.Name(), "", targetVector, dbConfig)
104
+ vector, err := vectorizer.VectorizeInput(ctx, input, cfg)
105
+ return true, vector, err
106
+ }
107
+ return false, nil, nil
108
+ }
platform/dbops/binaries/weaviate-src/usecases/modules/modules_test.go ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "io"
18
+ "testing"
19
+
20
+ "github.com/sirupsen/logrus/hooks/test"
21
+ "github.com/stretchr/testify/assert"
22
+ "github.com/tailor-inc/graphql"
23
+
24
+ "github.com/weaviate/weaviate/entities/backup"
25
+ "github.com/weaviate/weaviate/entities/dto"
26
+ "github.com/weaviate/weaviate/entities/models"
27
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
28
+ "github.com/weaviate/weaviate/entities/moduletools"
29
+ enitiesSchema "github.com/weaviate/weaviate/entities/schema"
30
+ ubackup "github.com/weaviate/weaviate/usecases/backup"
31
+ "github.com/weaviate/weaviate/usecases/config"
32
+ )
33
+
34
+ func TestModulesProvider(t *testing.T) {
35
+ t.Run("should register simple module", func(t *testing.T) {
36
+ // given
37
+ logger, _ := test.NewNullLogger()
38
+ modulesProvider := NewProvider(logger, config.Config{})
39
+ class := &models.Class{
40
+ Class: "ClassOne",
41
+ Vectorizer: "mod1",
42
+ }
43
+ schema := &models.Schema{
44
+ Classes: []*models.Class{class},
45
+ }
46
+ schemaGetter := getFakeSchemaGetter()
47
+ modulesProvider.SetSchemaGetter(schemaGetter)
48
+
49
+ params := map[string]interface{}{}
50
+ params["nearArgumentSomeParam"] = string("doesn't matter here")
51
+ arguments := map[string]interface{}{}
52
+ arguments["nearArgument"] = params
53
+
54
+ // when
55
+ modulesProvider.Register(newGraphQLModule("mod1").withArg("nearArgument"))
56
+ err := modulesProvider.Init(context.Background(), nil, logger)
57
+ registered := modulesProvider.GetAll()
58
+ getArgs := modulesProvider.GetArguments(class)
59
+ exploreArgs := modulesProvider.ExploreArguments(schema)
60
+ extractedArgs, _ := modulesProvider.ExtractSearchParams(arguments, class.Class)
61
+
62
+ // then
63
+ mod1 := registered[0]
64
+ assert.Nil(t, err)
65
+ assert.Equal(t, "mod1", mod1.Name())
66
+ assert.NotNil(t, getArgs["nearArgument"])
67
+ assert.NotNil(t, exploreArgs["nearArgument"])
68
+ assert.NotNil(t, extractedArgs["nearArgument"])
69
+ })
70
+
71
+ t.Run("should not register modules providing the same search param", func(t *testing.T) {
72
+ // given
73
+ logger, _ := test.NewNullLogger()
74
+ modulesProvider := NewProvider(logger, config.Config{})
75
+ schemaGetter := getFakeSchemaGetter()
76
+ modulesProvider.SetSchemaGetter(schemaGetter)
77
+
78
+ // when
79
+ modulesProvider.Register(newGraphQLModule("mod1").withArg("nearArgument"))
80
+ modulesProvider.Register(newGraphQLModule("mod2").withArg("nearArgument"))
81
+ err := modulesProvider.Init(context.Background(), nil, logger)
82
+
83
+ // then
84
+ assert.Nil(t, err)
85
+ })
86
+
87
+ t.Run("should not register modules providing internal search param", func(t *testing.T) {
88
+ // given
89
+ logger, _ := test.NewNullLogger()
90
+ modulesProvider := NewProvider(logger, config.Config{})
91
+ schemaGetter := getFakeSchemaGetter()
92
+ modulesProvider.SetSchemaGetter(schemaGetter)
93
+
94
+ // when
95
+ modulesProvider.Register(newGraphQLModule("mod1").withArg("nearArgument"))
96
+ modulesProvider.Register(newGraphQLModule("mod3").
97
+ withExtractFn("limit").
98
+ withExtractFn("where").
99
+ withExtractFn("nearVector").
100
+ withExtractFn("nearObject").
101
+ withExtractFn("group"),
102
+ )
103
+ err := modulesProvider.Init(context.Background(), nil, logger)
104
+
105
+ // then
106
+ assert.NotNil(t, err)
107
+ assert.Contains(t, err.Error(), "nearObject conflicts with weaviate's internal searcher in modules: [mod3]")
108
+ assert.Contains(t, err.Error(), "nearVector conflicts with weaviate's internal searcher in modules: [mod3]")
109
+ assert.Contains(t, err.Error(), "where conflicts with weaviate's internal searcher in modules: [mod3]")
110
+ assert.Contains(t, err.Error(), "group conflicts with weaviate's internal searcher in modules: [mod3]")
111
+ assert.Contains(t, err.Error(), "limit conflicts with weaviate's internal searcher in modules: [mod3]")
112
+ })
113
+
114
+ t.Run("should not register modules providing faulty params", func(t *testing.T) {
115
+ // given
116
+ logger, _ := test.NewNullLogger()
117
+ modulesProvider := NewProvider(logger, config.Config{})
118
+ schemaGetter := getFakeSchemaGetter()
119
+ modulesProvider.SetSchemaGetter(schemaGetter)
120
+
121
+ // when
122
+ modulesProvider.Register(newGraphQLModule("mod1").withArg("nearArgument"))
123
+ modulesProvider.Register(newGraphQLModule("mod2").withArg("nearArgument"))
124
+ modulesProvider.Register(newGraphQLModule("mod3").
125
+ withExtractFn("limit").
126
+ withExtractFn("where").
127
+ withExtractFn("nearVector").
128
+ withExtractFn("nearObject").
129
+ withExtractFn("group"),
130
+ )
131
+ err := modulesProvider.Init(context.Background(), nil, logger)
132
+
133
+ // then
134
+ assert.NotNil(t, err)
135
+ assert.Contains(t, err.Error(), "nearObject conflicts with weaviate's internal searcher in modules: [mod3]")
136
+ assert.Contains(t, err.Error(), "nearVector conflicts with weaviate's internal searcher in modules: [mod3]")
137
+ assert.Contains(t, err.Error(), "where conflicts with weaviate's internal searcher in modules: [mod3]")
138
+ assert.Contains(t, err.Error(), "group conflicts with weaviate's internal searcher in modules: [mod3]")
139
+ assert.Contains(t, err.Error(), "limit conflicts with weaviate's internal searcher in modules: [mod3]")
140
+ })
141
+
142
+ t.Run("should register simple additional property module", func(t *testing.T) {
143
+ // given
144
+ logger, _ := test.NewNullLogger()
145
+ modulesProvider := NewProvider(logger, config.Config{})
146
+ class := &models.Class{
147
+ Class: "ClassOne",
148
+ Vectorizer: "mod1",
149
+ }
150
+ schema := &models.Schema{
151
+ Classes: []*models.Class{class},
152
+ }
153
+ schemaGetter := getFakeSchemaGetter()
154
+ modulesProvider.SetSchemaGetter(schemaGetter)
155
+
156
+ params := map[string]interface{}{}
157
+ params["nearArgumentSomeParam"] = string("doesn't matter here")
158
+ arguments := map[string]interface{}{}
159
+ arguments["nearArgument"] = params
160
+
161
+ // when
162
+ modulesProvider.Register(newGraphQLAdditionalModule("mod1").
163
+ withGraphQLArg("featureProjection", []string{"featureProjection"}).
164
+ withGraphQLArg("interpretation", []string{"interpretation"}).
165
+ withRestApiArg("featureProjection", []string{"featureProjection", "fp", "f-p"}).
166
+ withRestApiArg("interpretation", []string{"interpretation"}).
167
+ withArg("nearArgument"),
168
+ )
169
+ err := modulesProvider.Init(context.Background(), nil, logger)
170
+ registered := modulesProvider.GetAll()
171
+ getArgs := modulesProvider.GetArguments(class)
172
+ exploreArgs := modulesProvider.ExploreArguments(schema)
173
+ extractedArgs, _ := modulesProvider.ExtractSearchParams(arguments, class.Class)
174
+ restApiFPArgs := modulesProvider.RestApiAdditionalProperties("featureProjection", class)
175
+ restApiInterpretationArgs := modulesProvider.RestApiAdditionalProperties("interpretation", class)
176
+ graphQLArgs := modulesProvider.GraphQLAdditionalFieldNames()
177
+
178
+ // then
179
+ mod1 := registered[0]
180
+ assert.Nil(t, err)
181
+ assert.Equal(t, "mod1", mod1.Name())
182
+ assert.NotNil(t, getArgs["nearArgument"])
183
+ assert.NotNil(t, exploreArgs["nearArgument"])
184
+ assert.NotNil(t, extractedArgs["nearArgument"])
185
+ assert.NotNil(t, restApiFPArgs["featureProjection"])
186
+ assert.NotNil(t, restApiInterpretationArgs["interpretation"])
187
+ assert.Contains(t, graphQLArgs, "featureProjection")
188
+ assert.Contains(t, graphQLArgs, "interpretation")
189
+ })
190
+
191
+ t.Run("should not register additional property modules providing the same params", func(t *testing.T) {
192
+ // given
193
+ logger, _ := test.NewNullLogger()
194
+ modulesProvider := NewProvider(logger, config.Config{})
195
+ schemaGetter := getFakeSchemaGetter()
196
+ modulesProvider.SetSchemaGetter(schemaGetter)
197
+
198
+ // when
199
+ modulesProvider.Register(newGraphQLAdditionalModule("mod1").
200
+ withArg("nearArgument").
201
+ withGraphQLArg("featureProjection", []string{"featureProjection"}).
202
+ withRestApiArg("featureProjection", []string{"featureProjection", "fp", "f-p"}),
203
+ )
204
+ modulesProvider.Register(newGraphQLAdditionalModule("mod2").
205
+ withArg("nearArgument").
206
+ withGraphQLArg("featureProjection", []string{"featureProjection"}).
207
+ withRestApiArg("featureProjection", []string{"featureProjection", "fp", "f-p"}),
208
+ )
209
+ err := modulesProvider.Init(context.Background(), nil, logger)
210
+
211
+ // then
212
+ assert.Nil(t, err)
213
+ })
214
+
215
+ t.Run("should not register additional property modules providing internal search param", func(t *testing.T) {
216
+ // given
217
+ logger, _ := test.NewNullLogger()
218
+ modulesProvider := NewProvider(logger, config.Config{})
219
+ schemaGetter := getFakeSchemaGetter()
220
+ modulesProvider.SetSchemaGetter(schemaGetter)
221
+
222
+ // when
223
+ modulesProvider.Register(newGraphQLAdditionalModule("mod1").withArg("nearArgument"))
224
+ modulesProvider.Register(newGraphQLAdditionalModule("mod3").
225
+ withExtractFn("limit").
226
+ withExtractFn("where").
227
+ withExtractFn("nearVector").
228
+ withExtractFn("nearObject").
229
+ withExtractFn("group").
230
+ withExtractFn("groupBy").
231
+ withExtractFn("hybrid").
232
+ withExtractFn("bm25").
233
+ withExtractFn("offset").
234
+ withExtractFn("after").
235
+ withGraphQLArg("group", []string{"group"}).
236
+ withGraphQLArg("classification", []string{"classification"}).
237
+ withRestApiArg("classification", []string{"classification"}).
238
+ withGraphQLArg("certainty", []string{"certainty"}).
239
+ withRestApiArg("certainty", []string{"certainty"}).
240
+ withGraphQLArg("distance", []string{"distance"}).
241
+ withRestApiArg("distance", []string{"distance"}).
242
+ withGraphQLArg("id", []string{"id"}).
243
+ withRestApiArg("id", []string{"id"}),
244
+ )
245
+ err := modulesProvider.Init(context.Background(), nil, logger)
246
+
247
+ // then
248
+ assert.NotNil(t, err)
249
+ assert.Contains(t, err.Error(), "searcher: nearObject conflicts with weaviate's internal searcher in modules: [mod3]")
250
+ assert.Contains(t, err.Error(), "searcher: nearVector conflicts with weaviate's internal searcher in modules: [mod3]")
251
+ assert.Contains(t, err.Error(), "searcher: where conflicts with weaviate's internal searcher in modules: [mod3]")
252
+ assert.Contains(t, err.Error(), "searcher: group conflicts with weaviate's internal searcher in modules: [mod3]")
253
+ assert.Contains(t, err.Error(), "searcher: groupBy conflicts with weaviate's internal searcher in modules: [mod3]")
254
+ assert.Contains(t, err.Error(), "searcher: hybrid conflicts with weaviate's internal searcher in modules: [mod3]")
255
+ assert.Contains(t, err.Error(), "searcher: bm25 conflicts with weaviate's internal searcher in modules: [mod3]")
256
+ assert.Contains(t, err.Error(), "searcher: limit conflicts with weaviate's internal searcher in modules: [mod3]")
257
+ assert.Contains(t, err.Error(), "searcher: offset conflicts with weaviate's internal searcher in modules: [mod3]")
258
+ assert.Contains(t, err.Error(), "searcher: after conflicts with weaviate's internal searcher in modules: [mod3]")
259
+ assert.Contains(t, err.Error(), "rest api additional property: classification conflicts with weaviate's internal searcher in modules: [mod3]")
260
+ assert.Contains(t, err.Error(), "rest api additional property: certainty conflicts with weaviate's internal searcher in modules: [mod3]")
261
+ assert.Contains(t, err.Error(), "rest api additional property: distance conflicts with weaviate's internal searcher in modules: [mod3]")
262
+ assert.Contains(t, err.Error(), "rest api additional property: id conflicts with weaviate's internal searcher in modules: [mod3]")
263
+ assert.Contains(t, err.Error(), "graphql additional property: classification conflicts with weaviate's internal searcher in modules: [mod3]")
264
+ assert.Contains(t, err.Error(), "graphql additional property: certainty conflicts with weaviate's internal searcher in modules: [mod3]")
265
+ assert.Contains(t, err.Error(), "graphql additional property: distance conflicts with weaviate's internal searcher in modules: [mod3]")
266
+ assert.Contains(t, err.Error(), "graphql additional property: id conflicts with weaviate's internal searcher in modules: [mod3]")
267
+ assert.Contains(t, err.Error(), "graphql additional property: group conflicts with weaviate's internal searcher in modules: [mod3]")
268
+ })
269
+
270
+ t.Run("should not register additional property modules providing faulty params", func(t *testing.T) {
271
+ // given
272
+ logger, _ := test.NewNullLogger()
273
+ modulesProvider := NewProvider(logger, config.Config{})
274
+ schemaGetter := getFakeSchemaGetter()
275
+ modulesProvider.SetSchemaGetter(schemaGetter)
276
+
277
+ // when
278
+ modulesProvider.Register(newGraphQLAdditionalModule("mod1").
279
+ withArg("nearArgument").
280
+ withGraphQLArg("semanticPath", []string{"semanticPath"}).
281
+ withRestApiArg("featureProjection", []string{"featureProjection", "fp", "f-p"}),
282
+ )
283
+ modulesProvider.Register(newGraphQLAdditionalModule("mod2").
284
+ withArg("nearArgument").
285
+ withGraphQLArg("semanticPath", []string{"semanticPath"}).
286
+ withRestApiArg("featureProjection", []string{"featureProjection", "fp", "f-p"}),
287
+ )
288
+ modulesProvider.Register(newGraphQLModule("mod3").
289
+ withExtractFn("limit").
290
+ withExtractFn("where").
291
+ withExtractFn("nearVector").
292
+ withExtractFn("nearObject").
293
+ withExtractFn("group"),
294
+ )
295
+ modulesProvider.Register(newGraphQLAdditionalModule("mod4").
296
+ withGraphQLArg("classification", []string{"classification"}).
297
+ withRestApiArg("classification", []string{"classification"}).
298
+ withGraphQLArg("certainty", []string{"certainty"}).
299
+ withRestApiArg("certainty", []string{"certainty"}).
300
+ withGraphQLArg("id", []string{"id"}).
301
+ withRestApiArg("id", []string{"id"}),
302
+ )
303
+ err := modulesProvider.Init(context.Background(), nil, logger)
304
+
305
+ // then
306
+ assert.NotNil(t, err)
307
+ assert.Contains(t, err.Error(), "searcher: nearObject conflicts with weaviate's internal searcher in modules: [mod3]")
308
+ assert.Contains(t, err.Error(), "searcher: nearVector conflicts with weaviate's internal searcher in modules: [mod3]")
309
+ assert.Contains(t, err.Error(), "searcher: where conflicts with weaviate's internal searcher in modules: [mod3]")
310
+ assert.Contains(t, err.Error(), "searcher: group conflicts with weaviate's internal searcher in modules: [mod3]")
311
+ assert.Contains(t, err.Error(), "searcher: limit conflicts with weaviate's internal searcher in modules: [mod3]")
312
+ assert.Contains(t, err.Error(), "rest api additional property: classification conflicts with weaviate's internal searcher in modules: [mod4]")
313
+ assert.Contains(t, err.Error(), "rest api additional property: certainty conflicts with weaviate's internal searcher in modules: [mod4]")
314
+ assert.Contains(t, err.Error(), "rest api additional property: id conflicts with weaviate's internal searcher in modules: [mod4]")
315
+ assert.Contains(t, err.Error(), "graphql additional property: classification conflicts with weaviate's internal searcher in modules: [mod4]")
316
+ assert.Contains(t, err.Error(), "graphql additional property: certainty conflicts with weaviate's internal searcher in modules: [mod4]")
317
+ assert.Contains(t, err.Error(), "graphql additional property: id conflicts with weaviate's internal searcher in modules: [mod4]")
318
+ })
319
+
320
+ t.Run("should register module with alt names", func(t *testing.T) {
321
+ logger, _ := test.NewNullLogger()
322
+ module := &dummyBackupModuleWithAltNames{}
323
+ modulesProvider := NewProvider(logger, config.Config{})
324
+ modulesProvider.Register(module)
325
+
326
+ modByName := modulesProvider.GetByName("SomeBackend")
327
+ modByAltName1 := modulesProvider.GetByName("AltBackendName")
328
+ modByAltName2 := modulesProvider.GetByName("YetAnotherBackendName")
329
+ modMissing := modulesProvider.GetByName("DoesNotExist")
330
+
331
+ assert.NotNil(t, modByName)
332
+ assert.NotNil(t, modByAltName1)
333
+ assert.NotNil(t, modByAltName2)
334
+ assert.Nil(t, modMissing)
335
+ })
336
+
337
+ t.Run("should provide backup backend", func(t *testing.T) {
338
+ logger, _ := test.NewNullLogger()
339
+ module := &dummyBackupModuleWithAltNames{}
340
+ modulesProvider := NewProvider(logger, config.Config{})
341
+ modulesProvider.Register(module)
342
+
343
+ provider, ok := interface{}(modulesProvider).(ubackup.BackupBackendProvider)
344
+ assert.True(t, ok)
345
+
346
+ fmt.Printf("provider: %v\n", provider)
347
+
348
+ backendByName, err1 := provider.BackupBackend("SomeBackend")
349
+ backendByAltName, err2 := provider.BackupBackend("YetAnotherBackendName")
350
+
351
+ assert.NotNil(t, backendByName)
352
+ assert.Nil(t, err1)
353
+ assert.NotNil(t, backendByAltName)
354
+ assert.Nil(t, err2)
355
+ })
356
+ }
357
+
358
+ func fakeExtractFn(param map[string]interface{}) (interface{}, *dto.TargetCombination, error) {
359
+ extracted := map[string]interface{}{}
360
+ extracted["nearArgumentParam"] = []string{"fake"}
361
+ return extracted, nil, nil
362
+ }
363
+
364
+ func fakeValidateFn(param interface{}) error {
365
+ return nil
366
+ }
367
+
368
+ func newGraphQLModule(name string) *dummyGraphQLModule {
369
+ return &dummyGraphQLModule{
370
+ dummyText2VecModuleNoCapabilities: newDummyText2VecModule(name, nil),
371
+ arguments: map[string]modulecapabilities.GraphQLArgument{},
372
+ }
373
+ }
374
+
375
+ type dummyGraphQLModule struct {
376
+ dummyText2VecModuleNoCapabilities
377
+ arguments map[string]modulecapabilities.GraphQLArgument
378
+ }
379
+
380
+ func (m *dummyGraphQLModule) withArg(argName string) *dummyGraphQLModule {
381
+ arg := modulecapabilities.GraphQLArgument{
382
+ GetArgumentsFunction: func(classname string) *graphql.ArgumentConfig { return &graphql.ArgumentConfig{} },
383
+ ExploreArgumentsFunction: func() *graphql.ArgumentConfig { return &graphql.ArgumentConfig{} },
384
+ ExtractFunction: fakeExtractFn,
385
+ ValidateFunction: fakeValidateFn,
386
+ }
387
+ m.arguments[argName] = arg
388
+ return m
389
+ }
390
+
391
+ func (m *dummyGraphQLModule) withExtractFn(argName string) *dummyGraphQLModule {
392
+ arg := m.arguments[argName]
393
+ arg.ExtractFunction = fakeExtractFn
394
+ m.arguments[argName] = arg
395
+ return m
396
+ }
397
+
398
+ func (m *dummyGraphQLModule) Arguments() map[string]modulecapabilities.GraphQLArgument {
399
+ return m.arguments
400
+ }
401
+
402
+ func newGraphQLAdditionalModule(name string) *dummyAdditionalModule {
403
+ return &dummyAdditionalModule{
404
+ dummyGraphQLModule: *newGraphQLModule(name),
405
+ additionalProperties: map[string]modulecapabilities.AdditionalProperty{},
406
+ }
407
+ }
408
+
409
+ type dummyAdditionalModule struct {
410
+ dummyGraphQLModule
411
+ additionalProperties map[string]modulecapabilities.AdditionalProperty
412
+ }
413
+
414
+ func (m *dummyAdditionalModule) withArg(argName string) *dummyAdditionalModule {
415
+ m.dummyGraphQLModule.withArg(argName)
416
+ return m
417
+ }
418
+
419
+ func (m *dummyAdditionalModule) withExtractFn(argName string) *dummyAdditionalModule {
420
+ arg := m.dummyGraphQLModule.arguments[argName]
421
+ arg.ExtractFunction = fakeExtractFn
422
+ m.dummyGraphQLModule.arguments[argName] = arg
423
+ return m
424
+ }
425
+
426
+ func (m *dummyAdditionalModule) withGraphQLArg(argName string, values []string) *dummyAdditionalModule {
427
+ prop := m.additionalProperties[argName]
428
+ if prop.GraphQLNames == nil {
429
+ prop.GraphQLNames = []string{}
430
+ }
431
+ prop.GraphQLNames = append(prop.GraphQLNames, values...)
432
+
433
+ m.additionalProperties[argName] = prop
434
+ return m
435
+ }
436
+
437
+ func (m *dummyAdditionalModule) withRestApiArg(argName string, values []string) *dummyAdditionalModule {
438
+ prop := m.additionalProperties[argName]
439
+ if prop.RestNames == nil {
440
+ prop.RestNames = []string{}
441
+ }
442
+ prop.RestNames = append(prop.RestNames, values...)
443
+ prop.DefaultValue = 100
444
+
445
+ m.additionalProperties[argName] = prop
446
+ return m
447
+ }
448
+
449
+ func (m *dummyAdditionalModule) AdditionalProperties() map[string]modulecapabilities.AdditionalProperty {
450
+ return m.additionalProperties
451
+ }
452
+
453
+ func getFakeSchemaGetter() schemaGetter {
454
+ sch := enitiesSchema.Schema{
455
+ Objects: &models.Schema{
456
+ Classes: []*models.Class{
457
+ {
458
+ Class: "ClassOne",
459
+ Vectorizer: "mod1",
460
+ ModuleConfig: map[string]interface{}{
461
+ "mod": map[string]interface{}{
462
+ "some-config": "some-config-value",
463
+ },
464
+ },
465
+ },
466
+ {
467
+ Class: "ClassTwo",
468
+ Vectorizer: "mod2",
469
+ ModuleConfig: map[string]interface{}{
470
+ "mod": map[string]interface{}{
471
+ "some-config": "some-config-value",
472
+ },
473
+ },
474
+ },
475
+ {
476
+ Class: "ClassThree",
477
+ Vectorizer: "mod3",
478
+ ModuleConfig: map[string]interface{}{
479
+ "mod": map[string]interface{}{
480
+ "some-config": "some-config-value",
481
+ },
482
+ },
483
+ },
484
+ },
485
+ },
486
+ }
487
+ return &fakeSchemaGetter{schema: sch}
488
+ }
489
+
490
+ type dummyBackupModuleWithAltNames struct{}
491
+
492
+ func (m *dummyBackupModuleWithAltNames) Name() string {
493
+ return "SomeBackend"
494
+ }
495
+
496
+ func (m *dummyBackupModuleWithAltNames) AltNames() []string {
497
+ return []string{"AltBackendName", "YetAnotherBackendName"}
498
+ }
499
+
500
+ func (m *dummyBackupModuleWithAltNames) Init(ctx context.Context, params moduletools.ModuleInitParams) error {
501
+ return nil
502
+ }
503
+
504
+ func (m *dummyBackupModuleWithAltNames) Type() modulecapabilities.ModuleType {
505
+ return modulecapabilities.Backup
506
+ }
507
+
508
+ func (m *dummyBackupModuleWithAltNames) HomeDir(backupID, overrideBucket, overridePath string) string {
509
+ return ""
510
+ }
511
+
512
+ func (m *dummyBackupModuleWithAltNames) AllBackups(context.Context) ([]*backup.DistributedBackupDescriptor, error) {
513
+ return nil, nil
514
+ }
515
+
516
+ func (m *dummyBackupModuleWithAltNames) GetObject(ctx context.Context, backupID, key, overrideBucket, overridePath string) ([]byte, error) {
517
+ return nil, nil
518
+ }
519
+
520
+ func (m *dummyBackupModuleWithAltNames) WriteToFile(ctx context.Context, backupID, key, destPath, overrideBucket, overridePath string) error {
521
+ return nil
522
+ }
523
+
524
+ func (m *dummyBackupModuleWithAltNames) Write(ctx context.Context, backupID, key, overrideBucket, overridePath string, r io.ReadCloser) (int64, error) {
525
+ return 0, nil
526
+ }
527
+
528
+ func (m *dummyBackupModuleWithAltNames) Read(ctx context.Context, backupID, key, overrideBucket, overridePath string, w io.WriteCloser) (int64, error) {
529
+ return 0, nil
530
+ }
531
+
532
+ func (m *dummyBackupModuleWithAltNames) SourceDataPath() string {
533
+ return ""
534
+ }
535
+
536
+ func (*dummyBackupModuleWithAltNames) IsExternal() bool {
537
+ return true
538
+ }
539
+
540
+ func (m *dummyBackupModuleWithAltNames) PutObject(ctx context.Context, backupID, key, overrideBucket, overridePath string, byes []byte) error {
541
+ return nil
542
+ }
543
+
544
+ func (m *dummyBackupModuleWithAltNames) PutFile(ctx context.Context, backupID, key, overrideBucket, overridePath, filePath string) error {
545
+ return nil
546
+ }
547
+
548
+ func (m *dummyBackupModuleWithAltNames) Initialize(ctx context.Context, backupID, overrideBucket, overridePath string) error {
549
+ return nil
550
+ }
platform/dbops/binaries/weaviate-src/usecases/modules/searchers_test.go ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+ "testing"
17
+
18
+ "github.com/go-openapi/strfmt"
19
+ "github.com/sirupsen/logrus/hooks/test"
20
+ "github.com/stretchr/testify/assert"
21
+ "github.com/stretchr/testify/require"
22
+ "github.com/weaviate/weaviate/entities/dto"
23
+ "github.com/weaviate/weaviate/entities/models"
24
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
25
+ "github.com/weaviate/weaviate/entities/moduletools"
26
+ "github.com/weaviate/weaviate/entities/schema"
27
+ "github.com/weaviate/weaviate/usecases/config"
28
+ "github.com/weaviate/weaviate/usecases/modulecomponents/generictypes"
29
+ )
30
+
31
+ func TestModulesWithSearchers(t *testing.T) {
32
+ sch := schema.Schema{
33
+ Objects: &models.Schema{
34
+ Classes: []*models.Class{
35
+ {
36
+ Class: "MyClass",
37
+ Vectorizer: "mod",
38
+ ModuleConfig: map[string]interface{}{
39
+ "mod": map[string]interface{}{
40
+ "some-config": "some-config-value",
41
+ },
42
+ },
43
+ },
44
+ },
45
+ },
46
+ }
47
+ logger, _ := test.NewNullLogger()
48
+
49
+ t.Run("get a vector for a class", func(t *testing.T) {
50
+ p := NewProvider(logger, config.Config{})
51
+ p.SetSchemaGetter(&fakeSchemaGetter{
52
+ schema: sch,
53
+ })
54
+ p.Register(newSearcherModule[[]float32]("mod").
55
+ withArg("nearGrape").
56
+ withSearcher("nearGrape", generictypes.VectorForParams(func(ctx context.Context, params interface{},
57
+ className string,
58
+ findVectorFn modulecapabilities.FindVectorFn[[]float32],
59
+ cfg moduletools.ClassConfig,
60
+ ) ([]float32, error) {
61
+ // verify that the config tool is set, as this is a per-class search,
62
+ // so it must be set
63
+ assert.NotNil(t, cfg)
64
+
65
+ // take the findVectorFn and append one dimension. This doesn't make too
66
+ // much sense, but helps verify that the modules method was used in the
67
+ // decisions
68
+ initial, _, _ := findVectorFn.FindVector(ctx, "class", "123", "", "")
69
+ return append(initial, 4), nil
70
+ })),
71
+ )
72
+ p.Init(context.Background(), nil, logger)
73
+
74
+ res, err := p.VectorFromSearchParam(context.Background(), "MyClass", "", "",
75
+ "nearGrape", nil, generictypes.FindVectorFn(fakeFindVector))
76
+
77
+ require.Nil(t, err)
78
+ assert.Equal(t, []float32{1, 2, 3, 4}, res)
79
+ })
80
+
81
+ t.Run("no module configured for a class", func(t *testing.T) {
82
+ p := NewProvider(logger, config.Config{})
83
+ p.SetSchemaGetter(&fakeSchemaGetter{
84
+ schema: sch,
85
+ })
86
+ p.Register(newSearcherModule[[]float32]("mod").
87
+ withArg("nearGrape").
88
+ withSearcher("nearGrape", generictypes.VectorForParams(func(ctx context.Context, params interface{},
89
+ className string,
90
+ findVectorFn modulecapabilities.FindVectorFn[[]float32],
91
+ cfg moduletools.ClassConfig,
92
+ ) ([]float32, error) {
93
+ // verify that the config tool is set, as this is a per-class search,
94
+ // so it must be set
95
+ assert.NotNil(t, cfg)
96
+
97
+ // take the findVectorFn and append one dimension. This doesn't make too
98
+ // much sense, but helps verify that the modules method was used in the
99
+ // decisions
100
+ initial, _, _ := findVectorFn.FindVector(ctx, "class", "123", "", "")
101
+ return append(initial, 4), nil
102
+ })),
103
+ )
104
+ p.Init(context.Background(), nil, logger)
105
+
106
+ _, err := p.VectorFromSearchParam(context.Background(), "MyClass", "", "",
107
+ "nearDoesNotExist", nil, generictypes.FindVectorFn(fakeFindVector))
108
+
109
+ require.NotNil(t, err)
110
+ assert.Contains(t, err.Error(), "could not vectorize input for collection")
111
+ })
112
+
113
+ t.Run("get a vector across classes", func(t *testing.T) {
114
+ p := NewProvider(logger, config.Config{})
115
+ p.SetSchemaGetter(&fakeSchemaGetter{
116
+ schema: sch,
117
+ })
118
+ p.Register(newSearcherModule[[]float32]("mod").
119
+ withArg("nearGrape").
120
+ withSearcher("nearGrape", generictypes.VectorForParams(func(ctx context.Context, params interface{},
121
+ className string,
122
+ findVectorFn modulecapabilities.FindVectorFn[[]float32],
123
+ cfg moduletools.ClassConfig,
124
+ ) ([]float32, error) {
125
+ // this is a cross-class search, such as is used for Explore{}, in this
126
+ // case we do not have class-based config, but we need at least pass
127
+ // a tenant information, that's why we pass an empty config with empty tenant
128
+ // so that it would be possible to perform cross class searches, without
129
+ // tenant context. Modules must be able to deal with this situation!
130
+ assert.NotNil(t, cfg)
131
+ assert.Equal(t, "", cfg.Tenant())
132
+
133
+ // take the findVectorFn and append one dimension. This doesn't make too
134
+ // much sense, but helps verify that the modules method was used in the
135
+ // decisions
136
+ initial, _, _ := findVectorFn.FindVector(ctx, "class", "123", "", "")
137
+ return append(initial, 4), nil
138
+ })),
139
+ )
140
+ p.Init(context.Background(), nil, logger)
141
+
142
+ res, targetVector, err := p.CrossClassVectorFromSearchParam(context.Background(),
143
+ "nearGrape", nil, generictypes.FindVectorFn(fakeFindVector))
144
+
145
+ require.Nil(t, err)
146
+ assert.Equal(t, []float32{1, 2, 3, 4}, res)
147
+ assert.Equal(t, "", targetVector)
148
+ })
149
+
150
+ t.Run("explore no vectorizer", func(t *testing.T) {
151
+ p := NewProvider(logger, config.Config{})
152
+ p.SetSchemaGetter(&fakeSchemaGetter{
153
+ schema: sch,
154
+ })
155
+ p.Register(newSearcherModule[[]float32]("mod").
156
+ withArg("nearGrape").
157
+ withSearcher("nearGrape", generictypes.VectorForParams(func(ctx context.Context, params interface{},
158
+ className string,
159
+ findVectorFn modulecapabilities.FindVectorFn[[]float32],
160
+ cfg moduletools.ClassConfig,
161
+ ) ([]float32, error) {
162
+ // this is a cross-class search, such as is used for Explore{}, in this
163
+ // case we do not have class-based config, but we need at least pass
164
+ // a tenant information, that's why we pass an empty config with empty tenant
165
+ // so that it would be possible to perform cross class searches, without
166
+ // tenant context. Modules must be able to deal with this situation!
167
+ assert.NotNil(t, cfg)
168
+ assert.Equal(t, "", cfg.Tenant())
169
+
170
+ // take the findVectorFn and append one dimension. This doesn't make too
171
+ // much sense, but helps verify that the modules method was used in the
172
+ // decisions
173
+ initial, _, _ := findVectorFn.FindVector(ctx, "class", "123", "", "")
174
+ return append(initial, 4), nil
175
+ })),
176
+ )
177
+ p.Init(context.Background(), nil, logger)
178
+
179
+ _, _, err := p.CrossClassVectorFromSearchParam(context.Background(),
180
+ "nearDoesNotExist", nil, generictypes.FindVectorFn(fakeFindVector))
181
+
182
+ require.NotNil(t, err)
183
+ })
184
+
185
+ t.Run("get a multi vector for a class", func(t *testing.T) {
186
+ p := NewProvider(logger, config.Config{})
187
+ p.SetSchemaGetter(&fakeSchemaGetter{
188
+ schema: sch,
189
+ })
190
+ p.Register(newSearcherModule[[][]float32]("mod").
191
+ withArg("nearGrape").
192
+ withSearcher("nearGrape", generictypes.MultiVectorForParams(func(ctx context.Context, params interface{},
193
+ className string,
194
+ findVectorFn modulecapabilities.FindVectorFn[[][]float32],
195
+ cfg moduletools.ClassConfig,
196
+ ) ([][]float32, error) {
197
+ // verify that the config tool is set, as this is a per-class search,
198
+ // so it must be set
199
+ assert.NotNil(t, cfg)
200
+
201
+ // take the findVectorFn and append one dimension. This doesn't make too
202
+ // much sense, but helps verify that the modules method was used in the
203
+ // decisions
204
+ initial, _, _ := findVectorFn.FindVector(ctx, "class", "123", "", "")
205
+ return initial, nil
206
+ })),
207
+ )
208
+ p.Init(context.Background(), nil, logger)
209
+
210
+ res, err := p.MultiVectorFromSearchParam(context.Background(), "MyClass", "", "",
211
+ "nearGrape", nil, generictypes.MultiFindVectorFn(multiFakeFindVector))
212
+
213
+ require.Nil(t, err)
214
+ assert.Equal(t, [][]float32{{0.1, 0.2, 0.3}, {0.11, 0.22, 0.33}}, res)
215
+ })
216
+
217
+ t.Run("get a multi vector across classes", func(t *testing.T) {
218
+ p := NewProvider(logger, config.Config{})
219
+ p.SetSchemaGetter(&fakeSchemaGetter{
220
+ schema: sch,
221
+ })
222
+ p.Register(newSearcherModule[[][]float32]("mod").
223
+ withArg("nearGrape").
224
+ withSearcher("nearGrape", generictypes.MultiVectorForParams(func(ctx context.Context, params interface{},
225
+ className string,
226
+ findVectorFn modulecapabilities.FindVectorFn[[][]float32],
227
+ cfg moduletools.ClassConfig,
228
+ ) ([][]float32, error) {
229
+ // this is a cross-class search, such as is used for Explore{}, in this
230
+ // case we do not have class-based config, but we need at least pass
231
+ // a tenant information, that's why we pass an empty config with empty tenant
232
+ // so that it would be possible to perform cross class searches, without
233
+ // tenant context. Modules must be able to deal with this situation!
234
+ assert.NotNil(t, cfg)
235
+ assert.Equal(t, "", cfg.Tenant())
236
+
237
+ // take the findVectorFn and append one dimension. This doesn't make too
238
+ // much sense, but helps verify that the modules method was used in the
239
+ // decisions
240
+ initial, _, _ := findVectorFn.FindVector(ctx, "class", "123", "", "")
241
+ return initial, nil
242
+ })),
243
+ )
244
+ p.Init(context.Background(), nil, logger)
245
+
246
+ res, targetVector, err := p.MultiCrossClassVectorFromSearchParam(context.Background(),
247
+ "nearGrape", nil, generictypes.MultiFindVectorFn(multiFakeFindVector))
248
+
249
+ require.Nil(t, err)
250
+ assert.Equal(t, [][]float32{{0.1, 0.2, 0.3}, {0.11, 0.22, 0.33}}, res)
251
+ assert.Equal(t, "", targetVector)
252
+ })
253
+ }
254
+
255
+ func fakeFindVector(ctx context.Context, className string, id strfmt.UUID, tenant, targetVector string) ([]float32, string, error) {
256
+ return []float32{1, 2, 3}, targetVector, nil
257
+ }
258
+
259
+ func multiFakeFindVector(ctx context.Context, className string, id strfmt.UUID, tenant, targetVector string) ([][]float32, string, error) {
260
+ return [][]float32{{0.1, 0.2, 0.3}, {0.11, 0.22, 0.33}}, targetVector, nil
261
+ }
262
+
263
+ func newSearcherModule[T dto.Embedding](name string) *dummySearcherModule[T] {
264
+ return &dummySearcherModule[T]{
265
+ dummyGraphQLModule: newGraphQLModule(name),
266
+ searchers: map[string]modulecapabilities.VectorForParams[T]{},
267
+ }
268
+ }
269
+
270
+ type dummySearcherModule[T dto.Embedding] struct {
271
+ *dummyGraphQLModule
272
+ searchers map[string]modulecapabilities.VectorForParams[T]
273
+ }
274
+
275
+ func (m *dummySearcherModule[T]) withArg(arg string) *dummySearcherModule[T] {
276
+ // call the super's withArg
277
+ m.dummyGraphQLModule.withArg(arg)
278
+
279
+ // but don't return their return type but ours :)
280
+ return m
281
+ }
282
+
283
+ // a helper for our test
284
+ func (m *dummySearcherModule[T]) withSearcher(arg string,
285
+ impl modulecapabilities.VectorForParams[T],
286
+ ) *dummySearcherModule[T] {
287
+ m.searchers[arg] = impl
288
+ return m
289
+ }
290
+
291
+ // public method to implement the modulecapabilities.Searcher interface
292
+ func (m *dummySearcherModule[T]) VectorSearches() map[string]modulecapabilities.VectorForParams[T] {
293
+ return m.searchers
294
+ }
platform/dbops/binaries/weaviate-src/usecases/modules/vectorizer.go ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "runtime"
19
+
20
+ "github.com/weaviate/weaviate/entities/dto"
21
+ enterrors "github.com/weaviate/weaviate/entities/errors"
22
+ "github.com/weaviate/weaviate/entities/modelsext"
23
+
24
+ "github.com/sirupsen/logrus"
25
+ "github.com/weaviate/weaviate/entities/models"
26
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
27
+ "github.com/weaviate/weaviate/entities/moduletools"
28
+ "github.com/weaviate/weaviate/entities/vectorindex/dynamic"
29
+ "github.com/weaviate/weaviate/entities/vectorindex/flat"
30
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
31
+ "github.com/weaviate/weaviate/usecases/config"
32
+ )
33
+
34
+ var _NUMCPU = runtime.NumCPU()
35
+
36
+ const (
37
+ errorVectorizerCapability = "module %q exists, but does not provide the " +
38
+ "Vectorizer or ReferenceVectorizer capability"
39
+
40
+ errorVectorIndexType = "vector index config (%T) is not of type HNSW, " +
41
+ "but objects manager is restricted to HNSW"
42
+
43
+ warningVectorIgnored = "This vector will be ignored. If you meant to index " +
44
+ "the vector, make sure to set vectorIndexConfig.skip to 'false'. If the previous " +
45
+ "setting is correct, make sure you set vectorizer to 'none' in the schema and " +
46
+ "provide a null-vector (i.e. no vector) at import time."
47
+
48
+ warningSkipVectorGenerated = "this class is configured to skip vector indexing, " +
49
+ "but a vector was generated by the %q vectorizer. " + warningVectorIgnored
50
+
51
+ warningSkipVectorProvided = "this class is configured to skip vector indexing, " +
52
+ "but a vector was explicitly provided. " + warningVectorIgnored
53
+ )
54
+
55
+ func (p *Provider) ValidateVectorizer(moduleName string) error {
56
+ mod := p.GetByName(moduleName)
57
+ if mod == nil {
58
+ return fmt.Errorf("no module with name %q present", moduleName)
59
+ }
60
+
61
+ okVec := p.implementsVectorizer(mod)
62
+ okRefVec := p.implementsReferenceVectorizer(mod)
63
+ if !okVec && !okRefVec {
64
+ return fmt.Errorf(errorVectorizerCapability, moduleName)
65
+ }
66
+
67
+ return nil
68
+ }
69
+
70
+ func (p *Provider) UsingRef2Vec(className string) bool {
71
+ class, err := p.getClass(className)
72
+ if err != nil {
73
+ return false
74
+ }
75
+
76
+ cfg := class.ModuleConfig
77
+ if cfg == nil {
78
+ return false
79
+ }
80
+
81
+ for modName := range cfg.(map[string]interface{}) {
82
+ if p.implementsReferenceVectorizer(p.GetByName(modName)) {
83
+ return true
84
+ }
85
+ }
86
+
87
+ return false
88
+ }
89
+
90
+ func (p *Provider) BatchUpdateVector(ctx context.Context, class *models.Class, objects []*models.Object,
91
+ findObjectFn modulecapabilities.FindObjectFn,
92
+ logger logrus.FieldLogger,
93
+ ) (map[int]error, error) {
94
+ modConfigs, err := p.getModuleConfigs(class)
95
+ if err != nil {
96
+ return nil, err
97
+ }
98
+
99
+ if len(modConfigs) == 0 {
100
+ // short-circuit collections without vector index
101
+ if class.Vectorizer == config.VectorizerModuleNone {
102
+ return nil, nil
103
+ }
104
+
105
+ return nil, fmt.Errorf("no vectorizer configs for class %s", class.Class)
106
+ }
107
+
108
+ var (
109
+ vecErrorsList = make([]map[int]error, len(modConfigs))
110
+ errorList = make([]error, len(modConfigs))
111
+ counter = 0
112
+ )
113
+
114
+ eg := enterrors.NewErrorGroupWrapper(logger)
115
+ eg.SetLimit(_NUMCPU)
116
+ for targetVector, modConfig := range modConfigs {
117
+ shouldVectorizeClass, err := p.shouldVectorizeClass(class, targetVector, logger)
118
+ if err != nil {
119
+ errorList[counter] = err
120
+ continue
121
+ }
122
+ if shouldVectorizeClass {
123
+ targetVector := targetVector
124
+ modConfig := modConfig
125
+ counter := counter
126
+
127
+ fun := func() error {
128
+ vecErrors, err := p.batchUpdateVector(ctx, objects, class, findObjectFn, targetVector, modConfig)
129
+ errorList[counter] = err
130
+ vecErrorsList[counter] = vecErrors
131
+ return nil // to use error group
132
+ }
133
+ eg.Go(fun)
134
+ }
135
+
136
+ counter += 1
137
+ }
138
+ if err := eg.Wait(); err != nil {
139
+ return nil, err
140
+ }
141
+
142
+ // combine errors from different runs
143
+ combinedErrors := make(map[int]error, 0)
144
+ for _, vecErrors := range vecErrorsList {
145
+ for i, vecError := range vecErrors {
146
+ if existingErr, ok := combinedErrors[i]; ok {
147
+ vecError = errors.Join(existingErr, vecError)
148
+ }
149
+ combinedErrors[i] = vecError
150
+ }
151
+ }
152
+
153
+ return combinedErrors, errors.Join(errorList...)
154
+ }
155
+
156
+ func (p *Provider) shouldVectorizeClass(class *models.Class, targetVector string, logger logrus.FieldLogger) (bool, error) {
157
+ hnswConfig, err := p.getVectorIndexConfig(class, targetVector)
158
+ if err != nil {
159
+ return false, err
160
+ }
161
+
162
+ vectorizer := p.getVectorizer(class, targetVector)
163
+ if vectorizer == config.VectorizerModuleNone {
164
+ return false, nil
165
+ }
166
+
167
+ if hnswConfig.Skip {
168
+ logger.WithField("className", class.Class).
169
+ WithField("vectorizer", vectorizer).
170
+ Warningf(warningSkipVectorGenerated, vectorizer)
171
+ }
172
+ return true, nil
173
+ }
174
+
175
+ func (p *Provider) batchUpdateVector(ctx context.Context, objects []*models.Object, class *models.Class,
176
+ findObjectFn modulecapabilities.FindObjectFn,
177
+ targetVector string, modConfig map[string]interface{},
178
+ ) (map[int]error, error) {
179
+ found := p.getModule(modConfig)
180
+ if found == nil {
181
+ return nil, fmt.Errorf("no vectorizer found for class %q", class.Class)
182
+ }
183
+ cfg := NewClassBasedModuleConfig(class, found.Name(), "", targetVector, &p.cfg)
184
+
185
+ if vectorizer, ok := found.(modulecapabilities.Vectorizer[[]float32]); ok {
186
+ // each target vector can have its own associated properties, and we need to determine for each one if we should
187
+ // skip it or not. To simplify things, we create a boolean slice that indicates for each object if the given
188
+ // vectorizer needs to act on it or not. This allows us to use the same objects slice for all vectorizers and
189
+ // simplifies the mapping of the returned vectors to the objects.
190
+ skipRevectorization := make([]bool, len(objects))
191
+ for i, obj := range objects {
192
+ if !p.shouldVectorizeObject(obj, cfg) {
193
+ skipRevectorization[i] = true
194
+ continue
195
+ }
196
+ reVectorize, addProps, vector, err := reVectorize(ctx, cfg, vectorizer, obj,
197
+ class, nil, targetVector, findObjectFn, p.cfg.RevectorizeCheckDisabled.Get())
198
+ if err != nil {
199
+ return nil, fmt.Errorf("cannot vectorize class %q: %w", class.Class, err)
200
+ }
201
+ if !reVectorize {
202
+ skipRevectorization[i] = true
203
+ p.lockGuard(func() {
204
+ p.addVectorToObject(obj, vector, nil, addProps, cfg)
205
+ })
206
+ }
207
+ }
208
+ vectors, addProps, vecErrors := vectorizer.VectorizeBatch(ctx, objects, skipRevectorization, cfg)
209
+ for i := range objects {
210
+ if _, ok := vecErrors[i]; ok || skipRevectorization[i] {
211
+ continue
212
+ }
213
+
214
+ var addProp models.AdditionalProperties = nil
215
+ if addProps != nil { // only present for contextionary and probably nobody is using this
216
+ addProp = addProps[i]
217
+ }
218
+
219
+ p.lockGuard(func() {
220
+ p.addVectorToObject(objects[i], vectors[i], nil, addProp, cfg)
221
+ })
222
+ }
223
+
224
+ return vecErrors, nil
225
+ } else if vectorizer, ok := found.(modulecapabilities.Vectorizer[[][]float32]); ok {
226
+ // each target vector can have its own associated properties, and we need to determine for each one if we should
227
+ // skip it or not. To simplify things, we create a boolean slice that indicates for each object if the given
228
+ // vectorizer needs to act on it or not. This allows us to use the same objects slice for all vectorizers and
229
+ // simplifies the mapping of the returned vectors to the objects.
230
+ skipRevectorization := make([]bool, len(objects))
231
+ for i, obj := range objects {
232
+ if !p.shouldVectorizeObject(obj, cfg) {
233
+ skipRevectorization[i] = true
234
+ continue
235
+ }
236
+ reVectorize, addProps, multiVector, err := reVectorizeMulti(ctx, cfg,
237
+ vectorizer, obj, class, nil, targetVector, findObjectFn,
238
+ p.cfg.RevectorizeCheckDisabled.Get())
239
+ if err != nil {
240
+ return nil, fmt.Errorf("cannot vectorize class %q: %w", class.Class, err)
241
+ }
242
+ if !reVectorize {
243
+ skipRevectorization[i] = true
244
+ p.lockGuard(func() {
245
+ p.addVectorToObject(obj, nil, multiVector, addProps, cfg)
246
+ })
247
+ }
248
+ }
249
+ multiVectors, addProps, vecErrors := vectorizer.VectorizeBatch(ctx, objects, skipRevectorization, cfg)
250
+ for i := range objects {
251
+ if _, ok := vecErrors[i]; ok || skipRevectorization[i] {
252
+ continue
253
+ }
254
+
255
+ var addProp models.AdditionalProperties = nil
256
+ if addProps != nil { // only present for contextionary and probably nobody is using this
257
+ addProp = addProps[i]
258
+ }
259
+
260
+ p.lockGuard(func() {
261
+ p.addVectorToObject(objects[i], nil, multiVectors[i], addProp, cfg)
262
+ })
263
+ }
264
+
265
+ return vecErrors, nil
266
+ } else {
267
+ refVectorizer := found.(modulecapabilities.ReferenceVectorizer[[]float32])
268
+ errs := make(map[int]error, 0)
269
+ for i, obj := range objects {
270
+ vector, err := refVectorizer.VectorizeObject(ctx, obj, cfg, findObjectFn)
271
+ if err != nil {
272
+ errs[i] = fmt.Errorf("update reference vector: %w", err)
273
+ }
274
+ p.lockGuard(func() {
275
+ p.addVectorToObject(obj, vector, nil, nil, cfg)
276
+ })
277
+ }
278
+ return errs, nil
279
+ }
280
+ }
281
+
282
+ func (p *Provider) UpdateVector(ctx context.Context, object *models.Object, class *models.Class,
283
+ findObjectFn modulecapabilities.FindObjectFn,
284
+ logger logrus.FieldLogger,
285
+ ) error {
286
+ eg := enterrors.NewErrorGroupWrapper(logger)
287
+ eg.SetLimit(_NUMCPU)
288
+
289
+ modConfigs, err := p.getModuleConfigs(class)
290
+ if err != nil {
291
+ return err
292
+ }
293
+
294
+ for targetVector, modConfig := range modConfigs {
295
+ targetVector := targetVector // https://golang.org/doc/faq#closures_and_goroutines
296
+ modConfig := modConfig // https://golang.org/doc/faq#closures_and_goroutines
297
+ eg.Go(func() error {
298
+ return p.vectorizeOne(ctx, object, class, findObjectFn, targetVector, modConfig, logger)
299
+ }, targetVector)
300
+ }
301
+ if err = eg.Wait(); err != nil {
302
+ return err
303
+ }
304
+ return nil
305
+ }
306
+
307
+ func (p *Provider) lockGuard(mutate func()) {
308
+ p.vectorsLock.Lock()
309
+ defer p.vectorsLock.Unlock()
310
+ mutate()
311
+ }
312
+
313
+ func (p *Provider) addVectorToObject(object *models.Object,
314
+ vector []float32, multiVector [][]float32,
315
+ additional models.AdditionalProperties, cfg moduletools.ClassConfig,
316
+ ) {
317
+ if len(additional) > 0 {
318
+ if object.Additional == nil {
319
+ object.Additional = models.AdditionalProperties{}
320
+ }
321
+ for additionalName, additionalValue := range additional {
322
+ object.Additional[additionalName] = additionalValue
323
+ }
324
+ }
325
+ if cfg.TargetVector() == "" {
326
+ object.Vector = vector
327
+ return
328
+ }
329
+ if object.Vectors == nil {
330
+ object.Vectors = models.Vectors{}
331
+ }
332
+ if multiVector != nil {
333
+ object.Vectors[cfg.TargetVector()] = multiVector
334
+ } else {
335
+ object.Vectors[cfg.TargetVector()] = vector
336
+ }
337
+ }
338
+
339
+ func (p *Provider) vectorizeOne(ctx context.Context, object *models.Object, class *models.Class,
340
+ findObjectFn modulecapabilities.FindObjectFn,
341
+ targetVector string, modConfig map[string]interface{},
342
+ logger logrus.FieldLogger,
343
+ ) error {
344
+ vectorize, err := p.shouldVectorize(object, class, targetVector, logger)
345
+ if err != nil {
346
+ return fmt.Errorf("vectorize check for target vector %s: %w", targetVector, err)
347
+ }
348
+ if vectorize {
349
+ if err := p.vectorize(ctx, object, class, findObjectFn, targetVector, modConfig); err != nil {
350
+ return fmt.Errorf("vectorize target vector %s: %w", targetVector, err)
351
+ }
352
+ }
353
+ return nil
354
+ }
355
+
356
+ func (p *Provider) vectorize(ctx context.Context, object *models.Object, class *models.Class,
357
+ findObjectFn modulecapabilities.FindObjectFn,
358
+ targetVector string, modConfig map[string]interface{},
359
+ ) error {
360
+ found := p.getModule(modConfig)
361
+ if found == nil {
362
+ return fmt.Errorf(
363
+ "no vectorizer found for class %q", object.Class)
364
+ }
365
+
366
+ cfg := NewClassBasedModuleConfig(class, found.Name(), "", targetVector, &p.cfg)
367
+
368
+ if vectorizer, ok := found.(modulecapabilities.Vectorizer[[]float32]); ok {
369
+ if p.shouldVectorizeObject(object, cfg) {
370
+ var targetProperties []string
371
+ vecConfig, ok := modConfig[found.Name()]
372
+ if ok {
373
+ if properties, ok := vecConfig.(map[string]interface{})["properties"]; ok {
374
+ if propSlice, ok := properties.([]string); ok {
375
+ targetProperties = propSlice
376
+ }
377
+ }
378
+ }
379
+ needsRevectorization, additionalProperties, vector, err := reVectorize(ctx,
380
+ cfg, vectorizer, object, class, targetProperties, targetVector, findObjectFn,
381
+ p.cfg.RevectorizeCheckDisabled.Get())
382
+ if err != nil {
383
+ return fmt.Errorf("cannot revectorize class %q: %w", object.Class, err)
384
+ }
385
+ if needsRevectorization {
386
+ var err error
387
+ vector, additionalProperties, err = vectorizer.VectorizeObject(ctx, object, cfg)
388
+ if err != nil {
389
+ return fmt.Errorf("update vector: %w", err)
390
+ }
391
+ }
392
+
393
+ p.lockGuard(func() {
394
+ p.addVectorToObject(object, vector, nil, additionalProperties, cfg)
395
+ })
396
+ return nil
397
+ }
398
+ } else if vectorizer, ok := found.(modulecapabilities.Vectorizer[[][]float32]); ok {
399
+ if p.shouldVectorizeObject(object, cfg) {
400
+ var targetProperties []string
401
+ vecConfig, ok := modConfig[found.Name()]
402
+ if ok {
403
+ if properties, ok := vecConfig.(map[string]interface{})["properties"]; ok {
404
+ if propSlice, ok := properties.([]string); ok {
405
+ targetProperties = propSlice
406
+ }
407
+ }
408
+ }
409
+ needsRevectorization, additionalProperties, multiVector, err := reVectorizeMulti(ctx,
410
+ cfg, vectorizer, object, class, targetProperties, targetVector, findObjectFn,
411
+ p.cfg.RevectorizeCheckDisabled.Get())
412
+ if err != nil {
413
+ return fmt.Errorf("cannot revectorize class %q: %w", object.Class, err)
414
+ }
415
+ if needsRevectorization {
416
+ var err error
417
+ multiVector, additionalProperties, err = vectorizer.VectorizeObject(ctx, object, cfg)
418
+ if err != nil {
419
+ return fmt.Errorf("update vector: %w", err)
420
+ }
421
+ }
422
+
423
+ p.lockGuard(func() {
424
+ p.addVectorToObject(object, nil, multiVector, additionalProperties, cfg)
425
+ })
426
+ return nil
427
+ }
428
+ } else {
429
+ refVectorizer := found.(modulecapabilities.ReferenceVectorizer[[]float32])
430
+ vector, err := refVectorizer.VectorizeObject(ctx, object, cfg, findObjectFn)
431
+ if err != nil {
432
+ return fmt.Errorf("update reference vector: %w", err)
433
+ }
434
+ p.lockGuard(func() {
435
+ p.addVectorToObject(object, vector, nil, nil, cfg)
436
+ })
437
+ }
438
+ return nil
439
+ }
440
+
441
+ func (p *Provider) shouldVectorizeObject(object *models.Object, cfg moduletools.ClassConfig) bool {
442
+ if cfg.TargetVector() == "" {
443
+ return object.Vector == nil
444
+ }
445
+
446
+ targetVectorExists := false
447
+ p.lockGuard(func() {
448
+ vec, ok := object.Vectors[cfg.TargetVector()]
449
+ isVectorEmpty, _ := dto.IsVectorEmpty(vec)
450
+ targetVectorExists = ok && !isVectorEmpty
451
+ })
452
+ return !targetVectorExists
453
+ }
454
+
455
+ func (p *Provider) shouldVectorize(object *models.Object, class *models.Class,
456
+ targetVector string, logger logrus.FieldLogger,
457
+ ) (bool, error) {
458
+ hnswConfig, err := p.getVectorIndexConfig(class, targetVector)
459
+ if err != nil {
460
+ return false, err
461
+ }
462
+
463
+ vectorizer := p.getVectorizer(class, targetVector)
464
+ if vectorizer == config.VectorizerModuleNone {
465
+ vector := p.getVector(object, targetVector)
466
+ isEmpty, err := dto.IsVectorEmpty(vector)
467
+ if err != nil {
468
+ return false, fmt.Errorf("should vectorize: is vector empty: %w", err)
469
+ }
470
+ if hnswConfig.Skip && !isEmpty {
471
+ logger.WithField("className", class.Class).
472
+ Warningf(warningSkipVectorProvided)
473
+ }
474
+ return false, nil
475
+ }
476
+
477
+ if hnswConfig.Skip {
478
+ logger.WithField("className", class.Class).
479
+ WithField("vectorizer", vectorizer).
480
+ Warningf(warningSkipVectorGenerated, vectorizer)
481
+ }
482
+ return true, nil
483
+ }
484
+
485
+ func (p *Provider) getVectorizer(class *models.Class, targetVector string) string {
486
+ if targetVector != "" && len(class.VectorConfig) > 0 {
487
+ if vectorConfig, ok := class.VectorConfig[targetVector]; ok {
488
+ if vectorizer, ok := vectorConfig.Vectorizer.(map[string]interface{}); ok && len(vectorizer) == 1 {
489
+ for vectorizerName := range vectorizer {
490
+ return vectorizerName
491
+ }
492
+ }
493
+ }
494
+ return ""
495
+ }
496
+ return class.Vectorizer
497
+ }
498
+
499
+ func (p *Provider) getVector(object *models.Object, targetVector string) models.Vector {
500
+ p.vectorsLock.Lock()
501
+ defer p.vectorsLock.Unlock()
502
+ if targetVector != "" {
503
+ if len(object.Vectors) == 0 {
504
+ return nil
505
+ }
506
+ return object.Vectors[targetVector]
507
+ }
508
+ return object.Vector
509
+ }
510
+
511
+ func (p *Provider) getVectorIndexConfig(class *models.Class, targetVector string) (hnsw.UserConfig, error) {
512
+ vectorIndexConfig := class.VectorIndexConfig
513
+ if targetVector != "" {
514
+ vectorIndexConfig = class.VectorConfig[targetVector].VectorIndexConfig
515
+ }
516
+ hnswConfig, okHnsw := vectorIndexConfig.(hnsw.UserConfig)
517
+ _, okFlat := vectorIndexConfig.(flat.UserConfig)
518
+ _, okDynamic := vectorIndexConfig.(dynamic.UserConfig)
519
+ if !(okHnsw || okFlat || okDynamic) {
520
+ return hnsw.UserConfig{}, fmt.Errorf(errorVectorIndexType, vectorIndexConfig)
521
+ }
522
+ return hnswConfig, nil
523
+ }
524
+
525
+ func (p *Provider) getModuleConfigs(class *models.Class) (map[string]map[string]interface{}, error) {
526
+ modConfigs := map[string]map[string]interface{}{}
527
+ // get all named vectorizers for classs
528
+ for name, vectorConfig := range class.VectorConfig {
529
+ modConfig, ok := vectorConfig.Vectorizer.(map[string]interface{})
530
+ if !ok {
531
+ return nil, fmt.Errorf("class %v vectorizer %s not present", class.Class, name)
532
+ }
533
+ modConfigs[name] = modConfig
534
+ }
535
+
536
+ if modelsext.ClassHasLegacyVectorIndex(class) && class.Vectorizer != config.VectorizerModuleNone {
537
+ if modConfig, ok := class.ModuleConfig.(map[string]interface{}); ok {
538
+ modConfigs[""] = modConfig
539
+ } else {
540
+ return nil, fmt.Errorf("no moduleconfig for class %v present", class.Class)
541
+ }
542
+ }
543
+
544
+ return modConfigs, nil
545
+ }
546
+
547
+ func (p *Provider) getModule(modConfig map[string]interface{}) (found modulecapabilities.Module) {
548
+ for modName := range modConfig {
549
+ if err := p.ValidateVectorizer(modName); err == nil {
550
+ found = p.GetByName(modName)
551
+ break
552
+ }
553
+ }
554
+ return
555
+ }
556
+
557
+ func (p *Provider) VectorizerName(className string) (string, error) {
558
+ name, _, err := p.getClassVectorizer(className)
559
+ if err != nil {
560
+ return "", err
561
+ }
562
+ return name, nil
563
+ }
564
+
565
+ func (p *Provider) getClassVectorizer(className string) (string, interface{}, error) {
566
+ class := p.schemaGetter.ReadOnlyClass(className)
567
+ if class == nil {
568
+ // this should be impossible by the time this method gets called, but let's
569
+ // be 100% certain
570
+ return "", nil, fmt.Errorf("class %s not present", className)
571
+ }
572
+
573
+ return class.Vectorizer, class.VectorIndexConfig, nil
574
+ }
575
+
576
+ func (p *Provider) implementsVectorizer(mod modulecapabilities.Module) bool {
577
+ switch mod.(type) {
578
+ case modulecapabilities.Vectorizer[[]float32], modulecapabilities.Vectorizer[[][]float32]:
579
+ return true
580
+ default:
581
+ return false
582
+ }
583
+ }
584
+
585
+ func (p *Provider) implementsReferenceVectorizer(mod modulecapabilities.Module) bool {
586
+ switch mod.(type) {
587
+ case modulecapabilities.ReferenceVectorizer[[]float32], modulecapabilities.ReferenceVectorizer[[][]float32]:
588
+ return true
589
+ default:
590
+ return false
591
+ }
592
+ }
platform/dbops/binaries/weaviate-src/usecases/modules/vectorizer_test.go ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package modules
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "testing"
18
+
19
+ "github.com/go-openapi/strfmt"
20
+ "github.com/google/uuid"
21
+ "github.com/sirupsen/logrus/hooks/test"
22
+ "github.com/stretchr/testify/assert"
23
+ "github.com/stretchr/testify/require"
24
+ "github.com/weaviate/weaviate/entities/models"
25
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
26
+ "github.com/weaviate/weaviate/entities/schema"
27
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
28
+ "github.com/weaviate/weaviate/usecases/config"
29
+ )
30
+
31
+ func TestProvider_ValidateVectorizer(t *testing.T) {
32
+ logger, _ := test.NewNullLogger()
33
+ t.Run("with vectorizer module", func(t *testing.T) {
34
+ p := NewProvider(logger, config.Config{})
35
+ vec := newDummyModule("some-module", modulecapabilities.Text2Vec)
36
+ p.Register(vec)
37
+
38
+ err := p.ValidateVectorizer(vec.Name())
39
+ assert.Nil(t, err)
40
+ })
41
+
42
+ t.Run("with reference vectorizer module", func(t *testing.T) {
43
+ p := NewProvider(logger, config.Config{})
44
+ refVec := newDummyModule("some-module", modulecapabilities.Ref2Vec)
45
+ p.Register(refVec)
46
+
47
+ err := p.ValidateVectorizer(refVec.Name())
48
+ assert.Nil(t, err)
49
+ })
50
+
51
+ t.Run("with non-vectorizer module", func(t *testing.T) {
52
+ modName := "some-module"
53
+ p := NewProvider(logger, config.Config{})
54
+ nonVec := newDummyModule(modName, "")
55
+ p.Register(nonVec)
56
+
57
+ expectedErr := fmt.Sprintf(
58
+ "module %q exists, but does not provide the Vectorizer or ReferenceVectorizer capability",
59
+ modName)
60
+ err := p.ValidateVectorizer(nonVec.Name())
61
+ assert.EqualError(t, err, expectedErr)
62
+ })
63
+
64
+ t.Run("with unregistered module", func(t *testing.T) {
65
+ modName := "does-not-exist"
66
+ p := NewProvider(logger, config.Config{})
67
+ expectedErr := fmt.Sprintf(
68
+ "no module with name %q present",
69
+ modName)
70
+ err := p.ValidateVectorizer(modName)
71
+ assert.EqualError(t, err, expectedErr)
72
+ })
73
+ }
74
+
75
+ func TestProvider_UsingRef2Vec(t *testing.T) {
76
+ logger, _ := test.NewNullLogger()
77
+ t.Run("with ReferenceVectorizer", func(t *testing.T) {
78
+ modName := "some-module"
79
+ className := "SomeClass"
80
+ mod := newDummyModule(modName, modulecapabilities.Ref2Vec)
81
+ sch := schema.Schema{Objects: &models.Schema{
82
+ Classes: []*models.Class{{
83
+ Class: className,
84
+ ModuleConfig: map[string]interface{}{
85
+ modName: struct{}{},
86
+ },
87
+ }},
88
+ }}
89
+ p := NewProvider(logger, config.Config{})
90
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
91
+ p.Register(mod)
92
+ assert.True(t, p.UsingRef2Vec(className))
93
+ })
94
+
95
+ t.Run("with Vectorizer", func(t *testing.T) {
96
+ modName := "some-module"
97
+ className := "SomeClass"
98
+ mod := newDummyModule(modName, modulecapabilities.Text2Vec)
99
+ sch := schema.Schema{Objects: &models.Schema{
100
+ Classes: []*models.Class{{
101
+ Class: className,
102
+ ModuleConfig: map[string]interface{}{
103
+ modName: struct{}{},
104
+ },
105
+ }},
106
+ }}
107
+ p := NewProvider(logger, config.Config{})
108
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
109
+ p.Register(mod)
110
+ assert.False(t, p.UsingRef2Vec(className))
111
+ })
112
+
113
+ t.Run("with nonexistent class", func(t *testing.T) {
114
+ className := "SomeClass"
115
+ mod := newDummyModule("", "")
116
+
117
+ p := NewProvider(logger, config.Config{})
118
+ p.SetSchemaGetter(&fakeSchemaGetter{schema.Schema{}})
119
+ p.Register(mod)
120
+ assert.False(t, p.UsingRef2Vec(className))
121
+ })
122
+
123
+ t.Run("with empty class module config", func(t *testing.T) {
124
+ modName := "some-module"
125
+ className := "SomeClass"
126
+ mod := newDummyModule(modName, modulecapabilities.Text2Vec)
127
+ sch := schema.Schema{Objects: &models.Schema{
128
+ Classes: []*models.Class{{
129
+ Class: className,
130
+ }},
131
+ }}
132
+ p := NewProvider(logger, config.Config{})
133
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
134
+ p.Register(mod)
135
+ assert.False(t, p.UsingRef2Vec(className))
136
+ })
137
+
138
+ t.Run("with unregistered module", func(t *testing.T) {
139
+ modName := "some-module"
140
+ className := "SomeClass"
141
+ sch := schema.Schema{Objects: &models.Schema{
142
+ Classes: []*models.Class{{
143
+ Class: className,
144
+ ModuleConfig: map[string]interface{}{
145
+ modName: struct{}{},
146
+ },
147
+ }},
148
+ }}
149
+ p := NewProvider(logger, config.Config{})
150
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
151
+ assert.False(t, p.UsingRef2Vec(className))
152
+ })
153
+ }
154
+
155
+ func TestProvider_UpdateVector(t *testing.T) {
156
+ t.Run("with Vectorizer", func(t *testing.T) {
157
+ ctx := context.Background()
158
+ modName := "some-vzr"
159
+ className := "SomeClass"
160
+ mod := newDummyModule(modName, modulecapabilities.Text2Vec)
161
+ class := models.Class{
162
+ Class: className,
163
+ ModuleConfig: map[string]interface{}{
164
+ modName: map[string]interface{}{},
165
+ },
166
+ Vectorizer: "text2vec-contextionary",
167
+ VectorIndexConfig: hnsw.UserConfig{},
168
+ }
169
+ sch := schema.Schema{
170
+ Objects: &models.Schema{
171
+ Classes: []*models.Class{&class},
172
+ },
173
+ }
174
+ repo := &fakeObjectsRepo{}
175
+ logger, _ := test.NewNullLogger()
176
+
177
+ p := NewProvider(logger, config.Config{})
178
+ p.Register(mod)
179
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
180
+
181
+ obj := &models.Object{Class: className, ID: newUUID()}
182
+ err := p.UpdateVector(ctx, obj, &class, repo.Object, logger)
183
+ assert.Nil(t, err)
184
+ })
185
+
186
+ t.Run("with missing vectorizer modconfig", func(t *testing.T) {
187
+ ctx := context.Background()
188
+ class := &models.Class{
189
+ Class: "SomeClass",
190
+ VectorIndexConfig: hnsw.UserConfig{},
191
+ Vectorizer: "text2vec-contextionary",
192
+ }
193
+ mod := newDummyModule("", "")
194
+ logger, _ := test.NewNullLogger()
195
+
196
+ p := NewProvider(logger, config.Config{})
197
+ p.Register(mod)
198
+ p.SetSchemaGetter(&fakeSchemaGetter{schema.Schema{}})
199
+
200
+ obj := &models.Object{Class: class.Class, ID: newUUID()}
201
+ err := p.UpdateVector(ctx, obj, class, (&fakeObjectsRepo{}).Object, logger)
202
+ expectedErr := fmt.Sprintf("no moduleconfig for class %v present", class.Class)
203
+ assert.EqualError(t, err, expectedErr)
204
+ })
205
+
206
+ t.Run("with no vectors configuration", func(t *testing.T) {
207
+ ctx := context.Background()
208
+ class := &models.Class{
209
+ Class: "SomeClass",
210
+ Vectorizer: "none",
211
+ }
212
+
213
+ logger, _ := test.NewNullLogger()
214
+ p := NewProvider(logger, config.Config{})
215
+
216
+ obj := &models.Object{Class: class.Class, ID: newUUID()}
217
+ err := p.UpdateVector(ctx, obj, class, (&fakeObjectsRepo{}).Object, logger)
218
+ require.NoError(t, err)
219
+ })
220
+
221
+ t.Run("with ReferenceVectorizer", func(t *testing.T) {
222
+ ctx := context.Background()
223
+ modName := "some-vzr"
224
+ className := "SomeClass"
225
+ mod := newDummyModule(modName, modulecapabilities.Ref2Vec)
226
+ class := &models.Class{
227
+ Class: className,
228
+ ModuleConfig: map[string]interface{}{
229
+ modName: struct{}{},
230
+ },
231
+ Vectorizer: "text2vec-contextionary",
232
+ VectorIndexConfig: hnsw.UserConfig{},
233
+ }
234
+
235
+ sch := schema.Schema{Objects: &models.Schema{
236
+ Classes: []*models.Class{class},
237
+ }}
238
+ repo := &fakeObjectsRepo{}
239
+ logger, _ := test.NewNullLogger()
240
+
241
+ p := NewProvider(logger, config.Config{})
242
+ p.Register(mod)
243
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
244
+
245
+ obj := &models.Object{Class: className, ID: newUUID()}
246
+ err := p.UpdateVector(ctx, obj, class, repo.Object, logger)
247
+ assert.Nil(t, err)
248
+ })
249
+
250
+ t.Run("with nonexistent vector index config type", func(t *testing.T) {
251
+ ctx := context.Background()
252
+ modName := "some-vzr"
253
+ className := "SomeClass"
254
+ mod := newDummyModule(modName, modulecapabilities.Ref2Vec)
255
+ class := &models.Class{
256
+ Class: className,
257
+ ModuleConfig: map[string]interface{}{
258
+ modName: struct{}{},
259
+ },
260
+ Vectorizer: "text2vec-contextionary",
261
+ VectorIndexConfig: struct{}{},
262
+ }
263
+ sch := schema.Schema{Objects: &models.Schema{
264
+ Classes: []*models.Class{class},
265
+ }}
266
+ repo := &fakeObjectsRepo{}
267
+ logger, _ := test.NewNullLogger()
268
+
269
+ p := NewProvider(logger, config.Config{})
270
+ p.Register(mod)
271
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
272
+
273
+ obj := &models.Object{Class: className, ID: newUUID()}
274
+
275
+ err := p.UpdateVector(ctx, obj, class, repo.Object, logger)
276
+ expectedErr := "vector index config (struct {}) is not of type HNSW, " +
277
+ "but objects manager is restricted to HNSW"
278
+ require.ErrorContains(t, err, expectedErr)
279
+ })
280
+
281
+ t.Run("with ColBERT Vectorizer", func(t *testing.T) {
282
+ ctx := context.Background()
283
+ modName := "colbert"
284
+ className := "SomeClass"
285
+ mod := newDummyModule(modName, modulecapabilities.Text2Multivec)
286
+ class := models.Class{
287
+ Class: className,
288
+ VectorConfig: map[string]models.VectorConfig{
289
+ "colbert": {
290
+ Vectorizer: map[string]interface{}{modName: map[string]interface{}{}},
291
+ VectorIndexConfig: hnsw.UserConfig{Multivector: hnsw.MultivectorConfig{Enabled: true}},
292
+ VectorIndexType: "hnsw",
293
+ },
294
+ },
295
+ }
296
+ sch := schema.Schema{
297
+ Objects: &models.Schema{
298
+ Classes: []*models.Class{&class},
299
+ },
300
+ }
301
+ repo := &fakeObjectsRepo{}
302
+ logger, _ := test.NewNullLogger()
303
+
304
+ p := NewProvider(logger, config.Config{})
305
+ p.Register(mod)
306
+ p.SetSchemaGetter(&fakeSchemaGetter{sch})
307
+
308
+ obj := &models.Object{Class: className, ID: newUUID()}
309
+ err := p.UpdateVector(ctx, obj, &class, repo.Object, logger)
310
+ assert.NoError(t, err)
311
+ assert.NotEmpty(t, obj.Vectors)
312
+ assert.Equal(t, [][]float32{{0.11, 0.22, 0.33}, {0.11, 0.22, 0.33}}, obj.Vectors["colbert"])
313
+ })
314
+ }
315
+
316
+ func newUUID() strfmt.UUID {
317
+ return strfmt.UUID(uuid.NewString())
318
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/grpc.go ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "strings"
18
+ "time"
19
+
20
+ "github.com/prometheus/client_golang/prometheus"
21
+ "google.golang.org/grpc"
22
+ "google.golang.org/grpc/codes"
23
+ "google.golang.org/grpc/stats"
24
+ "google.golang.org/grpc/status"
25
+ )
26
+
27
+ // Make sure `GrpcStatsHandler always implements stats.Handler
28
+ var _ stats.Handler = &GrpcStatsHandler{}
29
+
30
+ type key int
31
+
32
+ const (
33
+ keyMethodName key = 1
34
+ keyRouteName key = 2
35
+ )
36
+
37
+ // InstrumentGrpc accepts server metrics and returns the few `[]grpc.ServerOption` which you can
38
+ // then wrap it with any `grpc.Server` to get these metrics instrumented automatically.
39
+ //
40
+ // ```
41
+ //
42
+ // svrMetrics := monitoring.NewGRPCServerMetrics(metrics, prometheus.DefaultRegisterer)
43
+ // grpcServer := grpc.NewServer(monitoring.InstrumentGrpc(*svrMetrics)...)
44
+ //
45
+ // grpcServer.Serve(listener)
46
+ //
47
+ // ```
48
+ func InstrumentGrpc(svrMetrics *GRPCServerMetrics) []grpc.ServerOption {
49
+ grpcOptions := []grpc.ServerOption{
50
+ grpc.StatsHandler(NewGrpcStatsHandler(
51
+ svrMetrics.InflightRequests,
52
+ svrMetrics.RequestBodySize,
53
+ svrMetrics.ResponseBodySize,
54
+ )),
55
+ }
56
+
57
+ grpcInterceptUnary := grpc.ChainUnaryInterceptor(
58
+ UnaryServerInstrument(svrMetrics.RequestDuration),
59
+ )
60
+ grpcOptions = append(grpcOptions, grpcInterceptUnary)
61
+
62
+ grpcInterceptStream := grpc.ChainStreamInterceptor(
63
+ StreamServerInstrument(svrMetrics.RequestDuration),
64
+ )
65
+ grpcOptions = append(grpcOptions, grpcInterceptStream)
66
+
67
+ return grpcOptions
68
+ }
69
+
70
+ func NewGrpcStatsHandler(inflight *prometheus.GaugeVec, requestSize *prometheus.HistogramVec, responseSize *prometheus.HistogramVec) *GrpcStatsHandler {
71
+ return &GrpcStatsHandler{
72
+ inflightRequests: inflight,
73
+ requestSize: requestSize,
74
+ responseSize: responseSize,
75
+ }
76
+ }
77
+
78
+ type GrpcStatsHandler struct {
79
+ inflightRequests *prometheus.GaugeVec
80
+
81
+ // in bytes
82
+ requestSize *prometheus.HistogramVec
83
+ responseSize *prometheus.HistogramVec
84
+ }
85
+
86
+ func (g *GrpcStatsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
87
+ return context.WithValue(ctx, keyMethodName, info.FullMethodName)
88
+ }
89
+
90
+ func (g *GrpcStatsHandler) HandleRPC(ctx context.Context, rpcStats stats.RPCStats) {
91
+ fullMethodName, ok := ctx.Value(keyMethodName).(string)
92
+ if !ok {
93
+ return
94
+ }
95
+
96
+ service, method := splitFullMethodName(fullMethodName)
97
+
98
+ switch s := rpcStats.(type) {
99
+ case *stats.Begin:
100
+ g.inflightRequests.WithLabelValues(service, method).Inc()
101
+ case *stats.End:
102
+ g.inflightRequests.WithLabelValues(service, method).Dec()
103
+ case *stats.InHeader:
104
+ // Ignore incoming headers.
105
+ case *stats.InPayload:
106
+ g.requestSize.WithLabelValues(service, method).Observe(float64(s.WireLength))
107
+ case *stats.InTrailer:
108
+ // Ignore incoming trailers.
109
+ case *stats.OutHeader:
110
+ // Ignore outgoing headers.
111
+ case *stats.OutPayload:
112
+ g.responseSize.WithLabelValues(service, method).Observe(float64(s.WireLength))
113
+ case *stats.OutTrailer:
114
+ // Ignore outgoing trailers. OutTrailer doesn't have valid WireLength (there is a deprecated field, always set to 0).
115
+ }
116
+ }
117
+
118
+ func (g *GrpcStatsHandler) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context {
119
+ return ctx
120
+ }
121
+
122
+ func (g *GrpcStatsHandler) HandleConn(_ context.Context, _ stats.ConnStats) {
123
+ // Don't need
124
+ }
125
+
126
+ func UnaryServerInstrument(hist *prometheus.HistogramVec) grpc.UnaryServerInterceptor {
127
+ return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
128
+ begin := time.Now()
129
+ resp, err := handler(ctx, req)
130
+ observe(hist, info.FullMethod, err, time.Since(begin))
131
+ return resp, err
132
+ }
133
+ }
134
+
135
+ func StreamServerInstrument(hist *prometheus.HistogramVec) grpc.StreamServerInterceptor {
136
+ return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
137
+ begin := time.Now()
138
+ err := handler(srv, ss)
139
+ observe(hist, info.FullMethod, err, time.Since(begin))
140
+ return err
141
+ }
142
+ }
143
+
144
+ func observe(hist *prometheus.HistogramVec, fullMethod string, err error, duration time.Duration) {
145
+ service, method := splitFullMethodName(fullMethod)
146
+
147
+ // `hist` has following labels
148
+ // service - gRPC service name (e.g: weaviate.v1.Weaviate, weaviate.internal.cluster.ClusterService)
149
+ // method - Method from the gRPC service that got invoked. (e.g: Search, RemovePeer)
150
+ // status - grpc status (e.g: "OK", "CANCELED", "UNKNOWN", etc)
151
+
152
+ labelValues := []string{
153
+ service,
154
+ method,
155
+ errorToStatus(err),
156
+ }
157
+ hist.WithLabelValues(labelValues...).Observe(duration.Seconds())
158
+ }
159
+
160
+ func errorToStatus(err error) string {
161
+ code := errorToGrpcCode(err)
162
+ return code.String()
163
+ }
164
+
165
+ func errorToGrpcCode(err error) codes.Code {
166
+ if err == nil {
167
+ return codes.OK
168
+ }
169
+
170
+ if errors.Is(err, context.Canceled) {
171
+ return codes.Canceled
172
+ }
173
+
174
+ type grpcStatus interface {
175
+ GRPCStatus() *status.Status
176
+ }
177
+
178
+ var g grpcStatus
179
+ if errors.As(err, &g) {
180
+ st := g.GRPCStatus()
181
+ if st != nil {
182
+ return st.Code()
183
+ }
184
+ }
185
+ return codes.Unknown
186
+ }
187
+
188
+ // splitFullMethodName converts full gRPC method call into `service` and `method`
189
+ // e.g: "/weaviate.v1.Weaviate/Search" -> "weaviate.v1.Weaviate", "/Search"
190
+ func splitFullMethodName(fullMethod string) (string, string) {
191
+ fullMethod = strings.TrimPrefix(fullMethod, "/") // remove leading slash
192
+ if i := strings.Index(fullMethod, "/"); i >= 0 {
193
+ return fullMethod[:i], fullMethod[i+1:]
194
+ }
195
+ return "unknown", "unknown"
196
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/http.go ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import (
15
+ "io"
16
+ "net/http"
17
+ "strconv"
18
+
19
+ "github.com/felixge/httpsnoop"
20
+ "github.com/prometheus/client_golang/prometheus"
21
+ )
22
+
23
+ // StaticRouteLabel takes any http request and return canonical and static route label
24
+ // that can used in metrics without worrying about unbounded cardinality.
25
+
26
+ // Examples:
27
+ // `/schema/Movies/properties` -> `/schema/{className}`
28
+ // `/replicas/indices/Movies/shards/hello0/objects` -> `/replicas/indices`
29
+ type StaticRouteLabel func(r *http.Request) (*http.Request, string)
30
+
31
+ type InstrumentHandler struct {
32
+ inflightRequests *prometheus.GaugeVec
33
+ duration *prometheus.HistogramVec
34
+
35
+ // in bytes
36
+ requestSize *prometheus.HistogramVec
37
+ responseSize *prometheus.HistogramVec
38
+
39
+ // next is original http handler we instrument
40
+ next http.Handler
41
+
42
+ routeLabel StaticRouteLabel
43
+ }
44
+
45
+ func InstrumentHTTP(
46
+ next http.Handler,
47
+ routeLabel StaticRouteLabel,
48
+ inflight *prometheus.GaugeVec,
49
+ duration *prometheus.HistogramVec,
50
+ requestSize *prometheus.HistogramVec,
51
+ responseSize *prometheus.HistogramVec,
52
+ ) *InstrumentHandler {
53
+ return &InstrumentHandler{
54
+ next: next,
55
+ routeLabel: routeLabel,
56
+ inflightRequests: inflight,
57
+ duration: duration,
58
+ requestSize: requestSize,
59
+ responseSize: responseSize,
60
+ }
61
+ }
62
+
63
+ func (i *InstrumentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
64
+ r, route := i.routeLabel(r)
65
+ method := r.Method
66
+
67
+ inflight := i.inflightRequests.WithLabelValues(method, route)
68
+ inflight.Inc()
69
+ defer inflight.Dec()
70
+
71
+ origBody := r.Body
72
+ defer func() {
73
+ // We don't need `countingReadCloser` before this instrument handler
74
+ r.Body = origBody
75
+ }()
76
+
77
+ cr := &countingReadCloser{
78
+ r: r.Body,
79
+ }
80
+ r.Body = cr
81
+
82
+ // This is where we run actual upstream http.Handler
83
+ respWithMetrics := httpsnoop.CaptureMetricsFn(w, func(rw http.ResponseWriter) {
84
+ i.next.ServeHTTP(rw, r)
85
+ })
86
+
87
+ i.requestSize.WithLabelValues(method, route).Observe(float64(cr.read))
88
+ i.responseSize.WithLabelValues(method, route).Observe(float64(respWithMetrics.Written))
89
+
90
+ labelValues := []string{
91
+ method,
92
+ route,
93
+ strconv.Itoa(respWithMetrics.Code),
94
+ }
95
+
96
+ i.duration.WithLabelValues(labelValues...).Observe(respWithMetrics.Duration.Seconds())
97
+ }
98
+
99
+ type countingReadCloser struct {
100
+ r io.ReadCloser
101
+ read int64
102
+ }
103
+
104
+ func (c *countingReadCloser) Read(p []byte) (int, error) {
105
+ n, err := c.r.Read(p)
106
+ if n > 0 {
107
+ c.read += int64(n)
108
+ }
109
+ return n, err
110
+ }
111
+
112
+ func (c *countingReadCloser) Close() error {
113
+ return c.r.Close()
114
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/listen.go ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import (
15
+ "net"
16
+ "sync"
17
+
18
+ "github.com/prometheus/client_golang/prometheus"
19
+ )
20
+
21
+ type countingListener struct {
22
+ net.Listener
23
+ count prometheus.Gauge
24
+ }
25
+
26
+ func CountingListener(l net.Listener, g prometheus.Gauge) net.Listener {
27
+ return &countingListener{Listener: l, count: g}
28
+ }
29
+
30
+ func (c *countingListener) Accept() (net.Conn, error) {
31
+ conn, err := c.Listener.Accept()
32
+ if err != nil {
33
+ return nil, err
34
+ }
35
+ c.count.Inc()
36
+ return &countingConn{Conn: conn, count: c.count}, nil
37
+ }
38
+
39
+ type countingConn struct {
40
+ net.Conn
41
+ count prometheus.Gauge
42
+ once sync.Once
43
+ }
44
+
45
+ func (c *countingConn) Close() error {
46
+ err := c.Conn.Close()
47
+
48
+ // Client can call `Close()` any number of times on a single connection. Make sure to decrement the counter only once.
49
+ c.once.Do(func() {
50
+ c.count.Dec()
51
+ })
52
+
53
+ return err
54
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/listen_test.go ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import (
15
+ "errors"
16
+ "net"
17
+ "testing"
18
+
19
+ "github.com/prometheus/client_golang/prometheus"
20
+ "github.com/prometheus/client_golang/prometheus/promauto"
21
+ "github.com/prometheus/client_golang/prometheus/testutil"
22
+ "github.com/stretchr/testify/assert"
23
+ )
24
+
25
+ type fakeListener struct {
26
+ net.Listener
27
+ acceptErr error
28
+ closeErr error
29
+ }
30
+
31
+ type fakeConn struct {
32
+ net.Conn
33
+ closeErr error
34
+ }
35
+
36
+ func (c *fakeConn) Close() error {
37
+ return c.closeErr
38
+ }
39
+
40
+ func (c *fakeListener) Accept() (net.Conn, error) {
41
+ return &fakeConn{closeErr: c.closeErr}, c.acceptErr
42
+ }
43
+
44
+ func TestCountingListener(t *testing.T) {
45
+ reg := prometheus.NewPedanticRegistry()
46
+ g := promauto.With(reg).NewGauge(prometheus.GaugeOpts{
47
+ Namespace: "test",
48
+ Name: "gauge",
49
+ })
50
+
51
+ fake := &fakeListener{}
52
+ l := CountingListener(fake, g)
53
+ assert.Equal(t, float64(0), testutil.ToFloat64(g))
54
+
55
+ // Accepting connections should increment the gauge.
56
+ c1, err := l.Accept()
57
+ assert.NoError(t, err)
58
+ assert.Equal(t, float64(1), testutil.ToFloat64(g))
59
+ c2, err := l.Accept()
60
+ assert.NoError(t, err)
61
+ assert.Equal(t, float64(2), testutil.ToFloat64(g))
62
+
63
+ // Closing connections should decrement the gauge.
64
+ assert.NoError(t, c1.Close())
65
+ assert.Equal(t, float64(1), testutil.ToFloat64(g))
66
+ assert.NoError(t, c2.Close())
67
+ assert.Equal(t, float64(0), testutil.ToFloat64(g))
68
+
69
+ // Duplicate calls to Close should not decrement.
70
+ assert.NoError(t, c1.Close())
71
+ assert.Equal(t, float64(0), testutil.ToFloat64(g))
72
+
73
+ // Accept errors should not cause an increment.
74
+ fake.acceptErr = errors.New("accept")
75
+ _, err = l.Accept()
76
+ assert.Error(t, err)
77
+ assert.Equal(t, float64(0), testutil.ToFloat64(g))
78
+
79
+ // Close errors should still decrement.
80
+ fake.acceptErr = nil
81
+ fake.closeErr = errors.New("close")
82
+ c3, err := l.Accept()
83
+ assert.NoError(t, err)
84
+ assert.Equal(t, float64(1), testutil.ToFloat64(g))
85
+ assert.Error(t, c3.Close())
86
+ assert.Equal(t, float64(0), testutil.ToFloat64(g))
87
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/noop.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import "github.com/prometheus/client_golang/prometheus"
15
+
16
+ // NoopRegisterer is a no-op Prometheus register.
17
+ var NoopRegisterer prometheus.Registerer = noopRegisterer{}
18
+
19
+ type noopRegisterer struct{}
20
+
21
+ func (n noopRegisterer) Register(_ prometheus.Collector) error { return nil }
22
+
23
+ func (n noopRegisterer) MustRegister(_ ...prometheus.Collector) {}
24
+
25
+ func (n noopRegisterer) Unregister(_ prometheus.Collector) bool { return true }
platform/dbops/binaries/weaviate-src/usecases/monitoring/prometheus.go ADDED
@@ -0,0 +1,876 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import (
15
+ "sync"
16
+
17
+ "github.com/prometheus/client_golang/prometheus"
18
+ "github.com/prometheus/client_golang/prometheus/promauto"
19
+ )
20
+
21
+ const (
22
+ DefaultMetricsNamespace = "weaviate"
23
+ )
24
+
25
+ type Config struct {
26
+ Enabled bool `json:"enabled" yaml:"enabled" long:"enabled"`
27
+ Tool string `json:"tool" yaml:"tool"`
28
+ Port int `json:"port" yaml:"port" long:"port" default:"8081"`
29
+ Group bool `json:"group_classes" yaml:"group_classes"`
30
+ MonitorCriticalBucketsOnly bool `json:"monitor_critical_buckets_only" yaml:"monitor_critical_buckets_only"`
31
+
32
+ // Metrics namespace group the metrics with common prefix.
33
+ MetricsNamespace string `json:"metrics_namespace" yaml:"metrics_namespace" long:"metrics_namespace" default:""`
34
+ }
35
+
36
+ // NOTE: Do not add any new metrics to this global `PrometheusMetrics` struct.
37
+ // Instead add your metrics close the corresponding component.
38
+ type PrometheusMetrics struct {
39
+ Registerer prometheus.Registerer
40
+
41
+ BatchTime *prometheus.HistogramVec
42
+ BatchSizeBytes *prometheus.SummaryVec
43
+ BatchSizeObjects prometheus.Summary
44
+ BatchSizeTenants prometheus.Summary
45
+ BatchDeleteTime *prometheus.SummaryVec
46
+ BatchCount *prometheus.CounterVec
47
+ BatchCountBytes *prometheus.CounterVec
48
+ ObjectsTime *prometheus.SummaryVec
49
+ LSMBloomFilters *prometheus.SummaryVec
50
+ AsyncOperations *prometheus.GaugeVec
51
+ LSMSegmentCount *prometheus.GaugeVec
52
+ LSMObjectsBucketSegmentCount *prometheus.GaugeVec
53
+ LSMCompressedVecsBucketSegmentCount *prometheus.GaugeVec
54
+ LSMSegmentCountByLevel *prometheus.GaugeVec
55
+ LSMSegmentUnloaded *prometheus.GaugeVec
56
+ LSMSegmentObjects *prometheus.GaugeVec
57
+ LSMSegmentSize *prometheus.GaugeVec
58
+ LSMMemtableSize *prometheus.GaugeVec
59
+ LSMMemtableDurations *prometheus.SummaryVec
60
+ LSMBitmapBuffersUsage *prometheus.CounterVec
61
+ ObjectCount *prometheus.GaugeVec
62
+ QueriesCount *prometheus.GaugeVec
63
+ RequestsTotal *prometheus.GaugeVec
64
+ QueriesDurations *prometheus.HistogramVec
65
+ QueriesFilteredVectorDurations *prometheus.SummaryVec
66
+ QueryDimensions *prometheus.CounterVec
67
+ QueryDimensionsCombined prometheus.Counter
68
+ GoroutinesCount *prometheus.GaugeVec
69
+ BackupRestoreDurations *prometheus.SummaryVec
70
+ BackupStoreDurations *prometheus.SummaryVec
71
+ BucketPauseDurations *prometheus.SummaryVec
72
+ BackupRestoreClassDurations *prometheus.SummaryVec
73
+ BackupRestoreBackupInitDurations *prometheus.SummaryVec
74
+ BackupRestoreFromStorageDurations *prometheus.SummaryVec
75
+ BackupRestoreDataTransferred *prometheus.CounterVec
76
+ BackupStoreDataTransferred *prometheus.CounterVec
77
+ FileIOWrites *prometheus.SummaryVec
78
+ FileIOReads *prometheus.SummaryVec
79
+ MmapOperations *prometheus.CounterVec
80
+ MmapProcMaps prometheus.Gauge
81
+
82
+ // offload metric
83
+ QueueSize *prometheus.GaugeVec
84
+ QueueDiskUsage *prometheus.GaugeVec
85
+ QueuePaused *prometheus.GaugeVec
86
+ QueueCount *prometheus.GaugeVec
87
+ QueuePartitionProcessingDuration *prometheus.HistogramVec
88
+
89
+ VectorIndexQueueInsertCount *prometheus.CounterVec
90
+ VectorIndexQueueDeleteCount *prometheus.CounterVec
91
+
92
+ VectorIndexTombstones *prometheus.GaugeVec
93
+ VectorIndexTombstoneCleanupThreads *prometheus.GaugeVec
94
+ VectorIndexTombstoneCleanedCount *prometheus.CounterVec
95
+ VectorIndexTombstoneUnexpected *prometheus.CounterVec
96
+ VectorIndexTombstoneCycleStart *prometheus.GaugeVec
97
+ VectorIndexTombstoneCycleEnd *prometheus.GaugeVec
98
+ VectorIndexTombstoneCycleProgress *prometheus.GaugeVec
99
+ VectorIndexOperations *prometheus.GaugeVec
100
+ VectorIndexDurations *prometheus.SummaryVec
101
+ VectorIndexSize *prometheus.GaugeVec
102
+ VectorIndexMaintenanceDurations *prometheus.SummaryVec
103
+ VectorDimensionsSum *prometheus.GaugeVec
104
+ VectorSegmentsSum *prometheus.GaugeVec
105
+
106
+ StartupProgress *prometheus.GaugeVec
107
+ StartupDurations *prometheus.SummaryVec
108
+ StartupDiskIO *prometheus.SummaryVec
109
+
110
+ ShardsLoaded prometheus.Gauge
111
+ ShardsUnloaded prometheus.Gauge
112
+ ShardsLoading prometheus.Gauge
113
+ ShardsUnloading prometheus.Gauge
114
+
115
+ // RAFT-based schema metrics
116
+ SchemaWrites *prometheus.SummaryVec
117
+ SchemaReadsLocal *prometheus.SummaryVec
118
+ SchemaReadsLeader *prometheus.SummaryVec
119
+ SchemaWaitForVersion *prometheus.SummaryVec
120
+
121
+ TombstoneFindLocalEntrypoint *prometheus.CounterVec
122
+ TombstoneFindGlobalEntrypoint *prometheus.CounterVec
123
+ TombstoneReassignNeighbors *prometheus.CounterVec
124
+ TombstoneDeleteListSize *prometheus.GaugeVec
125
+
126
+ Group bool
127
+ // Keeping metering to only the critical buckets (objects, vectors_compressed)
128
+ // helps cut down on noise when monitoring
129
+ LSMCriticalBucketsOnly bool
130
+
131
+ // Deprecated metrics, keeping around because the classification features
132
+ // seems to sill use the old logic. However, those metrics are not actually
133
+ // used for the schema anymore, but only for the classification features.
134
+ SchemaTxOpened *prometheus.CounterVec
135
+ SchemaTxClosed *prometheus.CounterVec
136
+ SchemaTxDuration *prometheus.SummaryVec
137
+
138
+ // Vectorization
139
+ T2VBatches *prometheus.GaugeVec
140
+ T2VBatchQueueDuration *prometheus.HistogramVec
141
+ T2VRequestDuration *prometheus.HistogramVec
142
+ T2VTokensInBatch *prometheus.HistogramVec
143
+ T2VTokensInRequest *prometheus.HistogramVec
144
+ T2VRateLimitStats *prometheus.GaugeVec
145
+ T2VRepeatStats *prometheus.GaugeVec
146
+ T2VRequestsPerBatch *prometheus.HistogramVec
147
+
148
+ TokenizerDuration *prometheus.HistogramVec
149
+ TokenizerRequests *prometheus.CounterVec
150
+ TokenizerInitializeDuration *prometheus.HistogramVec
151
+ TokenCount *prometheus.CounterVec
152
+ TokenCountPerRequest *prometheus.HistogramVec
153
+
154
+ // Currently targeted at OpenAI, the metrics will have to be added to every vectorizer for complete coverage
155
+ ModuleExternalRequests *prometheus.CounterVec
156
+ ModuleExternalRequestDuration *prometheus.HistogramVec
157
+ ModuleExternalBatchLength *prometheus.HistogramVec
158
+ ModuleExternalRequestSingleCount *prometheus.CounterVec
159
+ ModuleExternalRequestBatchCount *prometheus.CounterVec
160
+ ModuleExternalRequestSize *prometheus.HistogramVec
161
+ ModuleExternalResponseSize *prometheus.HistogramVec
162
+ ModuleExternalResponseStatus *prometheus.CounterVec
163
+ VectorizerRequestTokens *prometheus.HistogramVec
164
+ ModuleExternalError *prometheus.CounterVec
165
+ ModuleCallError *prometheus.CounterVec
166
+ ModuleBatchError *prometheus.CounterVec
167
+
168
+ // Checksum metrics
169
+ ChecksumValidationDuration prometheus.Summary
170
+ ChecksumBytesRead prometheus.Summary
171
+ }
172
+
173
+ func NewTenantOffloadMetrics(cfg Config, reg prometheus.Registerer) *TenantOffloadMetrics {
174
+ r := promauto.With(reg)
175
+ return &TenantOffloadMetrics{
176
+ FetchedBytes: r.NewCounter(prometheus.CounterOpts{
177
+ Namespace: cfg.MetricsNamespace,
178
+ Name: "tenant_offload_fetched_bytes_total",
179
+ }),
180
+ TransferredBytes: r.NewCounter(prometheus.CounterOpts{
181
+ Namespace: cfg.MetricsNamespace,
182
+ Name: "tenant_offload_transferred_bytes_total",
183
+ }),
184
+ OpsDuration: r.NewHistogramVec(prometheus.HistogramOpts{
185
+ Namespace: cfg.MetricsNamespace,
186
+ Name: "tenant_offload_operation_duration_seconds",
187
+ Buckets: LatencyBuckets,
188
+ }, []string{"operation", "status"}), // status can be "success" or "failure"
189
+ }
190
+ }
191
+
192
+ type TenantOffloadMetrics struct {
193
+ // NOTE: These ops are not GET or PUT requests to object storage.
194
+ // these are one of the `download`, `upload` or `delete`. Because we use s5cmd to talk
195
+ // to object storage currently. Which supports these operations at high level.
196
+ FetchedBytes prometheus.Counter
197
+ TransferredBytes prometheus.Counter
198
+ OpsDuration *prometheus.HistogramVec
199
+ }
200
+
201
+ // NewHTPServerMetrics return the ServerMetrics that can be used in any of the grpc or http servers.
202
+ func NewHTTPServerMetrics(namespace string, reg prometheus.Registerer) *HTTPServerMetrics {
203
+ r := promauto.With(reg)
204
+
205
+ return &HTTPServerMetrics{
206
+ RequestDuration: r.NewHistogramVec(prometheus.HistogramOpts{
207
+ Namespace: namespace,
208
+ Name: "http_request_duration_seconds",
209
+ Help: "Time (in seconds) spent serving requests.",
210
+ Buckets: LatencyBuckets,
211
+ }, []string{"method", "route", "status_code"}),
212
+ RequestBodySize: r.NewHistogramVec(prometheus.HistogramOpts{
213
+ Namespace: namespace,
214
+ Name: "http_request_size_bytes",
215
+ Help: "Size (in bytes) of the request received.",
216
+ Buckets: sizeBuckets,
217
+ }, []string{"method", "route"}),
218
+ ResponseBodySize: r.NewHistogramVec(prometheus.HistogramOpts{
219
+ Namespace: namespace,
220
+ Name: "http_response_size_bytes",
221
+ Help: "Size (in bytes) of the response sent.",
222
+ Buckets: sizeBuckets,
223
+ }, []string{"method", "route"}),
224
+ InflightRequests: r.NewGaugeVec(prometheus.GaugeOpts{
225
+ Namespace: namespace,
226
+ Name: "http_requests_inflight",
227
+ Help: "Current number of inflight requests.",
228
+ }, []string{"method", "route"}),
229
+ }
230
+ }
231
+
232
+ // HTTPServerMetrics exposes set of prometheus metrics for http servers.
233
+ type HTTPServerMetrics struct {
234
+ TCPActiveConnections *prometheus.GaugeVec
235
+ RequestDuration *prometheus.HistogramVec
236
+ RequestBodySize *prometheus.HistogramVec
237
+ ResponseBodySize *prometheus.HistogramVec
238
+ InflightRequests *prometheus.GaugeVec
239
+ }
240
+
241
+ // GRPCServerMetrics exposes set of prometheus metrics for grpc servers.
242
+ type GRPCServerMetrics struct {
243
+ RequestDuration *prometheus.HistogramVec
244
+ RequestBodySize *prometheus.HistogramVec
245
+ ResponseBodySize *prometheus.HistogramVec
246
+ InflightRequests *prometheus.GaugeVec
247
+ }
248
+
249
+ func NewGRPCServerMetrics(namespace string, reg prometheus.Registerer) *GRPCServerMetrics {
250
+ r := promauto.With(reg)
251
+ return &GRPCServerMetrics{
252
+ RequestDuration: r.NewHistogramVec(prometheus.HistogramOpts{
253
+ Namespace: namespace,
254
+ Name: "grpc_server_request_duration_seconds",
255
+ Help: "Time (in seconds) spent serving requests.",
256
+ Buckets: LatencyBuckets,
257
+ }, []string{"grpc_service", "method", "status"}),
258
+ RequestBodySize: r.NewHistogramVec(prometheus.HistogramOpts{
259
+ Namespace: namespace,
260
+ Name: "grpc_server_request_size_bytes",
261
+ Help: "Size (in bytes) of the request received.",
262
+ Buckets: sizeBuckets,
263
+ }, []string{"grpc_service", "method"}),
264
+ ResponseBodySize: r.NewHistogramVec(prometheus.HistogramOpts{
265
+ Namespace: namespace,
266
+ Name: "grpc_server_response_size_bytes",
267
+ Help: "Size (in bytes) of the response sent.",
268
+ Buckets: sizeBuckets,
269
+ }, []string{"grpc_service", "method"}),
270
+ InflightRequests: r.NewGaugeVec(prometheus.GaugeOpts{
271
+ Namespace: namespace,
272
+ Name: "grpc_server_requests_inflight",
273
+ Help: "Current number of inflight requests.",
274
+ }, []string{"grpc_service", "method"}),
275
+ }
276
+ }
277
+
278
+ // Delete Shard deletes existing label combinations that match both
279
+ // the shard and class name. If a metric is not collected at the shard
280
+ // level it is unaffected. This is to make sure that deleting a single
281
+ // shard (e.g. multi-tenancy) does not affect metrics for existing
282
+ // shards.
283
+ //
284
+ // In addition, there are some metrics that we explicitly keep, such
285
+ // as vector_dimensions_sum as they can be used in billing decisions.
286
+ func (pm *PrometheusMetrics) DeleteShard(className, shardName string) error {
287
+ if pm == nil {
288
+ return nil
289
+ }
290
+
291
+ labels := prometheus.Labels{
292
+ "class_name": className,
293
+ "shard_name": shardName,
294
+ }
295
+ pm.BatchTime.DeletePartialMatch(labels)
296
+ pm.BatchDeleteTime.DeletePartialMatch(labels)
297
+ pm.ObjectsTime.DeletePartialMatch(labels)
298
+ pm.ObjectCount.DeletePartialMatch(labels)
299
+ pm.QueriesFilteredVectorDurations.DeletePartialMatch(labels)
300
+ pm.AsyncOperations.DeletePartialMatch(labels)
301
+ pm.LSMBloomFilters.DeletePartialMatch(labels)
302
+ pm.LSMMemtableDurations.DeletePartialMatch(labels)
303
+ pm.LSMMemtableSize.DeletePartialMatch(labels)
304
+ pm.LSMMemtableDurations.DeletePartialMatch(labels)
305
+ pm.LSMSegmentCount.DeletePartialMatch(labels)
306
+ pm.LSMSegmentSize.DeletePartialMatch(labels)
307
+ pm.LSMSegmentCountByLevel.DeletePartialMatch(labels)
308
+ pm.QueueSize.DeletePartialMatch(labels)
309
+ pm.QueueDiskUsage.DeletePartialMatch(labels)
310
+ pm.QueuePaused.DeletePartialMatch(labels)
311
+ pm.QueueCount.DeletePartialMatch(labels)
312
+ pm.QueuePartitionProcessingDuration.DeletePartialMatch(labels)
313
+ pm.VectorIndexQueueInsertCount.DeletePartialMatch(labels)
314
+ pm.VectorIndexQueueDeleteCount.DeletePartialMatch(labels)
315
+ pm.VectorIndexTombstones.DeletePartialMatch(labels)
316
+ pm.VectorIndexTombstoneCleanupThreads.DeletePartialMatch(labels)
317
+ pm.VectorIndexTombstoneCleanedCount.DeletePartialMatch(labels)
318
+ pm.VectorIndexTombstoneUnexpected.DeletePartialMatch(labels)
319
+ pm.VectorIndexTombstoneCycleStart.DeletePartialMatch(labels)
320
+ pm.VectorIndexTombstoneCycleEnd.DeletePartialMatch(labels)
321
+ pm.VectorIndexTombstoneCycleProgress.DeletePartialMatch(labels)
322
+ pm.VectorIndexOperations.DeletePartialMatch(labels)
323
+ pm.VectorIndexMaintenanceDurations.DeletePartialMatch(labels)
324
+ pm.VectorIndexDurations.DeletePartialMatch(labels)
325
+ pm.VectorIndexSize.DeletePartialMatch(labels)
326
+ pm.StartupProgress.DeletePartialMatch(labels)
327
+ pm.StartupDurations.DeletePartialMatch(labels)
328
+ pm.StartupDiskIO.DeletePartialMatch(labels)
329
+ return nil
330
+ }
331
+
332
+ // DeleteClass deletes all metrics that match the class name, but do
333
+ // not have a shard-specific label. See [DeleteShard] for more
334
+ // information.
335
+ func (pm *PrometheusMetrics) DeleteClass(className string) error {
336
+ if pm == nil {
337
+ return nil
338
+ }
339
+
340
+ labels := prometheus.Labels{
341
+ "class_name": className,
342
+ }
343
+ pm.QueriesCount.DeletePartialMatch(labels)
344
+ pm.QueriesDurations.DeletePartialMatch(labels)
345
+ pm.GoroutinesCount.DeletePartialMatch(labels)
346
+ pm.BackupRestoreClassDurations.DeletePartialMatch(labels)
347
+ pm.BackupRestoreBackupInitDurations.DeletePartialMatch(labels)
348
+ pm.BackupRestoreFromStorageDurations.DeletePartialMatch(labels)
349
+ pm.BackupStoreDurations.DeletePartialMatch(labels)
350
+ pm.BackupRestoreDataTransferred.DeletePartialMatch(labels)
351
+ pm.BackupStoreDataTransferred.DeletePartialMatch(labels)
352
+ pm.QueriesFilteredVectorDurations.DeletePartialMatch(labels)
353
+
354
+ return nil
355
+ }
356
+
357
+ const mb = 1024 * 1024
358
+
359
+ var (
360
+ // msBuckets and sBuckets are deprecated. Use `LatencyBuckets` and `sizeBuckets` instead.
361
+ msBuckets = []float64{10, 50, 100, 500, 1000, 5000, 10000, 60000, 300000}
362
+ sBuckets = []float64{0.01, 0.1, 1, 10, 20, 30, 60, 120, 180, 500}
363
+
364
+ // LatencyBuckets is default histogram bucket for response time (in seconds).
365
+ // It also includes request that served *very* fast and *very* slow
366
+ LatencyBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 25, 50, 100}
367
+
368
+ // sizeBuckets defines buckets for request/response body sizes (in bytes).
369
+ // TODO(kavi): Check with real data once deployed on prod and tweak accordingly.
370
+ sizeBuckets = []float64{1 * mb, 2.5 * mb, 5 * mb, 10 * mb, 25 * mb, 50 * mb, 100 * mb, 250 * mb}
371
+
372
+ metrics *PrometheusMetrics = nil
373
+ )
374
+
375
+ func init() {
376
+ metrics = newPrometheusMetrics()
377
+ }
378
+
379
+ func InitConfig(cfg Config) {
380
+ metrics.Group = cfg.Group
381
+ metrics.LSMCriticalBucketsOnly = cfg.MonitorCriticalBucketsOnly
382
+ }
383
+
384
+ func GetMetrics() *PrometheusMetrics {
385
+ return metrics
386
+ }
387
+
388
+ func newPrometheusMetrics() *PrometheusMetrics {
389
+ return &PrometheusMetrics{
390
+ Registerer: prometheus.DefaultRegisterer,
391
+ BatchTime: promauto.NewHistogramVec(prometheus.HistogramOpts{
392
+ Name: "batch_durations_ms",
393
+ Help: "Duration in ms of a single batch",
394
+ Buckets: msBuckets,
395
+ }, []string{"operation", "class_name", "shard_name"}),
396
+ BatchSizeBytes: promauto.NewSummaryVec(prometheus.SummaryOpts{
397
+ Name: "batch_size_bytes",
398
+ Help: "Size of a raw batch request batch in bytes",
399
+ }, []string{"api"}),
400
+ BatchSizeObjects: promauto.NewSummary(prometheus.SummaryOpts{
401
+ Name: "batch_size_objects",
402
+ Help: "Number of objects in a batch",
403
+ }),
404
+ BatchSizeTenants: promauto.NewSummary(prometheus.SummaryOpts{
405
+ Name: "batch_size_tenants",
406
+ Help: "Number of unique tenants referenced in a batch",
407
+ }),
408
+
409
+ BatchDeleteTime: promauto.NewSummaryVec(prometheus.SummaryOpts{
410
+ Name: "batch_delete_durations_ms",
411
+ Help: "Duration in ms of a single delete batch",
412
+ }, []string{"operation", "class_name", "shard_name"}),
413
+
414
+ BatchCount: promauto.NewCounterVec(prometheus.CounterOpts{
415
+ Name: "batch_objects_processed_total",
416
+ Help: "Number of objects processed in a batch",
417
+ }, []string{"class_name", "shard_name"}),
418
+
419
+ BatchCountBytes: promauto.NewCounterVec(prometheus.CounterOpts{
420
+ Name: "batch_objects_processed_bytes",
421
+ Help: "Number of bytes processed in a batch",
422
+ }, []string{"class_name", "shard_name"}),
423
+
424
+ ObjectsTime: promauto.NewSummaryVec(prometheus.SummaryOpts{
425
+ Name: "objects_durations_ms",
426
+ Help: "Duration of an individual object operation. Also as part of batches.",
427
+ }, []string{"operation", "step", "class_name", "shard_name"}),
428
+ ObjectCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
429
+ Name: "object_count",
430
+ Help: "Number of currently ongoing async operations",
431
+ }, []string{"class_name", "shard_name"}),
432
+
433
+ QueriesCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
434
+ Name: "concurrent_queries_count",
435
+ Help: "Number of concurrently running query operations",
436
+ }, []string{"class_name", "query_type"}),
437
+
438
+ RequestsTotal: promauto.NewGaugeVec(prometheus.GaugeOpts{
439
+ Name: "requests_total",
440
+ Help: "Number of all requests made",
441
+ }, []string{"status", "class_name", "api", "query_type"}),
442
+
443
+ QueriesDurations: promauto.NewHistogramVec(prometheus.HistogramOpts{
444
+ Name: "queries_durations_ms",
445
+ Help: "Duration of queries in milliseconds",
446
+ Buckets: msBuckets,
447
+ }, []string{"class_name", "query_type"}),
448
+
449
+ QueriesFilteredVectorDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
450
+ Name: "queries_filtered_vector_durations_ms",
451
+ Help: "Duration of queries in milliseconds",
452
+ }, []string{"class_name", "shard_name", "operation"}),
453
+
454
+ GoroutinesCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
455
+ Name: "concurrent_goroutines",
456
+ Help: "Number of concurrently running goroutines",
457
+ }, []string{"class_name", "query_type"}),
458
+
459
+ AsyncOperations: promauto.NewGaugeVec(prometheus.GaugeOpts{
460
+ Name: "async_operations_running",
461
+ Help: "Number of currently ongoing async operations",
462
+ }, []string{"operation", "class_name", "shard_name", "path"}),
463
+
464
+ // LSM metrics
465
+ LSMSegmentCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
466
+ Name: "lsm_active_segments",
467
+ Help: "Number of currently present segments per shard",
468
+ }, []string{"strategy", "class_name", "shard_name", "path"}),
469
+ LSMObjectsBucketSegmentCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
470
+ Name: "lsm_objects_bucket_segment_count",
471
+ Help: "Number of segments per shard in the objects bucket",
472
+ }, []string{"strategy", "class_name", "shard_name", "path"}),
473
+ LSMCompressedVecsBucketSegmentCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
474
+ Name: "lsm_compressed_vecs_bucket_segment_count",
475
+ Help: "Number of segments per shard in the vectors_compressed bucket",
476
+ }, []string{"strategy", "class_name", "shard_name", "path"}),
477
+ LSMBloomFilters: promauto.NewSummaryVec(prometheus.SummaryOpts{
478
+ Name: "lsm_bloom_filters_duration_ms",
479
+ Help: "Duration of bloom filter operations",
480
+ }, []string{"operation", "strategy", "class_name", "shard_name"}),
481
+ LSMSegmentObjects: promauto.NewGaugeVec(prometheus.GaugeOpts{
482
+ Name: "lsm_segment_objects",
483
+ Help: "Number of objects/entries of segment by level",
484
+ }, []string{"strategy", "class_name", "shard_name", "path", "level"}),
485
+ LSMSegmentSize: promauto.NewGaugeVec(prometheus.GaugeOpts{
486
+ Name: "lsm_segment_size",
487
+ Help: "Size of segment by level and unit",
488
+ }, []string{"strategy", "class_name", "shard_name", "path", "level", "unit"}),
489
+ LSMSegmentCountByLevel: promauto.NewGaugeVec(prometheus.GaugeOpts{
490
+ Name: "lsm_segment_count",
491
+ Help: "Number of segments by level",
492
+ }, []string{"strategy", "class_name", "shard_name", "path", "level"}),
493
+ LSMSegmentUnloaded: promauto.NewGaugeVec(prometheus.GaugeOpts{
494
+ Name: "lsm_segment_unloaded",
495
+ Help: "Number of unloaded segments",
496
+ }, []string{"strategy", "class_name", "shard_name", "path"}),
497
+ LSMMemtableSize: promauto.NewGaugeVec(prometheus.GaugeOpts{
498
+ Name: "lsm_memtable_size",
499
+ Help: "Size of memtable by path",
500
+ }, []string{"strategy", "class_name", "shard_name", "path"}),
501
+ LSMMemtableDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
502
+ Name: "lsm_memtable_durations_ms",
503
+ Help: "Time in ms for a bucket operation to complete",
504
+ }, []string{"strategy", "class_name", "shard_name", "path", "operation"}),
505
+ LSMBitmapBuffersUsage: promauto.NewCounterVec(prometheus.CounterOpts{
506
+ Name: "lsm_bitmap_buffers_usage",
507
+ Help: "Number of bitmap buffers used by size",
508
+ }, []string{"size", "operation"}),
509
+ FileIOWrites: promauto.NewSummaryVec(prometheus.SummaryOpts{
510
+ Name: "file_io_writes_total_bytes",
511
+ Help: "Total number of bytes written to disk",
512
+ }, []string{"operation", "strategy"}),
513
+ FileIOReads: promauto.NewSummaryVec(prometheus.SummaryOpts{
514
+ Name: "file_io_reads_total_bytes",
515
+ Help: "Total number of bytes read from disk",
516
+ }, []string{"operation"}),
517
+ MmapOperations: promauto.NewCounterVec(prometheus.CounterOpts{
518
+ Name: "mmap_operations_total",
519
+ Help: "Total number of mmap operations",
520
+ }, []string{"operation", "strategy"}),
521
+ MmapProcMaps: promauto.NewGauge(prometheus.GaugeOpts{
522
+ Name: "mmap_proc_maps",
523
+ Help: "Number of entries in /proc/self/maps",
524
+ }),
525
+
526
+ // Queue metrics
527
+ QueueSize: promauto.NewGaugeVec(prometheus.GaugeOpts{
528
+ Name: "queue_size",
529
+ Help: "Number of records in the queue",
530
+ }, []string{"class_name", "shard_name"}),
531
+ QueueDiskUsage: promauto.NewGaugeVec(prometheus.GaugeOpts{
532
+ Name: "queue_disk_usage",
533
+ Help: "Disk usage of the queue",
534
+ }, []string{"class_name", "shard_name"}),
535
+ QueuePaused: promauto.NewGaugeVec(prometheus.GaugeOpts{
536
+ Name: "queue_paused",
537
+ Help: "Whether the queue is paused",
538
+ }, []string{"class_name", "shard_name"}),
539
+ QueueCount: promauto.NewGaugeVec(prometheus.GaugeOpts{
540
+ Name: "queue_count",
541
+ Help: "Number of queues",
542
+ }, []string{"class_name", "shard_name"}),
543
+ QueuePartitionProcessingDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
544
+ Name: "queue_partition_processing_duration_ms",
545
+ Help: "Duration in ms of a single partition processing",
546
+ }, []string{"class_name", "shard_name"}),
547
+
548
+ // Async indexing metrics
549
+ VectorIndexQueueInsertCount: promauto.NewCounterVec(prometheus.CounterOpts{
550
+ Name: "vector_index_queue_insert_count",
551
+ Help: "Number of insert operations added to the vector index queue",
552
+ }, []string{"class_name", "shard_name", "target_vector"}),
553
+ VectorIndexQueueDeleteCount: promauto.NewCounterVec(prometheus.CounterOpts{
554
+ Name: "vector_index_queue_delete_count",
555
+ Help: "Number of delete operations added to the vector index queue",
556
+ }, []string{"class_name", "shard_name", "target_vector"}),
557
+
558
+ // Vector index metrics
559
+ VectorIndexTombstones: promauto.NewGaugeVec(prometheus.GaugeOpts{
560
+ Name: "vector_index_tombstones",
561
+ Help: "Number of active vector index tombstones",
562
+ }, []string{"class_name", "shard_name"}),
563
+ VectorIndexTombstoneCleanupThreads: promauto.NewGaugeVec(prometheus.GaugeOpts{
564
+ Name: "vector_index_tombstone_cleanup_threads",
565
+ Help: "Number of threads in use to clean up tombstones",
566
+ }, []string{"class_name", "shard_name"}),
567
+ VectorIndexTombstoneCleanedCount: promauto.NewCounterVec(prometheus.CounterOpts{
568
+ Name: "vector_index_tombstone_cleaned",
569
+ Help: "Total number of deleted objects that have been cleaned up",
570
+ }, []string{"class_name", "shard_name"}),
571
+ VectorIndexTombstoneUnexpected: promauto.NewCounterVec(prometheus.CounterOpts{
572
+ Name: "vector_index_tombstone_unexpected_total",
573
+ Help: "Total number of unexpected tombstones that were found, for example because a vector was not found for an existing id in the index",
574
+ }, []string{"class_name", "shard_name", "operation"}),
575
+ VectorIndexTombstoneCycleStart: promauto.NewGaugeVec(prometheus.GaugeOpts{
576
+ Name: "vector_index_tombstone_cycle_start_timestamp_seconds",
577
+ Help: "Unix epoch timestamp of the start of the current tombstone cleanup cycle",
578
+ }, []string{"class_name", "shard_name"}),
579
+ VectorIndexTombstoneCycleEnd: promauto.NewGaugeVec(prometheus.GaugeOpts{
580
+ Name: "vector_index_tombstone_cycle_end_timestamp_seconds",
581
+ Help: "Unix epoch timestamp of the end of the last tombstone cleanup cycle. A negative value indicates that the cycle is still running",
582
+ }, []string{"class_name", "shard_name"}),
583
+ VectorIndexTombstoneCycleProgress: promauto.NewGaugeVec(prometheus.GaugeOpts{
584
+ Name: "vector_index_tombstone_cycle_progress",
585
+ Help: "A ratio (percentage) of the progress of the current tombstone cleanup cycle. 0 indicates the very beginning, 1 is a complete cycle.",
586
+ }, []string{"class_name", "shard_name"}),
587
+ VectorIndexOperations: promauto.NewGaugeVec(prometheus.GaugeOpts{
588
+ Name: "vector_index_operations",
589
+ Help: "Total number of mutating operations on the vector index",
590
+ }, []string{"operation", "class_name", "shard_name"}),
591
+ VectorIndexSize: promauto.NewGaugeVec(prometheus.GaugeOpts{
592
+ Name: "vector_index_size",
593
+ Help: "The size of the vector index. Typically larger than number of vectors, as it grows proactively.",
594
+ }, []string{"class_name", "shard_name"}),
595
+ VectorIndexMaintenanceDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
596
+ Name: "vector_index_maintenance_durations_ms",
597
+ Help: "Duration of a sync or async vector index maintenance operation",
598
+ }, []string{"operation", "class_name", "shard_name"}),
599
+ VectorIndexDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
600
+ Name: "vector_index_durations_ms",
601
+ Help: "Duration of typical vector index operations (insert, delete)",
602
+ }, []string{"operation", "step", "class_name", "shard_name"}),
603
+ VectorDimensionsSum: promauto.NewGaugeVec(prometheus.GaugeOpts{
604
+ Name: "vector_dimensions_sum",
605
+ Help: "Total dimensions in a shard",
606
+ }, []string{"class_name", "shard_name"}),
607
+ VectorSegmentsSum: promauto.NewGaugeVec(prometheus.GaugeOpts{
608
+ Name: "vector_segments_sum",
609
+ Help: "Total segments in a shard if quantization enabled",
610
+ }, []string{"class_name", "shard_name"}),
611
+
612
+ // Startup metrics
613
+ StartupProgress: promauto.NewGaugeVec(prometheus.GaugeOpts{
614
+ Name: "startup_progress",
615
+ Help: "A ratio (percentage) of startup progress for a particular component in a shard",
616
+ }, []string{"operation", "class_name", "shard_name"}),
617
+ StartupDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
618
+ Name: "startup_durations_ms",
619
+ Help: "Duration of individual startup operations in ms",
620
+ }, []string{"operation", "class_name", "shard_name"}),
621
+ StartupDiskIO: promauto.NewSummaryVec(prometheus.SummaryOpts{
622
+ Name: "startup_diskio_throughput",
623
+ Help: "Disk I/O throuhput in bytes per second",
624
+ }, []string{"operation", "class_name", "shard_name"}),
625
+ QueryDimensions: promauto.NewCounterVec(prometheus.CounterOpts{
626
+ Name: "query_dimensions_total",
627
+ Help: "The vector dimensions used by any read-query that involves vectors",
628
+ }, []string{"query_type", "operation", "class_name"}),
629
+ QueryDimensionsCombined: promauto.NewCounter(prometheus.CounterOpts{
630
+ Name: "query_dimensions_combined_total",
631
+ Help: "The vector dimensions used by any read-query that involves vectors, aggregated across all classes and shards. The sum of all labels for query_dimensions_total should always match this labelless metric",
632
+ }),
633
+
634
+ // Backup/restore metrics
635
+ BackupRestoreDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
636
+ Name: "backup_restore_ms",
637
+ Help: "Duration of a backup restore",
638
+ }, []string{"backend_name", "class_name"}),
639
+ BackupRestoreClassDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
640
+ Name: "backup_restore_class_ms",
641
+ Help: "Duration restoring class",
642
+ }, []string{"class_name"}),
643
+ BackupRestoreBackupInitDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
644
+ Name: "backup_restore_init_ms",
645
+ Help: "startup phase of a backup restore",
646
+ }, []string{"backend_name", "class_name"}),
647
+ BackupRestoreFromStorageDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
648
+ Name: "backup_restore_from_backend_ms",
649
+ Help: "file transfer stage of a backup restore",
650
+ }, []string{"backend_name", "class_name"}),
651
+ BackupStoreDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
652
+ Name: "backup_store_to_backend_ms",
653
+ Help: "file transfer stage of a backup restore",
654
+ }, []string{"backend_name", "class_name"}),
655
+ BucketPauseDurations: promauto.NewSummaryVec(prometheus.SummaryOpts{
656
+ Name: "bucket_pause_durations_ms",
657
+ Help: "bucket pause durations",
658
+ }, []string{"bucket_dir"}),
659
+ BackupRestoreDataTransferred: promauto.NewCounterVec(prometheus.CounterOpts{
660
+ Name: "backup_restore_data_transferred",
661
+ Help: "Total number of bytes transferred during a backup restore",
662
+ }, []string{"backend_name", "class_name"}),
663
+ BackupStoreDataTransferred: promauto.NewCounterVec(prometheus.CounterOpts{
664
+ Name: "backup_store_data_transferred",
665
+ Help: "Total number of bytes transferred during a backup store",
666
+ }, []string{"backend_name", "class_name"}),
667
+
668
+ // Shard metrics
669
+ ShardsLoaded: promauto.NewGauge(prometheus.GaugeOpts{
670
+ Name: "shards_loaded",
671
+ Help: "Number of shards loaded",
672
+ }),
673
+ ShardsUnloaded: promauto.NewGauge(prometheus.GaugeOpts{
674
+ Name: "shards_unloaded",
675
+ Help: "Number of shards on not loaded",
676
+ }),
677
+ ShardsLoading: promauto.NewGauge(prometheus.GaugeOpts{
678
+ Name: "shards_loading",
679
+ Help: "Number of shards in process of loading",
680
+ }),
681
+ ShardsUnloading: promauto.NewGauge(prometheus.GaugeOpts{
682
+ Name: "shards_unloading",
683
+ Help: "Number of shards in process of unloading",
684
+ }),
685
+
686
+ // Schema TX-metrics. Can be removed when RAFT is ready
687
+ SchemaTxOpened: promauto.NewCounterVec(prometheus.CounterOpts{
688
+ Name: "schema_tx_opened_total",
689
+ Help: "Total number of opened schema transactions",
690
+ }, []string{"ownership"}),
691
+ SchemaTxClosed: promauto.NewCounterVec(prometheus.CounterOpts{
692
+ Name: "schema_tx_closed_total",
693
+ Help: "Total number of closed schema transactions. A close must be either successful or failed",
694
+ }, []string{"ownership", "status"}),
695
+ SchemaTxDuration: promauto.NewSummaryVec(prometheus.SummaryOpts{
696
+ Name: "schema_tx_duration_seconds",
697
+ Help: "Mean duration of a tx by status",
698
+ }, []string{"ownership", "status"}),
699
+
700
+ // RAFT-based schema metrics
701
+ SchemaWrites: promauto.NewSummaryVec(prometheus.SummaryOpts{
702
+ Name: "schema_writes_seconds",
703
+ Help: "Duration of schema writes (which always involve the leader)",
704
+ }, []string{"type"}),
705
+ SchemaReadsLocal: promauto.NewSummaryVec(prometheus.SummaryOpts{
706
+ Name: "schema_reads_local_seconds",
707
+ Help: "Duration of local schema reads that do not involve the leader",
708
+ }, []string{"type"}),
709
+ SchemaReadsLeader: promauto.NewSummaryVec(prometheus.SummaryOpts{
710
+ Name: "schema_reads_leader_seconds",
711
+ Help: "Duration of schema reads that are passed to the leader",
712
+ }, []string{"type"}),
713
+ SchemaWaitForVersion: promauto.NewSummaryVec(prometheus.SummaryOpts{
714
+ Name: "schema_wait_for_version_seconds",
715
+ Help: "Duration of waiting for a schema version to be reached",
716
+ }, []string{"type"}),
717
+
718
+ TombstoneFindLocalEntrypoint: promauto.NewCounterVec(prometheus.CounterOpts{
719
+ Name: "tombstone_find_local_entrypoint",
720
+ Help: "Total number of tombstone delete local entrypoint calls",
721
+ }, []string{"class_name", "shard_name"}),
722
+ TombstoneFindGlobalEntrypoint: promauto.NewCounterVec(prometheus.CounterOpts{
723
+ Name: "tombstone_find_global_entrypoint",
724
+ Help: "Total number of tombstone delete global entrypoint calls",
725
+ }, []string{"class_name", "shard_name"}),
726
+ TombstoneReassignNeighbors: promauto.NewCounterVec(prometheus.CounterOpts{
727
+ Name: "tombstone_reassign_neighbors",
728
+ Help: "Total number of tombstone reassign neighbor calls",
729
+ }, []string{"class_name", "shard_name"}),
730
+ TombstoneDeleteListSize: promauto.NewGaugeVec(prometheus.GaugeOpts{
731
+ Name: "tombstone_delete_list_size",
732
+ Help: "Delete list size of tombstones",
733
+ }, []string{"class_name", "shard_name"}),
734
+
735
+ T2VBatches: promauto.NewGaugeVec(prometheus.GaugeOpts{
736
+ Name: "t2v_concurrent_batches",
737
+ Help: "Number of batches currently running",
738
+ }, []string{"vectorizer"}),
739
+ T2VBatchQueueDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
740
+ Name: "t2v_batch_queue_duration_seconds",
741
+ Help: "Time of a batch spend in specific portions of the queue",
742
+ Buckets: sBuckets,
743
+ }, []string{"vectorizer", "operation"}),
744
+ T2VRequestDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
745
+ Name: "t2v_request_duration_seconds",
746
+ Help: "Duration of an individual request to the vectorizer",
747
+ Buckets: sBuckets,
748
+ }, []string{"vectorizer"}),
749
+ T2VTokensInBatch: promauto.NewHistogramVec(prometheus.HistogramOpts{
750
+ Name: "t2v_tokens_in_batch",
751
+ Help: "Number of tokens in a user-defined batch",
752
+ Buckets: []float64{1, 10, 100, 1000, 10000, 100000, 1000000},
753
+ }, []string{"vectorizer"}),
754
+ T2VTokensInRequest: promauto.NewHistogramVec(prometheus.HistogramOpts{
755
+ Name: "t2v_tokens_in_request",
756
+ Help: "Number of tokens in an individual request sent to the vectorizer",
757
+ Buckets: []float64{1, 10, 100, 1000, 10000, 100000, 1000000},
758
+ }, []string{"vectorizer"}),
759
+ T2VRateLimitStats: promauto.NewGaugeVec(prometheus.GaugeOpts{
760
+ Name: "t2v_rate_limit_stats",
761
+ Help: "Rate limit stats for the vectorizer",
762
+ }, []string{"vectorizer", "stat"}),
763
+ T2VRepeatStats: promauto.NewGaugeVec(prometheus.GaugeOpts{
764
+ Name: "t2v_repeat_stats",
765
+ Help: "Why batch scheduling is repeated",
766
+ }, []string{"vectorizer", "stat"}),
767
+ T2VRequestsPerBatch: promauto.NewHistogramVec(prometheus.HistogramOpts{
768
+ Name: "t2v_requests_per_batch",
769
+ Help: "Number of requests required to process an entire (user) batch",
770
+ Buckets: []float64{1, 2, 5, 10, 100, 1000},
771
+ }, []string{"vectorizer"}),
772
+ TokenizerDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
773
+ Name: "tokenizer_duration_seconds",
774
+ Help: "Duration of a tokenizer operation",
775
+ Buckets: LatencyBuckets,
776
+ }, []string{"tokenizer"}),
777
+ TokenizerRequests: promauto.NewCounterVec(prometheus.CounterOpts{
778
+ Name: "tokenizer_requests_total",
779
+ Help: "Number of tokenizer requests",
780
+ }, []string{"tokenizer"}),
781
+ TokenizerInitializeDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
782
+ Name: "tokenizer_initialize_duration_seconds",
783
+ Help: "Duration of a tokenizer initialization operation",
784
+ Buckets: []float64{0.05, 0.1, 0.5, 1, 2, 5, 10},
785
+ }, []string{"tokenizer"}),
786
+ TokenCount: promauto.NewCounterVec(prometheus.CounterOpts{
787
+ Name: "token_count_total",
788
+ Help: "Number of tokens processed",
789
+ }, []string{"tokenizer"}),
790
+ TokenCountPerRequest: promauto.NewHistogramVec(prometheus.HistogramOpts{
791
+ Name: "token_count_per_request",
792
+ Help: "Number of tokens processed per request",
793
+ Buckets: []float64{1, 10, 50, 100, 500, 1000, 10000, 100000, 1000000},
794
+ }, []string{"tokenizer"}),
795
+ ModuleExternalRequests: promauto.NewCounterVec(prometheus.CounterOpts{
796
+ Name: "weaviate_module_requests_total",
797
+ Help: "Number of module requests to external APIs",
798
+ }, []string{"op", "api"}),
799
+ ModuleExternalRequestDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
800
+ Name: "weaviate_module_request_duration_seconds",
801
+ Help: "Duration of an individual request to a module external API",
802
+ Buckets: LatencyBuckets,
803
+ }, []string{"op", "api"}),
804
+ ModuleExternalBatchLength: promauto.NewHistogramVec(prometheus.HistogramOpts{
805
+ Name: "weaviate_module_requests_per_batch",
806
+ Help: "Number of items in a batch",
807
+ Buckets: []float64{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608},
808
+ }, []string{"op", "api"}),
809
+ ModuleExternalRequestSize: promauto.NewHistogramVec(prometheus.HistogramOpts{
810
+ Name: "weaviate_module_request_size_bytes",
811
+ Help: "Size (in bytes) of the request sent to an external API",
812
+ Buckets: []float64{256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608},
813
+ }, []string{"op", "api"}),
814
+ ModuleExternalResponseSize: promauto.NewHistogramVec(prometheus.HistogramOpts{
815
+ Name: "weaviate_module_response_size_bytes",
816
+ Help: "Size (in bytes) of the response received from an external API",
817
+ Buckets: []float64{256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608},
818
+ }, []string{"op", "api"}),
819
+ VectorizerRequestTokens: promauto.NewHistogramVec(prometheus.HistogramOpts{
820
+ Name: "weaviate_vectorizer_request_tokens",
821
+ Help: "Number of tokens in the request sent to an external vectorizer",
822
+ Buckets: []float64{0, 1, 10, 50, 100, 500, 1000, 5000, 10000, 100000, 1000000},
823
+ }, []string{"inout", "api"}),
824
+ ModuleExternalRequestSingleCount: promauto.NewCounterVec(prometheus.CounterOpts{
825
+ Name: "weaviate_module_request_single_count",
826
+ Help: "Number of single-item external API requests",
827
+ }, []string{"op", "api"}),
828
+ ModuleExternalRequestBatchCount: promauto.NewCounterVec(prometheus.CounterOpts{
829
+ Name: "weaviate_module_request_batch_count",
830
+ Help: "Number of batched module requests",
831
+ }, []string{"op", "api"}),
832
+ ModuleExternalError: promauto.NewCounterVec(prometheus.CounterOpts{
833
+ Name: "weaviate_module_error_total",
834
+ Help: "Number of OpenAI errors",
835
+ }, []string{"op", "module", "endpoint", "status_code"}),
836
+ ModuleCallError: promauto.NewCounterVec(prometheus.CounterOpts{
837
+ Name: "weaviate_module_call_error_total",
838
+ Help: "Number of module errors (related to external calls)",
839
+ }, []string{"module", "endpoint", "status_code"}),
840
+ ModuleExternalResponseStatus: promauto.NewCounterVec(prometheus.CounterOpts{
841
+ Name: "weaviate_module_response_status_total",
842
+ Help: "Number of API response statuses",
843
+ }, []string{"op", "endpoint", "status"}),
844
+ ModuleBatchError: promauto.NewCounterVec(prometheus.CounterOpts{
845
+ Name: "weaviate_module_batch_error_total",
846
+ Help: "Number of batch errors",
847
+ }, []string{"operation", "class_name"}),
848
+
849
+ // Checksum metrics
850
+ ChecksumValidationDuration: promauto.NewSummary(prometheus.SummaryOpts{
851
+ Name: "checksum_validation_duration_seconds",
852
+ Help: "Duration of checksum validation",
853
+ }),
854
+ ChecksumBytesRead: promauto.NewSummary(prometheus.SummaryOpts{
855
+ Name: "checksum_bytes_read",
856
+ Help: "Number of bytes read during checksum validation",
857
+ }),
858
+ }
859
+ }
860
+
861
+ type OnceUponATimer struct {
862
+ sync.Once
863
+ Timer *prometheus.Timer
864
+ }
865
+
866
+ func NewOnceTimer(promTimer *prometheus.Timer) *OnceUponATimer {
867
+ o := OnceUponATimer{}
868
+ o.Timer = promTimer
869
+ return &o
870
+ }
871
+
872
+ func (o *OnceUponATimer) ObserveDurationOnce() {
873
+ o.Do(func() {
874
+ o.Timer.ObserveDuration()
875
+ })
876
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/shards.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ // Move the shard from unloaded to in progress
15
+ func (pm *PrometheusMetrics) StartLoadingShard() {
16
+ if pm == nil {
17
+ return
18
+ }
19
+
20
+ pm.ShardsUnloaded.Dec()
21
+ pm.ShardsLoading.Inc()
22
+ }
23
+
24
+ // Move the shard from in progress to loaded
25
+ func (pm *PrometheusMetrics) FinishLoadingShard() {
26
+ if pm == nil {
27
+ return
28
+ }
29
+
30
+ pm.ShardsLoading.Dec()
31
+ pm.ShardsLoaded.Inc()
32
+ }
33
+
34
+ // Move the shard from loaded to in progress
35
+ func (pm *PrometheusMetrics) StartUnloadingShard() {
36
+ if pm == nil {
37
+ return
38
+ }
39
+
40
+ pm.ShardsLoaded.Dec()
41
+ pm.ShardsUnloading.Inc()
42
+ }
43
+
44
+ // Move the shard from in progress to unloaded
45
+ func (pm *PrometheusMetrics) FinishUnloadingShard() {
46
+ if pm == nil {
47
+ return
48
+ }
49
+
50
+ pm.ShardsUnloading.Dec()
51
+ pm.ShardsUnloaded.Inc()
52
+ }
53
+
54
+ // Register a new, unloaded shard
55
+ func (pm *PrometheusMetrics) NewUnloadedshard() {
56
+ if pm == nil {
57
+ return
58
+ }
59
+
60
+ pm.ShardsUnloaded.Inc()
61
+ }
platform/dbops/binaries/weaviate-src/usecases/monitoring/shards_test.go ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package monitoring
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/prometheus/client_golang/prometheus/testutil"
18
+ "github.com/stretchr/testify/assert"
19
+ )
20
+
21
+ func TestShards(t *testing.T) {
22
+ m := GetMetrics()
23
+
24
+ t.Run("start_loading_shard", func(t *testing.T) {
25
+ // Setting base values
26
+ mv := m.ShardsLoading
27
+ mv.Set(1)
28
+
29
+ mv = m.ShardsUnloaded
30
+ mv.Set(1)
31
+
32
+ m.StartLoadingShard()
33
+
34
+ loadingCount := testutil.ToFloat64(m.ShardsLoading)
35
+ unloadedCount := testutil.ToFloat64(m.ShardsUnloaded)
36
+
37
+ assert.Equal(t, float64(2), loadingCount)
38
+ assert.Equal(t, float64(0), unloadedCount)
39
+ })
40
+
41
+ t.Run("finish_loading_shard", func(t *testing.T) {
42
+ // invariant:
43
+ // 1. `shards_loading` should be decremented
44
+ // 2. `shards_loaded` should be incremented
45
+
46
+ // Setting base values
47
+ mv := m.ShardsLoading
48
+ mv.Set(1)
49
+
50
+ mv = m.ShardsLoaded
51
+ mv.Set(1)
52
+
53
+ m.FinishLoadingShard()
54
+
55
+ loadingCount := testutil.ToFloat64(m.ShardsLoading)
56
+ loadedCount := testutil.ToFloat64(m.ShardsLoaded)
57
+
58
+ assert.Equal(t, float64(0), loadingCount) // dec
59
+ assert.Equal(t, float64(2), loadedCount) // inc
60
+ })
61
+
62
+ t.Run("start_unloading_shard", func(t *testing.T) {
63
+ // invariant:
64
+ // 1. `shards_loaded` should be decremented
65
+ // 2. `shards_unloading` should be incremented
66
+
67
+ // Setting base values
68
+ mv := m.ShardsLoaded
69
+ mv.Set(1)
70
+
71
+ mv = m.ShardsUnloading
72
+ mv.Set(1)
73
+
74
+ m.StartUnloadingShard()
75
+
76
+ loadedCount := testutil.ToFloat64(m.ShardsLoaded)
77
+ unloadingCount := testutil.ToFloat64(m.ShardsUnloading)
78
+
79
+ assert.Equal(t, float64(0), loadedCount) // dec
80
+ assert.Equal(t, float64(2), unloadingCount) // inc
81
+ })
82
+
83
+ t.Run("finish_unloading_shard", func(t *testing.T) {
84
+ // invariant:
85
+ // 1. `shards_unloading` should be decremented
86
+ // 2. `shards_unloaded` should be incremented
87
+
88
+ // Setting base values
89
+ mv := m.ShardsUnloading
90
+ mv.Set(1)
91
+
92
+ mv = m.ShardsUnloaded
93
+ mv.Set(1)
94
+
95
+ m.FinishUnloadingShard()
96
+
97
+ unloadingCount := testutil.ToFloat64(m.ShardsUnloading)
98
+ unloadedCount := testutil.ToFloat64(m.ShardsUnloaded)
99
+
100
+ assert.Equal(t, float64(0), unloadingCount) // dec
101
+ assert.Equal(t, float64(2), unloadedCount) // inc
102
+ })
103
+
104
+ t.Run("new_unloaded_shard", func(t *testing.T) {
105
+ // invariant:
106
+ // 1. `shards_unloaded` should be incremented
107
+
108
+ // Setting base values
109
+ mv := m.ShardsUnloaded
110
+ mv.Set(1)
111
+
112
+ m.NewUnloadedshard()
113
+
114
+ unloadedCount := testutil.ToFloat64(m.ShardsUnloaded)
115
+
116
+ assert.Equal(t, float64(2), unloadedCount) // inc
117
+ })
118
+ }
platform/dbops/binaries/weaviate-src/usecases/multitenancy/extensions.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package multitenancy
13
+
14
+ import "github.com/weaviate/weaviate/entities/models"
15
+
16
+ // IsMultiTenant returns true if a collection is multi-tenant, false otherwise
17
+ func IsMultiTenant(config *models.MultiTenancyConfig) bool {
18
+ return config != nil && config.Enabled
19
+ }
platform/dbops/binaries/weaviate-src/usecases/multitenancy/extensions_test.go ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package multitenancy_test
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/weaviate/weaviate/usecases/multitenancy"
18
+
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ )
21
+
22
+ func TestIsMultiTenant(t *testing.T) {
23
+ tests := []struct {
24
+ name string
25
+ config *models.MultiTenancyConfig
26
+ expected bool
27
+ }{
28
+ {
29
+ name: "nil config should return false",
30
+ config: nil,
31
+ expected: false,
32
+ },
33
+ {
34
+ name: "disabled multi-tenancy should return false",
35
+ config: &models.MultiTenancyConfig{
36
+ Enabled: false,
37
+ },
38
+ expected: false,
39
+ },
40
+ {
41
+ name: "enabled multi-tenancy should return true",
42
+ config: &models.MultiTenancyConfig{
43
+ Enabled: true,
44
+ },
45
+ expected: true,
46
+ },
47
+ {
48
+ name: "enabled with other fields should return true",
49
+ config: &models.MultiTenancyConfig{
50
+ Enabled: true,
51
+ AutoTenantCreation: true,
52
+ AutoTenantActivation: false,
53
+ },
54
+ expected: true,
55
+ },
56
+ }
57
+
58
+ for _, tt := range tests {
59
+ t.Run(tt.name, func(t *testing.T) {
60
+ result := multitenancy.IsMultiTenant(tt.config)
61
+ if result != tt.expected {
62
+ t.Errorf("IsMultiTenant() = %v, expected %v", result, tt.expected)
63
+ }
64
+ })
65
+ }
66
+ }
platform/dbops/binaries/weaviate-src/usecases/nodes/handler.go ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package nodes
13
+
14
+ import (
15
+ "context"
16
+ "time"
17
+
18
+ "github.com/weaviate/weaviate/usecases/auth/authorization/filter"
19
+ "github.com/weaviate/weaviate/usecases/auth/authorization/rbac/rbacconf"
20
+
21
+ "github.com/weaviate/weaviate/entities/verbosity"
22
+
23
+ "github.com/sirupsen/logrus"
24
+ "github.com/weaviate/weaviate/entities/models"
25
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
26
+ schemaUC "github.com/weaviate/weaviate/usecases/schema"
27
+ )
28
+
29
+ type db interface {
30
+ GetNodeStatus(ctx context.Context, className, shardName, verbosity string) ([]*models.NodeStatus, error)
31
+ GetNodeStatistics(ctx context.Context) ([]*models.Statistics, error)
32
+ }
33
+
34
+ type Manager struct {
35
+ logger logrus.FieldLogger
36
+ authorizer authorization.Authorizer
37
+ db db
38
+ schemaManager *schemaUC.Manager
39
+ rbacconfig rbacconf.Config
40
+ minimumInternalTimeout time.Duration
41
+ }
42
+
43
+ func NewManager(logger logrus.FieldLogger, authorizer authorization.Authorizer,
44
+ db db, schemaManager *schemaUC.Manager, rbacconfig rbacconf.Config, minimumInternalTimeout time.Duration,
45
+ ) *Manager {
46
+ return &Manager{logger, authorizer, db, schemaManager, rbacconfig, minimumInternalTimeout}
47
+ }
48
+
49
+ // GetNodeStatus aggregates the status across all nodes. It will try for a
50
+ // maximum of the configured timeout, then mark nodes as timed out.
51
+ func (m *Manager) GetNodeStatus(ctx context.Context,
52
+ principal *models.Principal, className, shardName, verbosityString string,
53
+ ) ([]*models.NodeStatus, error) {
54
+ ctxWithTimeout, cancel := context.WithTimeout(ctx, m.minimumInternalTimeout)
55
+ defer cancel()
56
+
57
+ // filter output after getting results if info about all shards is requested
58
+ filterOutput := verbosityString == verbosity.OutputVerbose && className == "" && m.rbacconfig.Enabled
59
+
60
+ if !filterOutput {
61
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Nodes(verbosityString, className)...); err != nil {
62
+ return nil, err
63
+ }
64
+ }
65
+
66
+ status, err := m.db.GetNodeStatus(ctxWithTimeout, className, shardName, verbosityString)
67
+ if err != nil {
68
+ return nil, err
69
+ }
70
+
71
+ if filterOutput {
72
+ resourceFilter := filter.New[*models.NodeShardStatus](m.authorizer, m.rbacconfig)
73
+
74
+ for i, nodeS := range status {
75
+ status[i].Shards = resourceFilter.Filter(
76
+ ctx,
77
+ m.logger,
78
+ principal,
79
+ nodeS.Shards,
80
+ authorization.READ,
81
+ func(shard *models.NodeShardStatus) string {
82
+ return authorization.Nodes(verbosityString, shard.Class)[0]
83
+ },
84
+ )
85
+ }
86
+ }
87
+
88
+ return status, nil
89
+ }
90
+
91
+ func (m *Manager) GetNodeStatistics(ctx context.Context,
92
+ principal *models.Principal,
93
+ ) ([]*models.Statistics, error) {
94
+ ctxWithTimeout, cancel := context.WithTimeout(ctx, m.minimumInternalTimeout)
95
+ defer cancel()
96
+
97
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Cluster()); err != nil {
98
+ return nil, err
99
+ }
100
+ return m.db.GetNodeStatistics(ctxWithTimeout)
101
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/add.go ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "strings"
19
+
20
+ "github.com/weaviate/weaviate/entities/schema"
21
+ "github.com/weaviate/weaviate/entities/versioned"
22
+
23
+ "github.com/go-openapi/strfmt"
24
+ "github.com/google/uuid"
25
+
26
+ "github.com/weaviate/weaviate/entities/additional"
27
+ "github.com/weaviate/weaviate/entities/classcache"
28
+ "github.com/weaviate/weaviate/entities/dto"
29
+ enterrors "github.com/weaviate/weaviate/entities/errors"
30
+ "github.com/weaviate/weaviate/entities/models"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
32
+ authzerrs "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
33
+ "github.com/weaviate/weaviate/usecases/memwatch"
34
+ "github.com/weaviate/weaviate/usecases/objects/validation"
35
+ )
36
+
37
+ // AddObject Class Instance to the connected DB.
38
+ func (m *Manager) AddObject(ctx context.Context, principal *models.Principal, object *models.Object,
39
+ repl *additional.ReplicationProperties,
40
+ ) (*models.Object, error) {
41
+ className := schema.UppercaseClassName(object.Class)
42
+ className, _ = m.resolveAlias(className)
43
+ object.Class = className
44
+
45
+ if err := m.authorizer.Authorize(ctx, principal, authorization.CREATE, authorization.ShardsData(className, object.Tenant)...); err != nil {
46
+ return nil, err
47
+ }
48
+
49
+ m.metrics.AddObjectInc()
50
+ defer m.metrics.AddObjectDec()
51
+
52
+ ctx = classcache.ContextWithClassCache(ctx)
53
+ // we don't reveal any info that the end users cannot get through the structure of the data anyway
54
+ fetchedClasses, err := m.schemaManager.GetCachedClassNoAuth(ctx, className)
55
+ if err != nil {
56
+ return nil, err
57
+ }
58
+
59
+ if err := m.allocChecker.CheckAlloc(memwatch.EstimateObjectMemory(object)); err != nil {
60
+ m.logger.WithError(err).Errorf("memory pressure: cannot process add object")
61
+ return nil, fmt.Errorf("cannot process add object: %w", err)
62
+ }
63
+
64
+ obj, err := m.addObjectToConnectorAndSchema(ctx, principal, object, repl, fetchedClasses)
65
+ if err != nil {
66
+ return nil, err
67
+ }
68
+
69
+ return obj, nil
70
+ }
71
+
72
+ func (m *Manager) addObjectToConnectorAndSchema(ctx context.Context, principal *models.Principal,
73
+ object *models.Object, repl *additional.ReplicationProperties, fetchedClasses map[string]versioned.Class,
74
+ ) (*models.Object, error) {
75
+ id, err := m.checkIDOrAssignNew(ctx, principal, object.Class, object.ID, repl, object.Tenant)
76
+ if err != nil {
77
+ return nil, err
78
+ }
79
+ object.ID = id
80
+
81
+ schemaVersion, err := m.autoSchemaManager.autoSchema(ctx, principal, true, fetchedClasses, object)
82
+ if err != nil {
83
+ return nil, fmt.Errorf("invalid object: %w", err)
84
+ }
85
+
86
+ if _, _, err = m.autoSchemaManager.autoTenants(ctx, principal, []*models.Object{object}, fetchedClasses); err != nil {
87
+ return nil, err
88
+ }
89
+
90
+ class := fetchedClasses[object.Class].Class
91
+
92
+ err = m.validateObjectAndNormalizeNames(ctx, repl, object, nil, fetchedClasses)
93
+ if err != nil {
94
+ return nil, NewErrInvalidUserInput("invalid object: %v", err)
95
+ }
96
+
97
+ now := m.timeSource.Now()
98
+ object.CreationTimeUnix = now
99
+ object.LastUpdateTimeUnix = now
100
+ if object.Properties == nil {
101
+ object.Properties = map[string]interface{}{}
102
+ }
103
+
104
+ err = m.modulesProvider.UpdateVector(ctx, object, class, m.findObject, m.logger)
105
+ if err != nil {
106
+ return nil, err
107
+ }
108
+
109
+ // Ensure that the local schema has caught up to the version we used to validate
110
+ if err := m.schemaManager.WaitForUpdate(ctx, schemaVersion); err != nil {
111
+ return nil, fmt.Errorf("error waiting for local schema to catch up to version %d: %w", schemaVersion, err)
112
+ }
113
+ vectors, multiVectors, err := dto.GetVectors(object.Vectors)
114
+ if err != nil {
115
+ return nil, fmt.Errorf("put object: cannot get vectors: %w", err)
116
+ }
117
+ err = m.vectorRepo.PutObject(ctx, object, object.Vector, vectors, multiVectors, repl, schemaVersion)
118
+ if err != nil {
119
+ return nil, fmt.Errorf("put object: %w", err)
120
+ }
121
+
122
+ return object, nil
123
+ }
124
+
125
+ func (m *Manager) checkIDOrAssignNew(ctx context.Context, principal *models.Principal,
126
+ className string, id strfmt.UUID, repl *additional.ReplicationProperties, tenant string,
127
+ ) (strfmt.UUID, error) {
128
+ if id == "" {
129
+ validatedID, err := generateUUID()
130
+ if err != nil {
131
+ return "", NewErrInternal("could not generate id: %v", err)
132
+ }
133
+ return validatedID, err
134
+ }
135
+
136
+ // IDs are always returned lowercase, but they are written
137
+ // to disk as uppercase, when provided that way. Here we
138
+ // ensure they are lowercase on disk as well, so things
139
+ // like filtering are not affected.
140
+ // See: https://github.com/weaviate/weaviate/issues/2647
141
+ validatedID := strfmt.UUID(strings.ToLower(id.String()))
142
+
143
+ exists, err := m.vectorRepo.Exists(ctx, className, validatedID, repl, tenant)
144
+ if exists {
145
+ return "", NewErrInvalidUserInput("id '%s' already exists", id)
146
+ } else if err != nil {
147
+ switch {
148
+ case errors.As(err, &ErrInvalidUserInput{}):
149
+ return "", err
150
+ case errors.As(err, &ErrMultiTenancy{}):
151
+ // This may be fine, the class is configured to create non-existing tenants.
152
+ // A non-existing tenant will still be detected later on
153
+ if enterrors.IsTenantNotFound(err) {
154
+ break
155
+ }
156
+ return "", err
157
+ default:
158
+ if errors.As(err, &authzerrs.Forbidden{}) {
159
+ return "", err
160
+ }
161
+ return "", NewErrInternal("%v", err)
162
+ }
163
+ }
164
+
165
+ return validatedID, nil
166
+ }
167
+
168
+ func (m *Manager) validateObjectAndNormalizeNames(ctx context.Context,
169
+ repl *additional.ReplicationProperties,
170
+ incoming *models.Object, existing *models.Object, fetchedClasses map[string]versioned.Class,
171
+ ) error {
172
+ err := m.validateUUID(incoming)
173
+ if err != nil {
174
+ return err
175
+ }
176
+
177
+ if _, ok := fetchedClasses[incoming.Class]; !ok || fetchedClasses[incoming.Class].Class == nil {
178
+ return fmt.Errorf("class %q not found in schema", incoming.Class)
179
+ }
180
+ class := fetchedClasses[incoming.Class].Class
181
+
182
+ return validation.New(m.vectorRepo.Exists, m.config, repl).
183
+ Object(ctx, class, incoming, existing)
184
+ }
185
+
186
+ func (m *Manager) validateUUID(obj *models.Object) error {
187
+ // Validate schema given in body with the weaviate schema
188
+ _, err := uuid.Parse(obj.ID.String())
189
+ return err
190
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/add_test.go ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "strings"
17
+ "testing"
18
+
19
+ "github.com/go-openapi/strfmt"
20
+ "github.com/google/uuid"
21
+ "github.com/prometheus/client_golang/prometheus"
22
+ "github.com/sirupsen/logrus/hooks/test"
23
+ "github.com/stretchr/testify/assert"
24
+ "github.com/stretchr/testify/mock"
25
+ "github.com/stretchr/testify/require"
26
+
27
+ "github.com/weaviate/weaviate/entities/models"
28
+ "github.com/weaviate/weaviate/entities/schema"
29
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
30
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
31
+ "github.com/weaviate/weaviate/usecases/config"
32
+ "github.com/weaviate/weaviate/usecases/config/runtime"
33
+ )
34
+
35
+ func Test_Add_Object_WithNoVectorizerModule(t *testing.T) {
36
+ var (
37
+ vectorRepo *fakeVectorRepo
38
+ modulesProvider *fakeModulesProvider
39
+ manager *Manager
40
+ schemaManager *fakeSchemaManager
41
+ authorizer *mocks.FakeAuthorizer
42
+ )
43
+
44
+ sch := schema.Schema{
45
+ Objects: &models.Schema{
46
+ Classes: []*models.Class{
47
+ {
48
+ Class: "Foo",
49
+ Vectorizer: config.VectorizerModuleNone,
50
+ VectorIndexConfig: hnsw.UserConfig{},
51
+ },
52
+ {
53
+ Class: "FooSkipped",
54
+ Vectorizer: config.VectorizerModuleNone,
55
+ VectorIndexConfig: hnsw.UserConfig{
56
+ Skip: true,
57
+ },
58
+ },
59
+ },
60
+ },
61
+ }
62
+
63
+ resetAutoSchema := func(autoSchemaEnabled bool) {
64
+ vectorRepo = &fakeVectorRepo{}
65
+ vectorRepo.On("PutObject", mock.Anything, mock.Anything).Return(nil).Once()
66
+ schemaManager = &fakeSchemaManager{
67
+ GetSchemaResponse: sch,
68
+ }
69
+ cfg := &config.WeaviateConfig{
70
+ Config: config.Config{
71
+ AutoSchema: config.AutoSchema{
72
+ Enabled: runtime.NewDynamicValue(autoSchemaEnabled),
73
+ DefaultString: schema.DataTypeText.String(),
74
+ },
75
+ },
76
+ }
77
+ authorizer = mocks.NewMockAuthorizer()
78
+ logger, _ := test.NewNullLogger()
79
+
80
+ modulesProvider = getFakeModulesProvider()
81
+ metrics := &fakeMetrics{}
82
+ manager = NewManager(schemaManager, cfg, logger, authorizer,
83
+ vectorRepo, modulesProvider, metrics, nil,
84
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
85
+ }
86
+
87
+ reset := func() {
88
+ resetAutoSchema(false)
89
+ }
90
+
91
+ t.Run("without an id set", func(t *testing.T) {
92
+ reset()
93
+
94
+ ctx := context.Background()
95
+ class := &models.Object{
96
+ Vector: []float32{0.1, 0.2, 0.3},
97
+ Class: "Foo",
98
+ }
99
+
100
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
101
+ Return(nil, nil)
102
+
103
+ res, err := manager.AddObject(ctx, nil, class, nil)
104
+ require.Nil(t, err)
105
+ uuidDuringCreation := vectorRepo.Mock.Calls[0].Arguments.Get(0).(*models.Object).ID
106
+
107
+ assert.Len(t, uuidDuringCreation, 36, "check that a uuid was assigned")
108
+ assert.Equal(t, uuidDuringCreation, res.ID, "check that connector add ID and user response match")
109
+ })
110
+
111
+ t.Run("with an explicit (correct) ID set", func(t *testing.T) {
112
+ reset()
113
+
114
+ ctx := context.Background()
115
+ id := strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
116
+ object := &models.Object{
117
+ Vector: []float32{0.1, 0.2, 0.3},
118
+ ID: id,
119
+ Class: "Foo",
120
+ }
121
+ vectorRepo.On("Exists", "Foo", id).Return(false, nil).Once()
122
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
123
+ Return(nil, nil)
124
+
125
+ res, err := manager.AddObject(ctx, nil, object, nil)
126
+ require.Nil(t, err)
127
+ uuidDuringCreation := vectorRepo.Mock.Calls[1].Arguments.Get(0).(*models.Object).ID
128
+
129
+ assert.Equal(t, id, uuidDuringCreation, "check that a uuid is the user specified one")
130
+ assert.Equal(t, res.ID, uuidDuringCreation, "check that connector add ID and user response match")
131
+ })
132
+
133
+ t.Run("with an explicit (correct) uppercase id set", func(t *testing.T) {
134
+ reset()
135
+
136
+ ctx := context.Background()
137
+ id := strfmt.UUID("4A334D0B-6347-40A0-A5AE-339677B20EDE")
138
+ lowered := strfmt.UUID(strings.ToLower(id.String()))
139
+ object := &models.Object{
140
+ ID: id,
141
+ Class: "Foo",
142
+ Vector: []float32{0.1, 0.2, 0.3},
143
+ }
144
+ vectorRepo.On("Exists", "Foo", lowered).Return(false, nil).Once()
145
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
146
+ Return(nil, nil)
147
+
148
+ res, err := manager.AddObject(ctx, nil, object, nil)
149
+ require.Nil(t, err)
150
+ assert.Equal(t, res.ID, lowered, "check that id was lowered and added")
151
+ })
152
+
153
+ t.Run("with an explicit (correct) ID set and a property that doesn't exist", func(t *testing.T) {
154
+ resetAutoSchema(true)
155
+
156
+ ctx := context.Background()
157
+ id := strfmt.UUID("5aaad361-1e0d-42ae-bb52-ee09cb5f31cc")
158
+ object := &models.Object{
159
+ Vector: []float32{0.1, 0.2, 0.3},
160
+ ID: id,
161
+ Class: "Foo",
162
+ Properties: map[string]interface{}{
163
+ "newProperty": "string value",
164
+ },
165
+ }
166
+ vectorRepo.On("Exists", "Foo", id).Return(false, nil).Once()
167
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
168
+ Return(nil, nil)
169
+
170
+ res, err := manager.AddObject(ctx, nil, object, nil)
171
+ require.Nil(t, err)
172
+ uuidDuringCreation := vectorRepo.Mock.Calls[1].Arguments.Get(0).(*models.Object).ID
173
+
174
+ assert.Equal(t, id, uuidDuringCreation, "check that a uuid is the user specified one")
175
+ assert.Equal(t, res.ID, uuidDuringCreation, "check that connector add ID and user response match")
176
+ })
177
+
178
+ t.Run("with a uuid that's already taken", func(t *testing.T) {
179
+ reset()
180
+
181
+ ctx := context.Background()
182
+ id := strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
183
+ class := &models.Object{
184
+ ID: id,
185
+ Class: "Foo",
186
+ }
187
+
188
+ vectorRepo.On("Exists", "Foo", id).Return(true, nil).Once()
189
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
190
+ Return(nil, nil)
191
+
192
+ _, err := manager.AddObject(ctx, nil, class, nil)
193
+ assert.Equal(t, NewErrInvalidUserInput("id '%s' already exists", id), err)
194
+ })
195
+
196
+ t.Run("with a uuid that's malformed", func(t *testing.T) {
197
+ reset()
198
+
199
+ ctx := context.Background()
200
+ id := strfmt.UUID("5a1cd361-1e0d-4fooooooo2ae-bd52-ee09cb5f31cc")
201
+ class := &models.Object{
202
+ ID: id,
203
+ Class: "Foo",
204
+ }
205
+
206
+ vectorRepo.On("Exists", "Foo", id).Return(false, nil).Once()
207
+
208
+ _, err := manager.AddObject(ctx, nil, class, nil)
209
+ assert.Equal(t, NewErrInvalidUserInput("invalid object: invalid UUID length: %d", len(id)), err)
210
+ })
211
+
212
+ t.Run("without a vector", func(t *testing.T) {
213
+ // Note that this was an invalid case before v1.10 which added this
214
+ // functionality, as part of
215
+ // https://github.com/weaviate/weaviate/issues/1800
216
+ reset()
217
+
218
+ ctx := context.Background()
219
+ class := &models.Object{
220
+ Class: "Foo",
221
+ }
222
+
223
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
224
+ Return(nil, nil)
225
+
226
+ _, err := manager.AddObject(ctx, nil, class, nil)
227
+ assert.Nil(t, err)
228
+ })
229
+
230
+ t.Run("resolve alias before rbac check", func(t *testing.T) {
231
+ // This test is to make sure alias is resolved to correct
232
+ // collection before doing RBAC check on original class during add object.
233
+
234
+ reset()
235
+ ctx := context.Background()
236
+ alias := "FooAlias"
237
+ class := "Foo"
238
+
239
+ obj := &models.Object{
240
+ Class: alias, // via alias
241
+ }
242
+
243
+ schemaManager.resolveAliasTo = class
244
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
245
+ Return(nil, nil)
246
+
247
+ _, err := manager.AddObject(ctx, nil, obj, nil)
248
+ require.NoError(t, err)
249
+ assert.Len(t, authorizer.Calls(), 1)
250
+ assert.Contains(t, authorizer.Calls()[0].Resources[0], class) // make sure rbac is called with "resolved class" name
251
+ })
252
+
253
+ t.Run("without a vector, but indexing skipped", func(t *testing.T) {
254
+ reset()
255
+
256
+ ctx := context.Background()
257
+ class := &models.Object{
258
+ Class: "FooSkipped",
259
+ }
260
+
261
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
262
+ Return(nil, nil)
263
+
264
+ _, err := manager.AddObject(ctx, nil, class, nil)
265
+ assert.Nil(t, err)
266
+ })
267
+ }
268
+
269
+ func Test_Add_Object_WithExternalVectorizerModule(t *testing.T) {
270
+ var (
271
+ vectorRepo *fakeVectorRepo
272
+ modulesProvider *fakeModulesProvider
273
+ manager *Manager
274
+ )
275
+
276
+ schema := schema.Schema{
277
+ Objects: &models.Schema{
278
+ Classes: []*models.Class{
279
+ {
280
+ Class: "Foo",
281
+ Vectorizer: config.VectorizerModuleText2VecContextionary,
282
+ VectorIndexConfig: hnsw.UserConfig{},
283
+ },
284
+ },
285
+ },
286
+ }
287
+
288
+ reset := func() {
289
+ vectorRepo = &fakeVectorRepo{}
290
+ vectorRepo.On("PutObject", mock.Anything, mock.Anything).Return(nil).Once()
291
+ schemaManager := &fakeSchemaManager{
292
+ GetSchemaResponse: schema,
293
+ }
294
+ cfg := &config.WeaviateConfig{}
295
+ authorizer := mocks.NewMockAuthorizer()
296
+ logger, _ := test.NewNullLogger()
297
+ metrics := &fakeMetrics{}
298
+ modulesProvider = getFakeModulesProvider()
299
+ modulesProvider.On("UsingRef2Vec", mock.Anything).Return(false)
300
+ manager = NewManager(schemaManager, cfg, logger, authorizer,
301
+ vectorRepo, modulesProvider, metrics, nil,
302
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
303
+ }
304
+
305
+ t.Run("without an id set", func(t *testing.T) {
306
+ reset()
307
+
308
+ ctx := context.Background()
309
+ object := &models.Object{
310
+ Class: "Foo",
311
+ }
312
+
313
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
314
+ Return(nil, nil)
315
+
316
+ res, err := manager.AddObject(ctx, nil, object, nil)
317
+ require.Nil(t, err)
318
+
319
+ uuidDuringCreation := vectorRepo.Mock.Calls[0].Arguments.Get(0).(*models.Object).ID
320
+
321
+ assert.Len(t, uuidDuringCreation, 36, "check that a uuid was assigned")
322
+ assert.Equal(t, uuidDuringCreation, res.ID, "check that connector add ID and user response match")
323
+ })
324
+
325
+ t.Run("with an explicit (correct) ID set", func(t *testing.T) {
326
+ reset()
327
+
328
+ ctx := context.Background()
329
+ id := strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
330
+ object := &models.Object{
331
+ ID: id,
332
+ Class: "Foo",
333
+ }
334
+ vectorRepo.On("Exists", "Foo", id).Return(false, nil).Once()
335
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
336
+ Return(nil, nil)
337
+
338
+ res, err := manager.AddObject(ctx, nil, object, nil)
339
+ uuidDuringCreation := vectorRepo.Mock.Calls[1].Arguments.Get(0).(*models.Object).ID
340
+
341
+ assert.Nil(t, err)
342
+ assert.Equal(t, id, uuidDuringCreation, "check that a uuid is the user specified one")
343
+ assert.Equal(t, res.ID, uuidDuringCreation, "check that connector add ID and user response match")
344
+ })
345
+
346
+ t.Run("with a uuid that's already taken", func(t *testing.T) {
347
+ reset()
348
+
349
+ ctx := context.Background()
350
+ id := strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
351
+ object := &models.Object{
352
+ ID: id,
353
+ Class: "Foo",
354
+ }
355
+
356
+ vectorRepo.On("Exists", "Foo", id).Return(true, nil).Once()
357
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
358
+ Return(nil, nil)
359
+
360
+ _, err := manager.AddObject(ctx, nil, object, nil)
361
+ assert.Equal(t, NewErrInvalidUserInput("id '%s' already exists", id), err)
362
+ })
363
+
364
+ t.Run("with a uuid that's malformed", func(t *testing.T) {
365
+ reset()
366
+
367
+ ctx := context.Background()
368
+ id := strfmt.UUID("5a1cd361-1e0d-4f00000002ae-bd52-ee09cb5f31cc")
369
+ object := &models.Object{
370
+ ID: id,
371
+ Class: "Foo",
372
+ }
373
+
374
+ vectorRepo.On("Exists", "Foo", id).Return(false, nil).Once()
375
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
376
+ Return(nil, nil)
377
+
378
+ _, err := manager.AddObject(ctx, nil, object, nil)
379
+ assert.Equal(t, NewErrInvalidUserInput("invalid object: invalid UUID length: %d", len(id)), err)
380
+ })
381
+ }
382
+
383
+ func Test_Add_Object_OverrideVectorizer(t *testing.T) {
384
+ var (
385
+ vectorRepo *fakeVectorRepo
386
+ modulesProvider *fakeModulesProvider
387
+ manager *Manager
388
+ )
389
+
390
+ schema := schema.Schema{
391
+ Objects: &models.Schema{
392
+ Classes: []*models.Class{
393
+ {
394
+ Class: "FooOverride",
395
+ Vectorizer: config.VectorizerModuleText2VecContextionary,
396
+ VectorIndexConfig: hnsw.UserConfig{},
397
+ },
398
+ },
399
+ },
400
+ }
401
+
402
+ reset := func() {
403
+ vectorRepo = &fakeVectorRepo{}
404
+ vectorRepo.On("PutObject", mock.Anything, mock.Anything).Return(nil).Once()
405
+ schemaManager := &fakeSchemaManager{
406
+ GetSchemaResponse: schema,
407
+ }
408
+ cfg := &config.WeaviateConfig{}
409
+ authorizer := mocks.NewMockAuthorizer()
410
+ logger, _ := test.NewNullLogger()
411
+ modulesProvider = getFakeModulesProvider()
412
+ metrics := &fakeMetrics{}
413
+ manager = NewManager(schemaManager, cfg, logger,
414
+ authorizer, vectorRepo, modulesProvider, metrics, nil,
415
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
416
+ }
417
+
418
+ t.Run("overriding the vector by explicitly specifying it", func(t *testing.T) {
419
+ reset()
420
+
421
+ ctx := context.Background()
422
+ object := &models.Object{
423
+ Class: "FooOverride",
424
+ Vector: []float32{9, 9, 9},
425
+ }
426
+
427
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
428
+ Return(object.Vector, nil)
429
+
430
+ _, err := manager.AddObject(ctx, nil, object, nil)
431
+ require.Nil(t, err)
432
+
433
+ vec := vectorRepo.Mock.Calls[0].Arguments.Get(1).([]float32)
434
+
435
+ assert.Equal(t, []float32{9, 9, 9}, vec, "check that vector was overridden")
436
+ })
437
+ }
438
+
439
+ func Test_AddObjectEmptyProperties(t *testing.T) {
440
+ var (
441
+ vectorRepo *fakeVectorRepo
442
+ modulesProvider *fakeModulesProvider
443
+ manager *Manager
444
+ )
445
+ schema := schema.Schema{
446
+ Objects: &models.Schema{
447
+ Classes: []*models.Class{
448
+ {
449
+ Class: "TestClass",
450
+ VectorIndexConfig: hnsw.UserConfig{},
451
+
452
+ Properties: []*models.Property{
453
+ {
454
+ Name: "strings",
455
+ DataType: schema.DataTypeTextArray.PropString(),
456
+ Tokenization: models.PropertyTokenizationWhitespace,
457
+ },
458
+ },
459
+ },
460
+ },
461
+ },
462
+ }
463
+ reset := func() {
464
+ vectorRepo = &fakeVectorRepo{}
465
+ vectorRepo.On("PutObject", mock.Anything, mock.Anything).Return(nil).Once()
466
+ schemaManager := &fakeSchemaManager{
467
+ GetSchemaResponse: schema,
468
+ }
469
+ cfg := &config.WeaviateConfig{}
470
+ authorizer := mocks.NewMockAuthorizer()
471
+ logger, _ := test.NewNullLogger()
472
+ modulesProvider = getFakeModulesProvider()
473
+ metrics := &fakeMetrics{}
474
+ manager = NewManager(schemaManager, cfg, logger,
475
+ authorizer, vectorRepo, modulesProvider, metrics, nil,
476
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
477
+ }
478
+ reset()
479
+ ctx := context.Background()
480
+ object := &models.Object{
481
+ Class: "TestClass",
482
+ Vector: []float32{9, 9, 9},
483
+ }
484
+ assert.Nil(t, object.Properties)
485
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
486
+ Return(nil, nil)
487
+ addedObject, err := manager.AddObject(ctx, nil, object, nil)
488
+ assert.Nil(t, err)
489
+ assert.NotNil(t, addedObject.Properties)
490
+ }
491
+
492
+ func Test_AddObjectWithUUIDProps(t *testing.T) {
493
+ var (
494
+ vectorRepo *fakeVectorRepo
495
+ modulesProvider *fakeModulesProvider
496
+ manager *Manager
497
+ )
498
+ schema := schema.Schema{
499
+ Objects: &models.Schema{
500
+ Classes: []*models.Class{
501
+ {
502
+ Class: "TestClass",
503
+ VectorIndexConfig: hnsw.UserConfig{},
504
+
505
+ Properties: []*models.Property{
506
+ {
507
+ Name: "my_id",
508
+ DataType: []string{"uuid"},
509
+ },
510
+ {
511
+ Name: "my_idz",
512
+ DataType: []string{"uuid[]"},
513
+ },
514
+ },
515
+ },
516
+ },
517
+ },
518
+ }
519
+ reset := func() {
520
+ vectorRepo = &fakeVectorRepo{}
521
+ vectorRepo.On("PutObject", mock.Anything, mock.Anything).Return(nil).Once()
522
+ schemaManager := &fakeSchemaManager{
523
+ GetSchemaResponse: schema,
524
+ }
525
+ cfg := &config.WeaviateConfig{}
526
+ authorizer := mocks.NewMockAuthorizer()
527
+ logger, _ := test.NewNullLogger()
528
+ modulesProvider = getFakeModulesProvider()
529
+ metrics := &fakeMetrics{}
530
+ manager = NewManager(schemaManager, cfg, logger,
531
+ authorizer, vectorRepo, modulesProvider, metrics, nil,
532
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()),
533
+ )
534
+ }
535
+ reset()
536
+ ctx := context.Background()
537
+ object := &models.Object{
538
+ Class: "TestClass",
539
+ Vector: []float32{9, 9, 9},
540
+ Properties: map[string]interface{}{
541
+ "my_id": "28bafa1e-7956-4c58-8a02-4499a9d15253",
542
+ "my_idz": []any{"28bafa1e-7956-4c58-8a02-4499a9d15253"},
543
+ },
544
+ }
545
+ modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
546
+ Return(nil, nil)
547
+ addedObject, err := manager.AddObject(ctx, nil, object, nil)
548
+ require.Nil(t, err)
549
+ require.NotNil(t, addedObject.Properties)
550
+
551
+ expectedID := uuid.MustParse("28bafa1e-7956-4c58-8a02-4499a9d15253")
552
+ expectedIDz := []uuid.UUID{uuid.MustParse("28bafa1e-7956-4c58-8a02-4499a9d15253")}
553
+
554
+ assert.Equal(t, expectedID, addedObject.Properties.(map[string]interface{})["my_id"])
555
+ assert.Equal(t, expectedIDz, addedObject.Properties.(map[string]interface{})["my_idz"])
556
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/authorization_test.go ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "reflect"
19
+ "testing"
20
+
21
+ "github.com/go-openapi/strfmt"
22
+ "github.com/google/uuid"
23
+ "github.com/prometheus/client_golang/prometheus"
24
+ "github.com/sirupsen/logrus/hooks/test"
25
+ "github.com/stretchr/testify/assert"
26
+ "github.com/stretchr/testify/require"
27
+
28
+ "github.com/weaviate/weaviate/entities/additional"
29
+ "github.com/weaviate/weaviate/entities/models"
30
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ )
34
+
35
+ // A component-test like test suite that makes sure that every available UC is
36
+ // potentially protected with the Authorization plugin
37
+
38
+ func Test_Kinds_Authorization(t *testing.T) {
39
+ type testCase struct {
40
+ methodName string
41
+ additionalArgs []interface{}
42
+ expectedVerb string
43
+ expectedResources []string
44
+ }
45
+
46
+ tests := []testCase{
47
+ // single kind
48
+ {
49
+ methodName: "AddObject",
50
+ additionalArgs: []interface{}{(*models.Object)(nil)},
51
+ expectedVerb: authorization.UPDATE,
52
+ expectedResources: authorization.ShardsMetadata("", ""),
53
+ },
54
+ {
55
+ methodName: "ValidateObject",
56
+ additionalArgs: []interface{}{(*models.Object)(nil)},
57
+ expectedVerb: authorization.READ,
58
+ expectedResources: []string{authorization.Objects("", "", "")},
59
+ },
60
+ {
61
+ methodName: "GetObject",
62
+ additionalArgs: []interface{}{"", strfmt.UUID("foo"), additional.Properties{}},
63
+ expectedVerb: authorization.READ,
64
+ expectedResources: []string{authorization.Objects("", "", "foo")},
65
+ },
66
+ {
67
+ methodName: "DeleteObject",
68
+ additionalArgs: []interface{}{"class", strfmt.UUID("foo")},
69
+ expectedVerb: authorization.DELETE,
70
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
71
+ },
72
+ { // deprecated by the one above
73
+ methodName: "DeleteObject",
74
+ additionalArgs: []interface{}{"class", strfmt.UUID("foo")},
75
+ expectedVerb: authorization.DELETE,
76
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
77
+ },
78
+ {
79
+ methodName: "UpdateObject",
80
+ additionalArgs: []interface{}{"class", strfmt.UUID("foo"), (*models.Object)(nil)},
81
+ expectedVerb: authorization.UPDATE,
82
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
83
+ },
84
+ { // deprecated by the one above
85
+ methodName: "UpdateObject",
86
+ additionalArgs: []interface{}{"class", strfmt.UUID("foo"), (*models.Object)(nil)},
87
+ expectedVerb: authorization.UPDATE,
88
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
89
+ },
90
+ {
91
+ methodName: "MergeObject",
92
+ additionalArgs: []interface{}{
93
+ &models.Object{Class: "class", ID: "foo"},
94
+ (*additional.ReplicationProperties)(nil),
95
+ },
96
+ expectedVerb: authorization.UPDATE,
97
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
98
+ },
99
+ {
100
+ methodName: "GetObjectsClass",
101
+ additionalArgs: []interface{}{strfmt.UUID("foo")},
102
+ expectedVerb: authorization.READ,
103
+ expectedResources: []string{authorization.Objects("", "", "foo")},
104
+ },
105
+ {
106
+ methodName: "GetObjectClassFromName",
107
+ additionalArgs: []interface{}{strfmt.UUID("foo")},
108
+ expectedVerb: authorization.READ,
109
+ expectedResources: []string{authorization.Objects("", "", "foo")},
110
+ },
111
+ {
112
+ methodName: "HeadObject",
113
+ additionalArgs: []interface{}{"class", strfmt.UUID("foo")},
114
+ expectedVerb: authorization.READ,
115
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
116
+ },
117
+ { // deprecated by the one above
118
+ methodName: "HeadObject",
119
+ additionalArgs: []interface{}{"", strfmt.UUID("foo")},
120
+ expectedVerb: authorization.READ,
121
+ expectedResources: []string{authorization.Objects("", "", "foo")},
122
+ },
123
+
124
+ // query objects
125
+ {
126
+ methodName: "Query",
127
+ additionalArgs: []interface{}{new(QueryParams)},
128
+ expectedVerb: authorization.READ,
129
+ expectedResources: []string{authorization.ShardsMetadata("", "")[0]},
130
+ },
131
+
132
+ { // list objects is deprecated by query
133
+ methodName: "GetObjects",
134
+ additionalArgs: []interface{}{(*int64)(nil), (*int64)(nil), (*string)(nil), (*string)(nil), additional.Properties{}},
135
+ expectedVerb: authorization.READ,
136
+ expectedResources: []string{authorization.Objects("", "", "")},
137
+ },
138
+
139
+ // reference on objects
140
+ {
141
+ methodName: "AddObjectReference",
142
+ additionalArgs: []interface{}{AddReferenceInput{Class: "class", ID: strfmt.UUID("foo"), Property: "some prop"}, (*models.SingleRef)(nil)},
143
+ expectedVerb: authorization.UPDATE,
144
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
145
+ },
146
+ {
147
+ methodName: "DeleteObjectReference",
148
+ additionalArgs: []interface{}{strfmt.UUID("foo"), "some prop", (*models.SingleRef)(nil)},
149
+ expectedVerb: authorization.UPDATE,
150
+ expectedResources: []string{authorization.Objects("", "", "foo")},
151
+ },
152
+ {
153
+ methodName: "UpdateObjectReferences",
154
+ additionalArgs: []interface{}{&PutReferenceInput{Class: "class", ID: strfmt.UUID("foo"), Property: "some prop"}},
155
+ expectedVerb: authorization.UPDATE,
156
+ expectedResources: []string{authorization.Objects("class", "", "foo")},
157
+ },
158
+ }
159
+
160
+ t.Run("verify that a test for every public method exists", func(t *testing.T) {
161
+ testedMethods := make([]string, len(tests))
162
+ for i, test := range tests {
163
+ testedMethods[i] = test.methodName
164
+ }
165
+
166
+ for _, method := range allExportedMethods(&Manager{}, "") {
167
+ assert.Contains(t, testedMethods, method)
168
+ }
169
+ })
170
+
171
+ t.Run("verify the tested methods require correct permissions from the authorizer", func(t *testing.T) {
172
+ principal := &models.Principal{}
173
+ logger, _ := test.NewNullLogger()
174
+ for _, test := range tests {
175
+ if test.methodName != "MergeObject" {
176
+ continue
177
+ }
178
+ t.Run(test.methodName, func(t *testing.T) {
179
+ schemaManager := &fakeSchemaManager{}
180
+ cfg := &config.WeaviateConfig{}
181
+ authorizer := mocks.NewMockAuthorizer()
182
+ authorizer.SetErr(errors.New("just a test fake"))
183
+ vectorRepo := &fakeVectorRepo{}
184
+ manager := NewManager(schemaManager,
185
+ cfg, logger, authorizer,
186
+ vectorRepo, getFakeModulesProvider(), nil, nil,
187
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
188
+
189
+ args := append([]interface{}{context.Background(), principal}, test.additionalArgs...)
190
+ out, _ := callFuncByName(manager, test.methodName, args...)
191
+
192
+ require.Len(t, authorizer.Calls(), 1, "authorizer must be called")
193
+ aerr := out[len(out)-1].Interface().(error)
194
+ var customErr *Error
195
+ if !errors.As(aerr, &customErr) || !customErr.Forbidden() {
196
+ assert.Equal(t, errors.New("just a test fake"), aerr,
197
+ "execution must abort with authorizer error")
198
+ }
199
+
200
+ assert.Equal(t, mocks.AuthZReq{Principal: principal, Verb: test.expectedVerb, Resources: test.expectedResources},
201
+ authorizer.Calls()[0], "correct parameters must have been used on authorizer")
202
+ })
203
+ }
204
+ })
205
+ }
206
+
207
+ func Test_BatchKinds_Authorization(t *testing.T) {
208
+ type testCase struct {
209
+ methodName string
210
+ additionalArgs []interface{}
211
+ expectedVerb string
212
+ expectedResources []string
213
+ }
214
+
215
+ uri := strfmt.URI("weaviate://localhost/Class/" + uuid.New().String())
216
+
217
+ tests := []testCase{
218
+ {
219
+ methodName: "AddObjects",
220
+ additionalArgs: []interface{}{
221
+ []*models.Object{{}},
222
+ []*string{},
223
+ &additional.ReplicationProperties{},
224
+ },
225
+ expectedVerb: authorization.UPDATE,
226
+ expectedResources: authorization.ShardsData("", ""),
227
+ },
228
+ {
229
+ methodName: "AddReferences",
230
+ additionalArgs: []interface{}{
231
+ []*models.BatchReference{{From: uri + "/ref", To: uri, Tenant: ""}},
232
+ &additional.ReplicationProperties{},
233
+ },
234
+ expectedVerb: authorization.UPDATE,
235
+ expectedResources: authorization.ShardsData("Class", ""),
236
+ },
237
+ {
238
+ methodName: "DeleteObjects",
239
+ additionalArgs: []interface{}{
240
+ &models.BatchDeleteMatch{},
241
+ (*int64)(nil),
242
+ (*bool)(nil),
243
+ (*string)(nil),
244
+ &additional.ReplicationProperties{},
245
+ "",
246
+ },
247
+ expectedVerb: authorization.DELETE,
248
+ expectedResources: authorization.ShardsData("", ""),
249
+ },
250
+ }
251
+
252
+ t.Run("verify that a test for every public method exists", func(t *testing.T) {
253
+ testedMethods := make([]string, len(tests))
254
+ for i, test := range tests {
255
+ testedMethods[i] = test.methodName
256
+ }
257
+
258
+ // exception is public method for GRPC which has its own authorization check
259
+ for _, method := range allExportedMethods(&BatchManager{}, "DeleteObjectsFromGRPCAfterAuth", "AddObjectsGRPCAfterAuth") {
260
+ assert.Contains(t, testedMethods, method)
261
+ }
262
+ })
263
+
264
+ t.Run("verify the tested methods require correct permissions from the authorizer", func(t *testing.T) {
265
+ principal := &models.Principal{}
266
+ logger, _ := test.NewNullLogger()
267
+ for _, test := range tests {
268
+ schemaManager := &fakeSchemaManager{}
269
+ cfg := &config.WeaviateConfig{}
270
+ authorizer := mocks.NewMockAuthorizer()
271
+ authorizer.SetErr(errors.New("just a test fake"))
272
+ vectorRepo := &fakeVectorRepo{}
273
+ modulesProvider := getFakeModulesProvider()
274
+ manager := NewBatchManager(vectorRepo, modulesProvider, schemaManager, cfg, logger, authorizer, nil,
275
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
276
+
277
+ args := append([]interface{}{context.Background(), principal}, test.additionalArgs...)
278
+ out, _ := callFuncByName(manager, test.methodName, args...)
279
+
280
+ require.Len(t, authorizer.Calls(), 1, "authorizer must be called")
281
+ assert.Equal(t, errors.New("just a test fake"), out[len(out)-1].Interface(),
282
+ "execution must abort with authorizer error")
283
+ assert.Equal(t, mocks.AuthZReq{Principal: principal, Verb: test.expectedVerb, Resources: test.expectedResources},
284
+ authorizer.Calls()[0], "correct parameters must have been used on authorizer")
285
+ }
286
+ })
287
+ }
288
+
289
+ // inspired by https://stackoverflow.com/a/33008200
290
+ func callFuncByName(manager interface{}, funcName string, params ...interface{}) (out []reflect.Value, err error) {
291
+ managerValue := reflect.ValueOf(manager)
292
+ m := managerValue.MethodByName(funcName)
293
+ if !m.IsValid() {
294
+ return make([]reflect.Value, 0), fmt.Errorf("Method not found \"%s\"", funcName)
295
+ }
296
+ in := make([]reflect.Value, len(params))
297
+ for i, param := range params {
298
+ in[i] = reflect.ValueOf(param)
299
+ }
300
+ out = m.Call(in)
301
+ return
302
+ }
303
+
304
+ func allExportedMethods(subject interface{}, exceptions ...string) []string {
305
+ var methods []string
306
+ subjectType := reflect.TypeOf(subject)
307
+ methodLoop:
308
+ for i := 0; i < subjectType.NumMethod(); i++ {
309
+ name := subjectType.Method(i).Name
310
+ for j := range exceptions {
311
+ if name == exceptions[j] {
312
+ continue methodLoop
313
+ }
314
+ }
315
+ if name[0] >= 'A' && name[0] <= 'Z' {
316
+ methods = append(methods, name)
317
+ }
318
+ }
319
+
320
+ return methods
321
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/auto_schema.go ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "encoding/json"
17
+ "fmt"
18
+ "strings"
19
+ "sync"
20
+ "time"
21
+
22
+ "github.com/google/uuid"
23
+ "github.com/prometheus/client_golang/prometheus"
24
+ "github.com/prometheus/client_golang/prometheus/promauto"
25
+ "github.com/sirupsen/logrus"
26
+
27
+ "github.com/weaviate/weaviate/entities/additional"
28
+ "github.com/weaviate/weaviate/entities/classcache"
29
+ "github.com/weaviate/weaviate/entities/models"
30
+ "github.com/weaviate/weaviate/entities/schema"
31
+ "github.com/weaviate/weaviate/entities/schema/crossref"
32
+ "github.com/weaviate/weaviate/entities/search"
33
+ "github.com/weaviate/weaviate/entities/versioned"
34
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
35
+ "github.com/weaviate/weaviate/usecases/config"
36
+ "github.com/weaviate/weaviate/usecases/objects/validation"
37
+ )
38
+
39
+ type AutoSchemaManager struct {
40
+ mutex sync.RWMutex
41
+ authorizer authorization.Authorizer
42
+ schemaManager schemaManager
43
+ vectorRepo VectorRepo
44
+ config config.AutoSchema
45
+ logger logrus.FieldLogger
46
+
47
+ // Metrics without labels to avoid cardinality issues
48
+ opsDuration *prometheus.HistogramVec
49
+ tenantsCount prometheus.Counter
50
+ }
51
+
52
+ func NewAutoSchemaManager(schemaManager schemaManager, vectorRepo VectorRepo,
53
+ config *config.WeaviateConfig, authorizer authorization.Authorizer, logger logrus.FieldLogger,
54
+ reg prometheus.Registerer,
55
+ ) *AutoSchemaManager {
56
+ r := promauto.With(reg)
57
+
58
+ tenantsCount := r.NewCounter(
59
+ prometheus.CounterOpts{
60
+ Name: "weaviate_auto_tenant_total",
61
+ Help: "Total number of tenants processed",
62
+ },
63
+ )
64
+
65
+ opDuration := r.NewHistogramVec(
66
+ prometheus.HistogramOpts{
67
+ Name: "weaviate_auto_tenant_duration_seconds",
68
+ Help: "Time spent in auto tenant operations",
69
+ },
70
+ []string{"operation"},
71
+ )
72
+
73
+ return &AutoSchemaManager{
74
+ schemaManager: schemaManager,
75
+ vectorRepo: vectorRepo,
76
+ config: config.Config.AutoSchema,
77
+ logger: logger,
78
+ authorizer: authorizer,
79
+ tenantsCount: tenantsCount,
80
+ opsDuration: opDuration,
81
+ }
82
+ }
83
+
84
+ func (m *AutoSchemaManager) autoSchema(ctx context.Context, principal *models.Principal,
85
+ allowCreateClass bool, classes map[string]versioned.Class, objects ...*models.Object,
86
+ ) (uint64, error) {
87
+ enabled := m.config.Enabled.Get()
88
+
89
+ if !enabled {
90
+ return 0, nil
91
+ }
92
+
93
+ m.mutex.Lock()
94
+ defer m.mutex.Unlock()
95
+
96
+ var maxSchemaVersion uint64
97
+
98
+ for _, object := range objects {
99
+ if object == nil {
100
+ return 0, ErrInvalidUserInput{validation.ErrorMissingObject}
101
+ }
102
+
103
+ if len(object.Class) == 0 {
104
+ // stop performing auto schema
105
+ return 0, ErrInvalidUserInput{validation.ErrorMissingClass}
106
+ }
107
+
108
+ vclass := classes[object.Class]
109
+
110
+ schemaClass := vclass.Class
111
+ schemaVersion := vclass.Version
112
+
113
+ if schemaClass == nil && !allowCreateClass {
114
+ return 0, ErrInvalidUserInput{"given class does not exist"}
115
+ }
116
+ properties, err := m.getProperties(object)
117
+ if err != nil {
118
+ return 0, err
119
+ }
120
+
121
+ if schemaClass == nil {
122
+ err := m.authorizer.Authorize(ctx, principal, authorization.CREATE, authorization.CollectionsMetadata(object.Class)...)
123
+ if err != nil {
124
+ return 0, fmt.Errorf("auto schema can't create objects because can't create collection: %w", err)
125
+ }
126
+
127
+ // it returns the newly created class and version
128
+ schemaClass, schemaVersion, err = m.createClass(ctx, principal, object.Class, properties)
129
+ if err != nil {
130
+ return 0, err
131
+ }
132
+
133
+ classes[object.Class] = versioned.Class{Class: schemaClass, Version: schemaVersion}
134
+ classcache.RemoveClassFromContext(ctx, object.Class)
135
+ } else {
136
+ if newProperties := schema.DedupProperties(schemaClass.Properties, properties); len(newProperties) > 0 {
137
+ err := m.authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.CollectionsMetadata(schemaClass.Class)...)
138
+ if err != nil {
139
+ return 0, fmt.Errorf("auto schema can't create objects because can't update collection: %w", err)
140
+ }
141
+ schemaClass, schemaVersion, err = m.schemaManager.AddClassProperty(ctx,
142
+ principal, schemaClass, schemaClass.Class, true, newProperties...)
143
+ if err != nil {
144
+ return 0, err
145
+ }
146
+ classes[object.Class] = versioned.Class{Class: schemaClass, Version: schemaVersion}
147
+ classcache.RemoveClassFromContext(ctx, object.Class)
148
+ }
149
+ }
150
+
151
+ if schemaVersion > maxSchemaVersion {
152
+ maxSchemaVersion = schemaVersion
153
+ }
154
+ }
155
+ return maxSchemaVersion, nil
156
+ }
157
+
158
+ func (m *AutoSchemaManager) createClass(ctx context.Context, principal *models.Principal,
159
+ className string, properties []*models.Property,
160
+ ) (*models.Class, uint64, error) {
161
+ now := time.Now()
162
+ class := &models.Class{
163
+ Class: className,
164
+ Properties: properties,
165
+ Description: "This property was generated by Weaviate's auto-schema feature on " + now.Format(time.ANSIC),
166
+ }
167
+ m.logger.
168
+ WithField("auto_schema", "createClass").
169
+ Debugf("create class %s", className)
170
+ newClass, schemaVersion, err := m.schemaManager.AddClass(ctx, principal, class)
171
+ return newClass, schemaVersion, err
172
+ }
173
+
174
+ func (m *AutoSchemaManager) getProperties(object *models.Object) ([]*models.Property, error) {
175
+ properties := []*models.Property{}
176
+ if props, ok := object.Properties.(map[string]interface{}); ok {
177
+ for name, value := range props {
178
+ now := time.Now()
179
+ dt, err := m.determineType(value, false)
180
+ if err != nil {
181
+ return nil, fmt.Errorf("property '%s' on class '%s': %w", name, object.Class, err)
182
+ }
183
+
184
+ var nestedProperties []*models.NestedProperty
185
+ if len(dt) == 1 {
186
+ switch dt[0] {
187
+ case schema.DataTypeObject:
188
+ nestedProperties, err = m.determineNestedProperties(value.(map[string]interface{}), now)
189
+ case schema.DataTypeObjectArray:
190
+ nestedProperties, err = m.determineNestedPropertiesOfArray(value.([]interface{}), now)
191
+ default:
192
+ // do nothing
193
+ }
194
+ }
195
+ if err != nil {
196
+ return nil, fmt.Errorf("property '%s' on class '%s': %w", name, object.Class, err)
197
+ }
198
+
199
+ property := &models.Property{
200
+ Name: name,
201
+ DataType: m.getDataTypes(dt),
202
+ Description: "This property was generated by Weaviate's auto-schema feature on " + now.Format(time.ANSIC),
203
+ NestedProperties: nestedProperties,
204
+ }
205
+ properties = append(properties, property)
206
+ }
207
+ }
208
+ return properties, nil
209
+ }
210
+
211
+ func (m *AutoSchemaManager) getDataTypes(dataTypes []schema.DataType) []string {
212
+ dtypes := make([]string, len(dataTypes))
213
+ for i := range dataTypes {
214
+ dtypes[i] = string(dataTypes[i])
215
+ }
216
+ return dtypes
217
+ }
218
+
219
+ func (m *AutoSchemaManager) determineType(value interface{}, ofNestedProp bool) ([]schema.DataType, error) {
220
+ fallbackDataType := []schema.DataType{schema.DataTypeText}
221
+ fallbackArrayDataType := []schema.DataType{schema.DataTypeTextArray}
222
+
223
+ switch typedValue := value.(type) {
224
+ case string:
225
+ if _, err := time.Parse(time.RFC3339, typedValue); err == nil {
226
+ return []schema.DataType{schema.DataType(m.config.DefaultDate)}, nil
227
+ }
228
+ if _, err := uuid.Parse(typedValue); err == nil {
229
+ return []schema.DataType{schema.DataTypeUUID}, nil
230
+ }
231
+ if m.config.DefaultString != "" {
232
+ return []schema.DataType{schema.DataType(m.config.DefaultString)}, nil
233
+ }
234
+ return []schema.DataType{schema.DataTypeText}, nil
235
+ case json.Number:
236
+ return []schema.DataType{schema.DataType(m.config.DefaultNumber)}, nil
237
+ case float64:
238
+ return []schema.DataType{schema.DataTypeNumber}, nil
239
+ case int64:
240
+ return []schema.DataType{schema.DataTypeInt}, nil
241
+ case bool:
242
+ return []schema.DataType{schema.DataTypeBoolean}, nil
243
+ case map[string]interface{}:
244
+ // nested properties does not support phone and geo data types
245
+ if !ofNestedProp {
246
+ if dt, ok := m.asGeoCoordinatesType(typedValue); ok {
247
+ return dt, nil
248
+ }
249
+ if dt, ok := m.asPhoneNumber(typedValue); ok {
250
+ return dt, nil
251
+ }
252
+ }
253
+ return []schema.DataType{schema.DataTypeObject}, nil
254
+ case []interface{}:
255
+ if len(typedValue) == 0 {
256
+ return fallbackArrayDataType, nil
257
+ }
258
+
259
+ refDataTypes := []schema.DataType{}
260
+ var isRef bool
261
+ var determinedDataType schema.DataType
262
+
263
+ for i := range typedValue {
264
+ dataType, refDataType, err := m.determineArrayType(typedValue[i], ofNestedProp)
265
+ if err != nil {
266
+ return nil, fmt.Errorf("element [%d]: %w", i, err)
267
+ }
268
+ if i == 0 {
269
+ isRef = refDataType != ""
270
+ determinedDataType = dataType
271
+ }
272
+ if dataType != "" {
273
+ // if an array contains text and UUID/Date, the type should be text
274
+ if determinedDataType == schema.DataTypeTextArray && (dataType == schema.DataTypeUUIDArray || dataType == schema.DataTypeDateArray) {
275
+ continue
276
+ }
277
+ if determinedDataType == schema.DataTypeDateArray && (dataType == schema.DataTypeUUIDArray || dataType == schema.DataTypeTextArray) {
278
+ determinedDataType = schema.DataTypeTextArray
279
+ continue
280
+ }
281
+ if determinedDataType == schema.DataTypeUUIDArray && (dataType == schema.DataTypeDateArray || dataType == schema.DataTypeTextArray) {
282
+ determinedDataType = schema.DataTypeTextArray
283
+ continue
284
+ }
285
+
286
+ if isRef {
287
+ return nil, fmt.Errorf("element [%d]: mismatched data type - reference expected, got '%s'",
288
+ i, asSingleDataType(dataType))
289
+ }
290
+ if dataType != determinedDataType {
291
+ return nil, fmt.Errorf("element [%d]: mismatched data type - '%s' expected, got '%s'",
292
+ i, asSingleDataType(determinedDataType), asSingleDataType(dataType))
293
+ }
294
+ } else {
295
+ if !isRef {
296
+ return nil, fmt.Errorf("element [%d]: mismatched data type - '%s' expected, got reference",
297
+ i, asSingleDataType(determinedDataType))
298
+ }
299
+ refDataTypes = append(refDataTypes, refDataType)
300
+ }
301
+ }
302
+ if len(refDataTypes) > 0 {
303
+ return refDataTypes, nil
304
+ }
305
+ return []schema.DataType{determinedDataType}, nil
306
+ case nil:
307
+ return fallbackDataType, nil
308
+ default:
309
+ allowed := []string{
310
+ schema.DataTypeText.String(),
311
+ schema.DataTypeNumber.String(),
312
+ schema.DataTypeInt.String(),
313
+ schema.DataTypeBoolean.String(),
314
+ schema.DataTypeDate.String(),
315
+ schema.DataTypeUUID.String(),
316
+ schema.DataTypeObject.String(),
317
+ }
318
+ if !ofNestedProp {
319
+ allowed = append(allowed, schema.DataTypePhoneNumber.String(), schema.DataTypeGeoCoordinates.String())
320
+ }
321
+ return nil, fmt.Errorf("unrecognized data type of value '%v' - one of '%s' expected",
322
+ typedValue, strings.Join(allowed, "', '"))
323
+ }
324
+ }
325
+
326
+ func asSingleDataType(arrayDataType schema.DataType) schema.DataType {
327
+ if dt, isArray := schema.IsArrayType(arrayDataType); isArray {
328
+ return dt
329
+ }
330
+ return arrayDataType
331
+ }
332
+
333
+ func (m *AutoSchemaManager) determineArrayType(value interface{}, ofNestedProp bool,
334
+ ) (schema.DataType, schema.DataType, error) {
335
+ switch typedValue := value.(type) {
336
+ case string:
337
+ if _, err := time.Parse(time.RFC3339, typedValue); err == nil {
338
+ return schema.DataTypeDateArray, "", nil
339
+ }
340
+ if _, err := uuid.Parse(typedValue); err == nil {
341
+ return schema.DataTypeUUIDArray, "", nil
342
+ }
343
+ if schema.DataType(m.config.DefaultString) == schema.DataTypeString {
344
+ return schema.DataTypeStringArray, "", nil
345
+ }
346
+ return schema.DataTypeTextArray, "", nil
347
+ case json.Number:
348
+ if schema.DataType(m.config.DefaultNumber) == schema.DataTypeInt {
349
+ return schema.DataTypeIntArray, "", nil
350
+ }
351
+ return schema.DataTypeNumberArray, "", nil
352
+ case float64:
353
+ return schema.DataTypeNumberArray, "", nil
354
+ case int64:
355
+ return schema.DataTypeIntArray, "", nil
356
+ case bool:
357
+ return schema.DataTypeBooleanArray, "", nil
358
+ case map[string]interface{}:
359
+ if ofNestedProp {
360
+ return schema.DataTypeObjectArray, "", nil
361
+ }
362
+ if refDataType, ok := m.asRef(typedValue); ok {
363
+ return "", refDataType, nil
364
+ }
365
+ return schema.DataTypeObjectArray, "", nil
366
+ default:
367
+ allowed := []string{
368
+ schema.DataTypeText.String(),
369
+ schema.DataTypeNumber.String(),
370
+ schema.DataTypeInt.String(),
371
+ schema.DataTypeBoolean.String(),
372
+ schema.DataTypeDate.String(),
373
+ schema.DataTypeUUID.String(),
374
+ schema.DataTypeObject.String(),
375
+ }
376
+ if !ofNestedProp {
377
+ allowed = append(allowed, schema.DataTypeCRef.String())
378
+ }
379
+ return "", "", fmt.Errorf("unrecognized data type of value '%v' - one of '%s' expected",
380
+ typedValue, strings.Join(allowed, "', '"))
381
+ }
382
+ }
383
+
384
+ func (m *AutoSchemaManager) asGeoCoordinatesType(val map[string]interface{}) ([]schema.DataType, bool) {
385
+ if len(val) == 2 {
386
+ if val["latitude"] != nil && val["longitude"] != nil {
387
+ return []schema.DataType{schema.DataTypeGeoCoordinates}, true
388
+ }
389
+ }
390
+ return nil, false
391
+ }
392
+
393
+ func (m *AutoSchemaManager) asPhoneNumber(val map[string]interface{}) ([]schema.DataType, bool) {
394
+ if val["input"] != nil {
395
+ if len(val) == 1 {
396
+ return []schema.DataType{schema.DataTypePhoneNumber}, true
397
+ }
398
+ if len(val) == 2 {
399
+ if _, ok := val["defaultCountry"]; ok {
400
+ return []schema.DataType{schema.DataTypePhoneNumber}, true
401
+ }
402
+ }
403
+ }
404
+
405
+ return nil, false
406
+ }
407
+
408
+ func (m *AutoSchemaManager) asRef(val map[string]interface{}) (schema.DataType, bool) {
409
+ if v, ok := val["beacon"]; ok {
410
+ if beacon, ok := v.(string); ok {
411
+ ref, err := crossref.Parse(beacon)
412
+ if err == nil {
413
+ if ref.Class == "" {
414
+ res, err := m.vectorRepo.ObjectByID(context.Background(), ref.TargetID, search.SelectProperties{}, additional.Properties{}, "")
415
+ if err == nil && res != nil {
416
+ return schema.DataType(res.ClassName), true
417
+ }
418
+ } else {
419
+ return schema.DataType(ref.Class), true
420
+ }
421
+ }
422
+ }
423
+ }
424
+ return "", false
425
+ }
426
+
427
+ func (m *AutoSchemaManager) determineNestedProperties(values map[string]interface{}, now time.Time,
428
+ ) ([]*models.NestedProperty, error) {
429
+ i := 0
430
+ nestedProperties := make([]*models.NestedProperty, len(values))
431
+ for name, value := range values {
432
+ np, err := m.determineNestedProperty(name, value, now)
433
+ if err != nil {
434
+ return nil, fmt.Errorf("nested property '%s': %w", name, err)
435
+ }
436
+ nestedProperties[i] = np
437
+ i++
438
+ }
439
+ return nestedProperties, nil
440
+ }
441
+
442
+ func (m *AutoSchemaManager) determineNestedProperty(name string, value interface{}, now time.Time,
443
+ ) (*models.NestedProperty, error) {
444
+ dt, err := m.determineType(value, true)
445
+ if err != nil {
446
+ return nil, err
447
+ }
448
+
449
+ var np []*models.NestedProperty
450
+ if len(dt) == 1 {
451
+ switch dt[0] {
452
+ case schema.DataTypeObject:
453
+ np, err = m.determineNestedProperties(value.(map[string]interface{}), now)
454
+ case schema.DataTypeObjectArray:
455
+ np, err = m.determineNestedPropertiesOfArray(value.([]interface{}), now)
456
+ default:
457
+ // do nothing
458
+ }
459
+ }
460
+ if err != nil {
461
+ return nil, err
462
+ }
463
+
464
+ return &models.NestedProperty{
465
+ Name: name,
466
+ DataType: m.getDataTypes(dt),
467
+ Description: "This nested property was generated by Weaviate's auto-schema feature on " +
468
+ now.Format(time.ANSIC),
469
+ NestedProperties: np,
470
+ }, nil
471
+ }
472
+
473
+ func (m *AutoSchemaManager) determineNestedPropertiesOfArray(valArray []interface{}, now time.Time,
474
+ ) ([]*models.NestedProperty, error) {
475
+ if len(valArray) == 0 {
476
+ return []*models.NestedProperty{}, nil
477
+ }
478
+ nestedProperties, err := m.determineNestedProperties(valArray[0].(map[string]interface{}), now)
479
+ if err != nil {
480
+ return nil, err
481
+ }
482
+ if len(valArray) == 1 {
483
+ return nestedProperties, nil
484
+ }
485
+
486
+ nestedPropertiesIndexMap := make(map[string]int, len(nestedProperties))
487
+ for index := range nestedProperties {
488
+ nestedPropertiesIndexMap[nestedProperties[index].Name] = index
489
+ }
490
+
491
+ for i := 1; i < len(valArray); i++ {
492
+ values := valArray[i].(map[string]interface{})
493
+ for name, value := range values {
494
+ index, ok := nestedPropertiesIndexMap[name]
495
+ if !ok {
496
+ np, err := m.determineNestedProperty(name, value, now)
497
+ if err != nil {
498
+ return nil, err
499
+ }
500
+ nestedPropertiesIndexMap[name] = len(nestedProperties)
501
+ nestedProperties = append(nestedProperties, np)
502
+ } else if _, isNested := schema.AsNested(nestedProperties[index].DataType); isNested {
503
+ np, err := m.determineNestedProperty(name, value, now)
504
+ if err != nil {
505
+ return nil, err
506
+ }
507
+ if mergedNestedProperties, merged := schema.MergeRecursivelyNestedProperties(
508
+ nestedProperties[index].NestedProperties, np.NestedProperties,
509
+ ); merged {
510
+ nestedProperties[index].NestedProperties = mergedNestedProperties
511
+ }
512
+ }
513
+ }
514
+ }
515
+
516
+ return nestedProperties, nil
517
+ }
518
+
519
+ func (m *AutoSchemaManager) autoTenants(ctx context.Context,
520
+ principal *models.Principal, objects []*models.Object, fetchedClasses map[string]versioned.Class,
521
+ ) (uint64, int, error) {
522
+ start := time.Now()
523
+ defer func() {
524
+ m.opsDuration.With(prometheus.Labels{
525
+ "operation": "total",
526
+ }).Observe(time.Since(start).Seconds())
527
+ }()
528
+
529
+ classTenants := make(map[string]map[string]struct{})
530
+
531
+ // group by tenants by class
532
+ for _, obj := range objects {
533
+ if _, ok := classTenants[obj.Class]; !ok {
534
+ classTenants[obj.Class] = map[string]struct{}{}
535
+ }
536
+ classTenants[obj.Class][obj.Tenant] = struct{}{}
537
+ }
538
+
539
+ totalTenants := 0
540
+ // skip invalid classes, non-MT classes, no auto tenant creation classes
541
+ var maxSchemaVersion uint64
542
+ for className, tenantNames := range classTenants {
543
+ vclass, exists := fetchedClasses[className]
544
+ if !exists || // invalid class
545
+ vclass.Class == nil { // class is nil
546
+ continue
547
+ }
548
+ totalTenants += len(tenantNames)
549
+
550
+ if !schema.MultiTenancyEnabled(vclass.Class) || // non-MT class
551
+ !vclass.Class.MultiTenancyConfig.AutoTenantCreation { // no auto tenant creation
552
+ continue
553
+ }
554
+ names := make([]string, len(tenantNames))
555
+ tenants := make([]*models.Tenant, len(tenantNames))
556
+ i := 0
557
+ for name := range tenantNames {
558
+ names[i] = name
559
+ tenants[i] = &models.Tenant{Name: name}
560
+ i++
561
+ }
562
+ err := m.authorizer.Authorize(ctx, principal, authorization.CREATE, authorization.ShardsMetadata(className, names...)...)
563
+ if err != nil {
564
+ return 0, totalTenants, fmt.Errorf("add tenants because can't create collection: %w", err)
565
+ }
566
+
567
+ addStart := time.Now()
568
+ if err := m.addTenants(ctx, principal, className, tenants); err != nil {
569
+ return 0, totalTenants, fmt.Errorf("add tenants to class %q: %w", className, err)
570
+ }
571
+ m.tenantsCount.Add(float64(len(tenants)))
572
+ m.opsDuration.With(prometheus.Labels{
573
+ "operation": "add",
574
+ }).Observe(time.Since(addStart).Seconds())
575
+
576
+ if vclass.Version > maxSchemaVersion {
577
+ maxSchemaVersion = vclass.Version
578
+ }
579
+ }
580
+
581
+ if totalTenants == 0 {
582
+ // if we exclusively hit non-MT classes, count them as a single tenant
583
+ totalTenants = 1
584
+ }
585
+
586
+ return maxSchemaVersion, totalTenants, nil
587
+ }
588
+
589
+ func (m *AutoSchemaManager) addTenants(ctx context.Context, principal *models.Principal,
590
+ class string, tenants []*models.Tenant,
591
+ ) error {
592
+ if len(tenants) == 0 {
593
+ return fmt.Errorf(
594
+ "tenants must be included for multitenant-enabled class %q", class)
595
+ }
596
+ version, err := m.schemaManager.AddTenants(ctx, principal, class, tenants)
597
+ if err != nil {
598
+ return err
599
+ }
600
+
601
+ err = m.schemaManager.WaitForUpdate(ctx, version)
602
+ if err != nil {
603
+ return fmt.Errorf("could not wait for update: %w", err)
604
+ }
605
+
606
+ return nil
607
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/auto_schema_test.go ADDED
@@ -0,0 +1,1712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "encoding/json"
17
+ "fmt"
18
+ "reflect"
19
+ "testing"
20
+
21
+ "github.com/go-openapi/strfmt"
22
+ "github.com/sirupsen/logrus/hooks/test"
23
+ "github.com/stretchr/testify/assert"
24
+ "github.com/stretchr/testify/mock"
25
+ "github.com/stretchr/testify/require"
26
+
27
+ "github.com/weaviate/weaviate/entities/models"
28
+ "github.com/weaviate/weaviate/entities/schema"
29
+ "github.com/weaviate/weaviate/entities/schema/test_utils"
30
+ "github.com/weaviate/weaviate/entities/search"
31
+ "github.com/weaviate/weaviate/entities/versioned"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ "github.com/weaviate/weaviate/usecases/config/runtime"
34
+ "github.com/weaviate/weaviate/usecases/objects/validation"
35
+ )
36
+
37
+ func Test_autoSchemaManager_determineType(t *testing.T) {
38
+ type fields struct {
39
+ config config.AutoSchema
40
+ }
41
+ type args struct {
42
+ value interface{}
43
+ }
44
+
45
+ autoSchemaEnabledFields := fields{
46
+ config: config.AutoSchema{
47
+ Enabled: runtime.NewDynamicValue(true),
48
+ },
49
+ }
50
+
51
+ tests := []struct {
52
+ name string
53
+ fields fields
54
+ args args
55
+ want []schema.DataType
56
+ errMsgs []string
57
+ }{
58
+ {
59
+ name: "fail determining type of nested array (1)",
60
+ fields: fields{
61
+ config: config.AutoSchema{
62
+ Enabled: runtime.NewDynamicValue(true),
63
+ DefaultString: schema.DataTypeText.String(),
64
+ },
65
+ },
66
+ args: args{
67
+ value: []interface{}{[]interface{}{"panic"}},
68
+ },
69
+ errMsgs: []string{"unrecognized data type"},
70
+ },
71
+ {
72
+ name: "fail determining type of nested array (2)",
73
+ fields: fields{
74
+ config: config.AutoSchema{
75
+ Enabled: runtime.NewDynamicValue(true),
76
+ DefaultString: schema.DataTypeText.String(),
77
+ },
78
+ },
79
+ args: args{
80
+ value: []interface{}{[]string{}},
81
+ },
82
+ errMsgs: []string{"unrecognized data type"},
83
+ },
84
+ {
85
+ name: "fail determining type of mixed elements in array",
86
+ fields: fields{
87
+ config: config.AutoSchema{
88
+ Enabled: runtime.NewDynamicValue(true),
89
+ DefaultString: schema.DataTypeText.String(),
90
+ },
91
+ },
92
+ args: args{
93
+ value: []interface{}{"something", false},
94
+ },
95
+ errMsgs: []string{"mismatched data type", "'text' expected, got 'boolean'"},
96
+ },
97
+ {
98
+ name: "fail determining type of mixed refs and objects (1)",
99
+ fields: fields{
100
+ config: config.AutoSchema{
101
+ Enabled: runtime.NewDynamicValue(true),
102
+ },
103
+ },
104
+ args: args{
105
+ value: []interface{}{
106
+ map[string]interface{}{"beacon": "weaviate://localhost/df48b9f6-ba48-470c-bf6a-57657cb07390"},
107
+ map[string]interface{}{"propOfObject": "something"},
108
+ },
109
+ },
110
+ errMsgs: []string{"mismatched data type", "reference expected, got 'object'"},
111
+ },
112
+ {
113
+ name: "fail determining type of mixed refs and objects (2)",
114
+ fields: fields{
115
+ config: config.AutoSchema{
116
+ Enabled: runtime.NewDynamicValue(true),
117
+ },
118
+ },
119
+ args: args{
120
+ value: []interface{}{
121
+ map[string]interface{}{"propOfObject": "something"},
122
+ map[string]interface{}{"beacon": "weaviate://localhost/df48b9f6-ba48-470c-bf6a-57657cb07390"},
123
+ },
124
+ },
125
+ errMsgs: []string{"mismatched data type", "'object' expected, got reference"},
126
+ },
127
+ {
128
+ name: "determine text",
129
+ fields: fields{
130
+ config: config.AutoSchema{
131
+ Enabled: runtime.NewDynamicValue(true),
132
+ DefaultString: schema.DataTypeText.String(),
133
+ },
134
+ },
135
+ args: args{
136
+ value: "string",
137
+ },
138
+ want: []schema.DataType{schema.DataTypeText},
139
+ },
140
+ {
141
+ name: "determine text (implicit)",
142
+ fields: fields{
143
+ config: config.AutoSchema{
144
+ Enabled: runtime.NewDynamicValue(true),
145
+ },
146
+ },
147
+ args: args{
148
+ value: "string",
149
+ },
150
+ want: []schema.DataType{schema.DataTypeText},
151
+ },
152
+ {
153
+ name: "determine date",
154
+ fields: fields{
155
+ config: config.AutoSchema{
156
+ Enabled: runtime.NewDynamicValue(true),
157
+ DefaultDate: "date",
158
+ },
159
+ },
160
+ args: args{
161
+ value: "2002-10-02T15:00:00Z",
162
+ },
163
+ want: []schema.DataType{schema.DataTypeDate},
164
+ },
165
+ {
166
+ name: "determine uuid (1)",
167
+ fields: fields{
168
+ config: config.AutoSchema{
169
+ Enabled: runtime.NewDynamicValue(true),
170
+ },
171
+ },
172
+ args: args{
173
+ value: "5b2cbe85-c38a-41f7-9e8c-7406ff6d15aa",
174
+ },
175
+ want: []schema.DataType{schema.DataTypeUUID},
176
+ },
177
+ {
178
+ name: "determine uuid (2)",
179
+ fields: fields{
180
+ config: config.AutoSchema{
181
+ Enabled: runtime.NewDynamicValue(true),
182
+ },
183
+ },
184
+ args: args{
185
+ value: "5b2cbe85c38a41f79e8c7406ff6d15aa",
186
+ },
187
+ want: []schema.DataType{schema.DataTypeUUID},
188
+ },
189
+ {
190
+ name: "determine int",
191
+ fields: fields{
192
+ config: config.AutoSchema{
193
+ Enabled: runtime.NewDynamicValue(true),
194
+ DefaultNumber: "int",
195
+ },
196
+ },
197
+ args: args{
198
+ value: json.Number("1"),
199
+ },
200
+ want: []schema.DataType{schema.DataTypeInt},
201
+ },
202
+ {
203
+ name: "determine number",
204
+ fields: fields{
205
+ config: config.AutoSchema{
206
+ Enabled: runtime.NewDynamicValue(true),
207
+ DefaultNumber: "number",
208
+ },
209
+ },
210
+ args: args{
211
+ value: json.Number("1"),
212
+ },
213
+ want: []schema.DataType{schema.DataTypeNumber},
214
+ },
215
+ {
216
+ name: "determine boolean",
217
+ fields: fields{
218
+ config: config.AutoSchema{
219
+ Enabled: runtime.NewDynamicValue(true),
220
+ DefaultNumber: "number",
221
+ },
222
+ },
223
+ args: args{
224
+ value: true,
225
+ },
226
+ want: []schema.DataType{schema.DataTypeBoolean},
227
+ },
228
+ {
229
+ name: "determine geoCoordinates",
230
+ fields: fields{
231
+ config: config.AutoSchema{
232
+ Enabled: runtime.NewDynamicValue(true),
233
+ },
234
+ },
235
+ args: args{
236
+ value: map[string]interface{}{
237
+ "latitude": json.Number("1.1"),
238
+ "longitude": json.Number("1.1"),
239
+ },
240
+ },
241
+ want: []schema.DataType{schema.DataTypeGeoCoordinates},
242
+ },
243
+ {
244
+ name: "determine phoneNumber",
245
+ fields: fields{
246
+ config: config.AutoSchema{
247
+ Enabled: runtime.NewDynamicValue(true),
248
+ },
249
+ },
250
+ args: args{
251
+ value: map[string]interface{}{
252
+ "input": "020 1234567",
253
+ },
254
+ },
255
+ want: []schema.DataType{schema.DataTypePhoneNumber},
256
+ },
257
+ {
258
+ name: "determine phoneNumber (2)",
259
+ fields: fields{
260
+ config: config.AutoSchema{
261
+ Enabled: runtime.NewDynamicValue(true),
262
+ },
263
+ },
264
+ args: args{
265
+ value: map[string]interface{}{
266
+ "input": "020 1234567",
267
+ "defaultCountry": "nl",
268
+ },
269
+ },
270
+ want: []schema.DataType{schema.DataTypePhoneNumber},
271
+ },
272
+ {
273
+ name: "determine cross reference",
274
+ fields: fields{
275
+ config: config.AutoSchema{
276
+ Enabled: runtime.NewDynamicValue(true),
277
+ },
278
+ },
279
+ args: args{
280
+ value: []interface{}{
281
+ map[string]interface{}{"beacon": "weaviate://localhost/df48b9f6-ba48-470c-bf6a-57657cb07390"},
282
+ },
283
+ },
284
+ want: []schema.DataType{schema.DataType("Publication")},
285
+ },
286
+ {
287
+ name: "determine cross references",
288
+ fields: fields{
289
+ config: config.AutoSchema{
290
+ Enabled: runtime.NewDynamicValue(true),
291
+ },
292
+ },
293
+ args: args{
294
+ value: []interface{}{
295
+ map[string]interface{}{"beacon": "weaviate://localhost/df48b9f6-ba48-470c-bf6a-57657cb07390"},
296
+ map[string]interface{}{"beacon": "weaviate://localhost/df48b9f6-ba48-470c-bf6a-57657cb07391"},
297
+ },
298
+ },
299
+ want: []schema.DataType{schema.DataType("Publication"), schema.DataType("Article")},
300
+ },
301
+ {
302
+ name: "determine text array",
303
+ fields: fields{
304
+ config: config.AutoSchema{
305
+ Enabled: runtime.NewDynamicValue(true),
306
+ DefaultString: schema.DataTypeText.String(),
307
+ },
308
+ },
309
+ args: args{
310
+ value: []interface{}{"a", "b"},
311
+ },
312
+ want: []schema.DataType{schema.DataTypeTextArray},
313
+ },
314
+ {
315
+ name: "determine text array (implicit)",
316
+ fields: fields{
317
+ config: config.AutoSchema{
318
+ Enabled: runtime.NewDynamicValue(true),
319
+ },
320
+ },
321
+ args: args{
322
+ value: []interface{}{"a", "b"},
323
+ },
324
+ want: []schema.DataType{schema.DataTypeTextArray},
325
+ },
326
+ {
327
+ name: "determine int array",
328
+ fields: fields{
329
+ config: config.AutoSchema{
330
+ Enabled: runtime.NewDynamicValue(true),
331
+ DefaultNumber: "int",
332
+ },
333
+ },
334
+ args: args{
335
+ value: []interface{}{json.Number("11"), json.Number("12")},
336
+ },
337
+ want: []schema.DataType{schema.DataTypeIntArray},
338
+ },
339
+ {
340
+ name: "determine number array",
341
+ fields: fields{
342
+ config: config.AutoSchema{
343
+ Enabled: runtime.NewDynamicValue(true),
344
+ DefaultNumber: "number",
345
+ },
346
+ },
347
+ args: args{
348
+ value: []interface{}{json.Number("1.1"), json.Number("1.2")},
349
+ },
350
+ want: []schema.DataType{schema.DataTypeNumberArray},
351
+ },
352
+ {
353
+ name: "determine boolean array",
354
+ fields: fields{
355
+ config: config.AutoSchema{
356
+ Enabled: runtime.NewDynamicValue(true),
357
+ },
358
+ },
359
+ args: args{
360
+ value: []interface{}{true, false},
361
+ },
362
+ want: []schema.DataType{schema.DataTypeBooleanArray},
363
+ },
364
+ {
365
+ name: "determine date array",
366
+ fields: fields{
367
+ config: config.AutoSchema{
368
+ Enabled: runtime.NewDynamicValue(true),
369
+ DefaultDate: "date",
370
+ },
371
+ },
372
+ args: args{
373
+ value: []interface{}{"2002-10-02T15:00:00Z", "2002-10-02T15:01:00Z"},
374
+ },
375
+ want: []schema.DataType{schema.DataTypeDateArray},
376
+ },
377
+ {
378
+ name: "determine uuid array (1)",
379
+ fields: fields{
380
+ config: config.AutoSchema{
381
+ Enabled: runtime.NewDynamicValue(true),
382
+ },
383
+ },
384
+ args: args{
385
+ value: []interface{}{
386
+ "5b2cbe85-c38a-41f7-9e8c-7406ff6d15aa",
387
+ "57a8564d-089b-4cd9-be39-56681605e0da",
388
+ },
389
+ },
390
+ want: []schema.DataType{schema.DataTypeUUIDArray},
391
+ },
392
+ {
393
+ name: "determine uuid array (2)",
394
+ fields: fields{
395
+ config: config.AutoSchema{
396
+ Enabled: runtime.NewDynamicValue(true),
397
+ },
398
+ },
399
+ args: args{
400
+ value: []interface{}{
401
+ "5b2cbe85c38a41f79e8c7406ff6d15aa",
402
+ "57a8564d089b4cd9be3956681605e0da",
403
+ },
404
+ },
405
+ want: []schema.DataType{schema.DataTypeUUIDArray},
406
+ },
407
+ {
408
+ name: "determine mixed string arrays, string first",
409
+ fields: fields{
410
+ config: config.AutoSchema{
411
+ Enabled: runtime.NewDynamicValue(true),
412
+ },
413
+ },
414
+ args: args{
415
+ value: []interface{}{
416
+ "string",
417
+ "57a8564d089b4cd9be3956681605e0da",
418
+ },
419
+ },
420
+ want: []schema.DataType{schema.DataTypeTextArray},
421
+ },
422
+ {
423
+ name: "determine mixed string/UUID arrays, string later",
424
+ fields: fields{
425
+ config: config.AutoSchema{
426
+ Enabled: runtime.NewDynamicValue(true),
427
+ },
428
+ },
429
+ args: args{
430
+ value: []interface{}{
431
+ "57a8564d089b4cd9be3956681605e0da",
432
+ "string",
433
+ },
434
+ },
435
+ want: []schema.DataType{schema.DataTypeTextArray},
436
+ },
437
+ {
438
+ name: "determine mixed string/date arrays, string later",
439
+ fields: fields{
440
+ config: config.AutoSchema{
441
+ Enabled: runtime.NewDynamicValue(true),
442
+ },
443
+ },
444
+ args: args{
445
+ value: []interface{}{
446
+ "2002-10-02T15:00:00Z",
447
+ "string",
448
+ },
449
+ },
450
+ want: []schema.DataType{schema.DataTypeTextArray},
451
+ },
452
+ {
453
+ name: "[deprecated string] determine string",
454
+ fields: fields{
455
+ config: config.AutoSchema{
456
+ Enabled: runtime.NewDynamicValue(true),
457
+ DefaultString: schema.DataTypeString.String(),
458
+ },
459
+ },
460
+ args: args{
461
+ value: "string",
462
+ },
463
+ want: []schema.DataType{schema.DataTypeString},
464
+ },
465
+ {
466
+ name: "[deprecated string] determine string array",
467
+ fields: fields{
468
+ config: config.AutoSchema{
469
+ Enabled: runtime.NewDynamicValue(true),
470
+ DefaultString: schema.DataTypeString.String(),
471
+ },
472
+ },
473
+ args: args{
474
+ value: []interface{}{"a", "b"},
475
+ },
476
+ want: []schema.DataType{schema.DataTypeStringArray},
477
+ },
478
+ {
479
+ name: "determine object",
480
+ fields: autoSchemaEnabledFields,
481
+ args: args{
482
+ value: map[string]interface{}{
483
+ "some_number": 1.23,
484
+ "some_bool": false,
485
+ },
486
+ },
487
+ want: []schema.DataType{schema.DataTypeObject},
488
+ },
489
+ {
490
+ name: "determine object array",
491
+ fields: autoSchemaEnabledFields,
492
+ args: args{
493
+ value: []interface{}{
494
+ map[string]interface{}{
495
+ "some_number": 1.23,
496
+ "some_bool": false,
497
+ },
498
+ },
499
+ },
500
+ want: []schema.DataType{schema.DataTypeObjectArray},
501
+ },
502
+ {
503
+ name: "determine object, not geoCoordinates (too few props 1)",
504
+ fields: autoSchemaEnabledFields,
505
+ args: args{
506
+ value: map[string]interface{}{
507
+ "latitude": json.Number("1.1"),
508
+ },
509
+ },
510
+ want: []schema.DataType{schema.DataTypeObject},
511
+ },
512
+ {
513
+ name: "determine object, not geoCoordinates (too few props 2)",
514
+ fields: autoSchemaEnabledFields,
515
+ args: args{
516
+ value: map[string]interface{}{
517
+ "longitude": json.Number("1.1"),
518
+ },
519
+ },
520
+ want: []schema.DataType{schema.DataTypeObject},
521
+ },
522
+ {
523
+ name: "determine object, not geoCoordinates (too many props)",
524
+ fields: autoSchemaEnabledFields,
525
+ args: args{
526
+ value: map[string]interface{}{
527
+ "latitude": json.Number("1.1"),
528
+ "longitude": json.Number("1.1"),
529
+ "unrelevant": "some text",
530
+ },
531
+ },
532
+ want: []schema.DataType{schema.DataTypeObject},
533
+ },
534
+ {
535
+ name: "determine object, not phoneNumber (too few props)",
536
+ fields: autoSchemaEnabledFields,
537
+ args: args{
538
+ value: map[string]interface{}{
539
+ "defaultCountry": "nl",
540
+ },
541
+ },
542
+ want: []schema.DataType{schema.DataTypeObject},
543
+ },
544
+ {
545
+ name: "determine object, not phoneNumber (too many props)",
546
+ fields: autoSchemaEnabledFields,
547
+ args: args{
548
+ value: map[string]interface{}{
549
+ "input": "020 1234567",
550
+ "defaultCountry": "nl",
551
+ "internationalFormatted": "+31 20 1234567",
552
+ "countryCode": 31,
553
+ "national": 201234567,
554
+ "nationalFormatted": "020 1234567",
555
+ "valid": true,
556
+ },
557
+ },
558
+ want: []schema.DataType{schema.DataTypeObject},
559
+ },
560
+ }
561
+ for _, tt := range tests {
562
+ vectorRepo := &fakeVectorRepo{}
563
+ vectorRepo.On("ObjectByID", strfmt.UUID("df48b9f6-ba48-470c-bf6a-57657cb07390"), mock.Anything, mock.Anything, mock.Anything).
564
+ Return(&search.Result{ClassName: "Publication"}, nil).Once()
565
+ vectorRepo.On("ObjectByID", strfmt.UUID("df48b9f6-ba48-470c-bf6a-57657cb07391"), mock.Anything, mock.Anything, mock.Anything).
566
+ Return(&search.Result{ClassName: "Article"}, nil).Once()
567
+ m := &AutoSchemaManager{
568
+ schemaManager: &fakeSchemaManager{},
569
+ vectorRepo: vectorRepo,
570
+ config: tt.fields.config,
571
+ }
572
+ t.Run(tt.name, func(t *testing.T) {
573
+ got, err := m.determineType(tt.args.value, false)
574
+ if len(tt.errMsgs) == 0 {
575
+ require.NoError(t, err)
576
+ if !reflect.DeepEqual(got, tt.want) {
577
+ t.Errorf("autoSchemaManager.determineType() = %v, want %v", got, tt.want)
578
+ }
579
+ } else {
580
+ for _, errMsg := range tt.errMsgs {
581
+ require.ErrorContains(t, err, errMsg)
582
+ }
583
+ assert.Nil(t, got)
584
+ }
585
+ })
586
+ }
587
+ }
588
+
589
+ func Test_autoSchemaManager_autoSchema_emptyRequest(t *testing.T) {
590
+ // given
591
+ vectorRepo := &fakeVectorRepo{}
592
+ vectorRepo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
593
+ Return(&search.Result{ClassName: "Publication"}, nil).Once()
594
+ schemaManager := &fakeSchemaManager{}
595
+ logger, _ := test.NewNullLogger()
596
+ autoSchemaManager := &AutoSchemaManager{
597
+ schemaManager: schemaManager,
598
+ vectorRepo: vectorRepo,
599
+ config: config.AutoSchema{
600
+ Enabled: runtime.NewDynamicValue(true),
601
+ DefaultString: schema.DataTypeText.String(),
602
+ DefaultNumber: "number",
603
+ DefaultDate: "date",
604
+ },
605
+ authorizer: fakeAuthorizer{},
606
+ logger: logger,
607
+ }
608
+
609
+ var obj *models.Object
610
+
611
+ knownClasses := map[string]versioned.Class{}
612
+
613
+ _, err := autoSchemaManager.autoSchema(context.Background(), &models.Principal{}, true, knownClasses, obj)
614
+ assert.EqualError(t, fmt.Errorf(validation.ErrorMissingObject), err.Error())
615
+ }
616
+
617
+ func Test_autoSchemaManager_autoSchema_create(t *testing.T) {
618
+ // given
619
+ vectorRepo := &fakeVectorRepo{}
620
+ vectorRepo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
621
+ Return(&search.Result{ClassName: "Publication"}, nil).Once()
622
+ schemaManager := &fakeSchemaManager{}
623
+ logger, _ := test.NewNullLogger()
624
+ autoSchemaManager := &AutoSchemaManager{
625
+ schemaManager: schemaManager,
626
+ vectorRepo: vectorRepo,
627
+ config: config.AutoSchema{
628
+ Enabled: runtime.NewDynamicValue(true),
629
+ DefaultString: schema.DataTypeText.String(),
630
+ DefaultNumber: "number",
631
+ DefaultDate: "date",
632
+ },
633
+ authorizer: fakeAuthorizer{},
634
+ logger: logger,
635
+ }
636
+ obj := &models.Object{
637
+ Class: "Publication",
638
+ Properties: map[string]interface{}{
639
+ "name": "Jodie Sparrow",
640
+ "age": json.Number("30"),
641
+ "publicationDate": "2002-10-02T15:00:00Z",
642
+ "textArray": []interface{}{"a", "b"},
643
+ "numberArray": []interface{}{json.Number("30")},
644
+ },
645
+ }
646
+ knownClasses := map[string]versioned.Class{}
647
+
648
+ // when
649
+ schemaBefore := schemaManager.GetSchemaResponse
650
+ _, err := autoSchemaManager.autoSchema(context.Background(), &models.Principal{}, true, knownClasses, obj)
651
+ schemaAfter := schemaManager.GetSchemaResponse
652
+
653
+ // then
654
+ require.Nil(t, schemaBefore.Objects)
655
+ require.Nil(t, err)
656
+ require.NotNil(t, schemaAfter.Objects)
657
+ assert.Equal(t, 1, len(schemaAfter.Objects.Classes))
658
+
659
+ class := (schemaAfter.Objects.Classes)[0]
660
+ assert.Equal(t, "Publication", class.Class)
661
+ assert.Equal(t, 5, len(class.Properties))
662
+ require.NotNil(t, getProperty(class.Properties, "name"))
663
+ assert.Equal(t, "name", getProperty(class.Properties, "name").Name)
664
+ assert.Equal(t, "text", getProperty(class.Properties, "name").DataType[0])
665
+ require.NotNil(t, getProperty(class.Properties, "age"))
666
+ assert.Equal(t, "age", getProperty(class.Properties, "age").Name)
667
+ assert.Equal(t, "number", getProperty(class.Properties, "age").DataType[0])
668
+ require.NotNil(t, getProperty(class.Properties, "publicationDate"))
669
+ assert.Equal(t, "publicationDate", getProperty(class.Properties, "publicationDate").Name)
670
+ assert.Equal(t, "date", getProperty(class.Properties, "publicationDate").DataType[0])
671
+ require.NotNil(t, getProperty(class.Properties, "textArray"))
672
+ assert.Equal(t, "textArray", getProperty(class.Properties, "textArray").Name)
673
+ assert.Equal(t, "text[]", getProperty(class.Properties, "textArray").DataType[0])
674
+ require.NotNil(t, getProperty(class.Properties, "numberArray"))
675
+ assert.Equal(t, "numberArray", getProperty(class.Properties, "numberArray").Name)
676
+ assert.Equal(t, "number[]", getProperty(class.Properties, "numberArray").DataType[0])
677
+ assert.Equal(t, "hnsw", class.VectorIndexType)
678
+ assert.Equal(t, "none", class.Vectorizer)
679
+ assert.NotNil(t, class.VectorIndexConfig)
680
+ }
681
+
682
+ func Test_autoSchemaManager_autoSchema_update(t *testing.T) {
683
+ // given
684
+ vectorRepo := &fakeVectorRepo{}
685
+ vectorRepo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
686
+ Return(&search.Result{ClassName: "Publication"}, nil).Once()
687
+ logger, _ := test.NewNullLogger()
688
+
689
+ class := &models.Class{
690
+ Class: "Publication",
691
+ Properties: []*models.Property{
692
+ {
693
+ Name: "age",
694
+ DataType: []string{"int"},
695
+ },
696
+ },
697
+ }
698
+ schemaManager := &fakeSchemaManager{
699
+ GetSchemaResponse: schema.Schema{
700
+ Objects: &models.Schema{
701
+ Classes: []*models.Class{class},
702
+ },
703
+ },
704
+ }
705
+ autoSchemaManager := &AutoSchemaManager{
706
+ schemaManager: schemaManager,
707
+ vectorRepo: vectorRepo,
708
+ config: config.AutoSchema{
709
+ Enabled: runtime.NewDynamicValue(true),
710
+ DefaultString: schema.DataTypeText.String(),
711
+ DefaultNumber: "int",
712
+ DefaultDate: "date",
713
+ },
714
+ authorizer: fakeAuthorizer{},
715
+ logger: logger,
716
+ }
717
+ obj := &models.Object{
718
+ Class: "Publication",
719
+ Properties: map[string]interface{}{
720
+ "name": "Jodie Sparrow",
721
+ "age": json.Number("30"),
722
+ "publicationDate": "2002-10-02T15:00:00Z",
723
+ "textArray": []interface{}{"a", "b"},
724
+ "numberArray": []interface{}{json.Number("30")},
725
+ },
726
+ }
727
+ // when
728
+ // then
729
+ schemaBefore := schemaManager.GetSchemaResponse
730
+ require.NotNil(t, schemaBefore.Objects)
731
+ assert.Equal(t, 1, len(schemaBefore.Objects.Classes))
732
+ assert.Equal(t, "Publication", (schemaBefore.Objects.Classes)[0].Class)
733
+ assert.Equal(t, 1, len((schemaBefore.Objects.Classes)[0].Properties))
734
+ assert.Equal(t, "age", (schemaBefore.Objects.Classes)[0].Properties[0].Name)
735
+ assert.Equal(t, "int", (schemaBefore.Objects.Classes)[0].Properties[0].DataType[0])
736
+
737
+ knownClasses := map[string]versioned.Class{
738
+ class.Class: {Version: 0, Class: class},
739
+ }
740
+
741
+ _, err := autoSchemaManager.autoSchema(context.Background(), &models.Principal{}, true, knownClasses, obj)
742
+ require.Nil(t, err)
743
+
744
+ schemaAfter := schemaManager.GetSchemaResponse
745
+ require.NotNil(t, schemaAfter.Objects)
746
+ assert.Equal(t, 1, len(schemaAfter.Objects.Classes))
747
+ assert.Equal(t, "Publication", (schemaAfter.Objects.Classes)[0].Class)
748
+ assert.Equal(t, 5, len((schemaAfter.Objects.Classes)[0].Properties))
749
+ require.NotNil(t, getProperty((schemaAfter.Objects.Classes)[0].Properties, "age"))
750
+ assert.Equal(t, "age", getProperty((schemaAfter.Objects.Classes)[0].Properties, "age").Name)
751
+ assert.Equal(t, "int", getProperty((schemaAfter.Objects.Classes)[0].Properties, "age").DataType[0])
752
+ require.NotNil(t, getProperty((schemaAfter.Objects.Classes)[0].Properties, "name"))
753
+ assert.Equal(t, "name", getProperty((schemaAfter.Objects.Classes)[0].Properties, "name").Name)
754
+ assert.Equal(t, "text", getProperty((schemaAfter.Objects.Classes)[0].Properties, "name").DataType[0])
755
+ require.NotNil(t, getProperty((schemaAfter.Objects.Classes)[0].Properties, "publicationDate"))
756
+ assert.Equal(t, "publicationDate", getProperty((schemaAfter.Objects.Classes)[0].Properties, "publicationDate").Name)
757
+ assert.Equal(t, "date", getProperty((schemaAfter.Objects.Classes)[0].Properties, "publicationDate").DataType[0])
758
+ require.NotNil(t, getProperty((schemaAfter.Objects.Classes)[0].Properties, "textArray"))
759
+ assert.Equal(t, "textArray", getProperty((schemaAfter.Objects.Classes)[0].Properties, "textArray").Name)
760
+ assert.Equal(t, "text[]", getProperty((schemaAfter.Objects.Classes)[0].Properties, "textArray").DataType[0])
761
+ require.NotNil(t, getProperty((schemaAfter.Objects.Classes)[0].Properties, "numberArray"))
762
+ assert.Equal(t, "numberArray", getProperty((schemaAfter.Objects.Classes)[0].Properties, "numberArray").Name)
763
+ assert.Equal(t, "int[]", getProperty((schemaAfter.Objects.Classes)[0].Properties, "numberArray").DataType[0])
764
+ }
765
+
766
+ func Test_autoSchemaManager_getProperties(t *testing.T) {
767
+ type testCase struct {
768
+ name string
769
+ valProperties map[string]interface{}
770
+ expectedProperties []*models.Property
771
+ }
772
+
773
+ testCases := []testCase{
774
+ {
775
+ name: "mixed 1",
776
+ valProperties: map[string]interface{}{
777
+ "name": "someName",
778
+ "objectProperty": map[string]interface{}{
779
+ "nested_int": json.Number("123"),
780
+ "nested_text": "some text",
781
+ "nested_objects": []interface{}{
782
+ map[string]interface{}{
783
+ "nested_bool_lvl2": false,
784
+ "nested_numbers_lvl2": []interface{}{
785
+ json.Number("11.11"),
786
+ },
787
+ },
788
+ },
789
+ },
790
+ },
791
+ expectedProperties: []*models.Property{
792
+ {
793
+ Name: "name",
794
+ DataType: schema.DataTypeText.PropString(),
795
+ },
796
+ {
797
+ Name: "objectProperty",
798
+ DataType: schema.DataTypeObject.PropString(),
799
+ NestedProperties: []*models.NestedProperty{
800
+ {
801
+ Name: "nested_int",
802
+ DataType: schema.DataTypeNumber.PropString(),
803
+ },
804
+ {
805
+ Name: "nested_text",
806
+ DataType: schema.DataTypeText.PropString(),
807
+ },
808
+ {
809
+ Name: "nested_objects",
810
+ DataType: schema.DataTypeObjectArray.PropString(),
811
+ NestedProperties: []*models.NestedProperty{
812
+ {
813
+ Name: "nested_bool_lvl2",
814
+ DataType: schema.DataTypeBoolean.PropString(),
815
+ },
816
+ {
817
+ Name: "nested_numbers_lvl2",
818
+ DataType: schema.DataTypeNumberArray.PropString(),
819
+ },
820
+ },
821
+ },
822
+ },
823
+ },
824
+ },
825
+ },
826
+ {
827
+ name: "mixed 2",
828
+ valProperties: map[string]interface{}{
829
+ "name": "someName",
830
+ "objectProperty": map[string]interface{}{
831
+ "nested_number": json.Number("123"),
832
+ "nested_text": "some text",
833
+ "nested_objects": []interface{}{
834
+ map[string]interface{}{
835
+ "nested_date_lvl2": "2022-01-01T00:00:00+02:00",
836
+ "nested_numbers_lvl2": []interface{}{
837
+ json.Number("11.11"),
838
+ },
839
+ },
840
+ },
841
+ },
842
+ },
843
+ expectedProperties: []*models.Property{
844
+ {
845
+ Name: "name",
846
+ DataType: schema.DataTypeText.PropString(),
847
+ },
848
+ {
849
+ Name: "objectProperty",
850
+ DataType: schema.DataTypeObject.PropString(),
851
+ NestedProperties: []*models.NestedProperty{
852
+ {
853
+ Name: "nested_number",
854
+ DataType: schema.DataTypeNumber.PropString(),
855
+ },
856
+ {
857
+ Name: "nested_text",
858
+ DataType: schema.DataTypeText.PropString(),
859
+ },
860
+ {
861
+ Name: "nested_objects",
862
+ DataType: schema.DataTypeObjectArray.PropString(),
863
+ NestedProperties: []*models.NestedProperty{
864
+ {
865
+ Name: "nested_date_lvl2",
866
+ DataType: schema.DataTypeDate.PropString(),
867
+ },
868
+ {
869
+ Name: "nested_numbers_lvl2",
870
+ DataType: schema.DataTypeNumberArray.PropString(),
871
+ },
872
+ },
873
+ },
874
+ },
875
+ },
876
+ },
877
+ },
878
+ {
879
+ name: "ref",
880
+ valProperties: map[string]interface{}{
881
+ "name": "someName",
882
+ "objectProperty": map[string]interface{}{
883
+ "nested_ref_wannabe": []interface{}{
884
+ map[string]interface{}{
885
+ "beacon": "weaviate://localhost/Soup/8c156d37-81aa-4ce9-a811-621e2702b825",
886
+ },
887
+ },
888
+ "nested_objects": []interface{}{
889
+ map[string]interface{}{
890
+ "nested_ref_wannabe_lvl2": []interface{}{
891
+ map[string]interface{}{
892
+ "beacon": "weaviate://localhost/Soup/8c156d37-81aa-4ce9-a811-621e2702b825",
893
+ },
894
+ },
895
+ },
896
+ },
897
+ },
898
+ "ref": []interface{}{
899
+ map[string]interface{}{
900
+ "beacon": "weaviate://localhost/Soup/8c156d37-81aa-4ce9-a811-621e2702b825",
901
+ },
902
+ },
903
+ },
904
+ expectedProperties: []*models.Property{
905
+ {
906
+ Name: "name",
907
+ DataType: schema.DataTypeText.PropString(),
908
+ },
909
+ {
910
+ Name: "objectProperty",
911
+ DataType: schema.DataTypeObject.PropString(),
912
+ NestedProperties: []*models.NestedProperty{
913
+ {
914
+ Name: "nested_ref_wannabe",
915
+ DataType: schema.DataTypeObjectArray.PropString(),
916
+ NestedProperties: []*models.NestedProperty{
917
+ {
918
+ Name: "beacon",
919
+ DataType: schema.DataTypeText.PropString(),
920
+ },
921
+ },
922
+ },
923
+ {
924
+ Name: "nested_objects",
925
+ DataType: schema.DataTypeObjectArray.PropString(),
926
+ NestedProperties: []*models.NestedProperty{
927
+ {
928
+ Name: "nested_ref_wannabe_lvl2",
929
+ DataType: schema.DataTypeObjectArray.PropString(),
930
+ NestedProperties: []*models.NestedProperty{
931
+ {
932
+ Name: "beacon",
933
+ DataType: schema.DataTypeText.PropString(),
934
+ },
935
+ },
936
+ },
937
+ },
938
+ },
939
+ },
940
+ },
941
+ {
942
+ Name: "ref",
943
+ DataType: []string{"Soup"},
944
+ },
945
+ },
946
+ },
947
+ {
948
+ name: "phone",
949
+ valProperties: map[string]interface{}{
950
+ "name": "someName",
951
+ "objectProperty": map[string]interface{}{
952
+ "nested_phone_wannabe": map[string]interface{}{
953
+ "input": "020 1234567",
954
+ "defaultCountry": "nl",
955
+ },
956
+ "nested_phone_wannabes": []interface{}{
957
+ map[string]interface{}{
958
+ "input": "020 1234567",
959
+ "defaultCountry": "nl",
960
+ },
961
+ },
962
+ "nested_objects": []interface{}{
963
+ map[string]interface{}{
964
+ "nested_phone_wannabe_lvl2": map[string]interface{}{
965
+ "input": "020 1234567",
966
+ "defaultCountry": "nl",
967
+ },
968
+ "nested_phone_wannabes_lvl2": []interface{}{
969
+ map[string]interface{}{
970
+ "input": "020 1234567",
971
+ "defaultCountry": "nl",
972
+ },
973
+ },
974
+ },
975
+ },
976
+ },
977
+ "phone": map[string]interface{}{
978
+ "input": "020 1234567",
979
+ "defaultCountry": "nl",
980
+ },
981
+ "phone_wannabes": []interface{}{
982
+ map[string]interface{}{
983
+ "input": "020 1234567",
984
+ "defaultCountry": "nl",
985
+ },
986
+ },
987
+ },
988
+ expectedProperties: []*models.Property{
989
+ {
990
+ Name: "name",
991
+ DataType: schema.DataTypeText.PropString(),
992
+ },
993
+ {
994
+ Name: "objectProperty",
995
+ DataType: schema.DataTypeObject.PropString(),
996
+ NestedProperties: []*models.NestedProperty{
997
+ {
998
+ Name: "nested_phone_wannabe",
999
+ DataType: schema.DataTypeObject.PropString(),
1000
+ NestedProperties: []*models.NestedProperty{
1001
+ {
1002
+ Name: "input",
1003
+ DataType: schema.DataTypeText.PropString(),
1004
+ },
1005
+ {
1006
+ Name: "defaultCountry",
1007
+ DataType: schema.DataTypeText.PropString(),
1008
+ },
1009
+ },
1010
+ },
1011
+ {
1012
+ Name: "nested_phone_wannabes",
1013
+ DataType: schema.DataTypeObjectArray.PropString(),
1014
+ NestedProperties: []*models.NestedProperty{
1015
+ {
1016
+ Name: "input",
1017
+ DataType: schema.DataTypeText.PropString(),
1018
+ },
1019
+ {
1020
+ Name: "defaultCountry",
1021
+ DataType: schema.DataTypeText.PropString(),
1022
+ },
1023
+ },
1024
+ },
1025
+ {
1026
+ Name: "nested_objects",
1027
+ DataType: schema.DataTypeObjectArray.PropString(),
1028
+ NestedProperties: []*models.NestedProperty{
1029
+ {
1030
+ Name: "nested_phone_wannabe_lvl2",
1031
+ DataType: schema.DataTypeObject.PropString(),
1032
+ NestedProperties: []*models.NestedProperty{
1033
+ {
1034
+ Name: "input",
1035
+ DataType: schema.DataTypeText.PropString(),
1036
+ },
1037
+ {
1038
+ Name: "defaultCountry",
1039
+ DataType: schema.DataTypeText.PropString(),
1040
+ },
1041
+ },
1042
+ },
1043
+ {
1044
+ Name: "nested_phone_wannabes_lvl2",
1045
+ DataType: schema.DataTypeObjectArray.PropString(),
1046
+ NestedProperties: []*models.NestedProperty{
1047
+ {
1048
+ Name: "input",
1049
+ DataType: schema.DataTypeText.PropString(),
1050
+ },
1051
+ {
1052
+ Name: "defaultCountry",
1053
+ DataType: schema.DataTypeText.PropString(),
1054
+ },
1055
+ },
1056
+ },
1057
+ },
1058
+ },
1059
+ },
1060
+ },
1061
+ {
1062
+ Name: "phone",
1063
+ DataType: schema.DataTypePhoneNumber.PropString(),
1064
+ },
1065
+ {
1066
+ Name: "phone_wannabes",
1067
+ DataType: schema.DataTypeObjectArray.PropString(),
1068
+ NestedProperties: []*models.NestedProperty{
1069
+ {
1070
+ Name: "input",
1071
+ DataType: schema.DataTypeText.PropString(),
1072
+ },
1073
+ {
1074
+ Name: "defaultCountry",
1075
+ DataType: schema.DataTypeText.PropString(),
1076
+ },
1077
+ },
1078
+ },
1079
+ },
1080
+ },
1081
+ {
1082
+ name: "geo",
1083
+ valProperties: map[string]interface{}{
1084
+ "name": "someName",
1085
+ "objectProperty": map[string]interface{}{
1086
+ "nested_geo_wannabe": map[string]interface{}{
1087
+ "latitude": json.Number("1.1"),
1088
+ "longitude": json.Number("2.2"),
1089
+ },
1090
+ "nested_geo_wannabes": []interface{}{
1091
+ map[string]interface{}{
1092
+ "latitude": json.Number("1.1"),
1093
+ "longitude": json.Number("2.2"),
1094
+ },
1095
+ },
1096
+ "nested_objects": []interface{}{
1097
+ map[string]interface{}{
1098
+ "nested_geo_wannabe_lvl2": map[string]interface{}{
1099
+ "latitude": json.Number("1.1"),
1100
+ "longitude": json.Number("2.2"),
1101
+ },
1102
+ "nested_geo_wannabes_lvl2": []interface{}{
1103
+ map[string]interface{}{
1104
+ "latitude": json.Number("1.1"),
1105
+ "longitude": json.Number("2.2"),
1106
+ },
1107
+ },
1108
+ },
1109
+ },
1110
+ },
1111
+ "geo": map[string]interface{}{
1112
+ "latitude": json.Number("1.1"),
1113
+ "longitude": json.Number("2.2"),
1114
+ },
1115
+ "geo_wannabes": []interface{}{
1116
+ map[string]interface{}{
1117
+ "latitude": json.Number("1.1"),
1118
+ "longitude": json.Number("2.2"),
1119
+ },
1120
+ },
1121
+ },
1122
+ expectedProperties: []*models.Property{
1123
+ {
1124
+ Name: "name",
1125
+ DataType: schema.DataTypeText.PropString(),
1126
+ },
1127
+ {
1128
+ Name: "objectProperty",
1129
+ DataType: schema.DataTypeObject.PropString(),
1130
+ NestedProperties: []*models.NestedProperty{
1131
+ {
1132
+ Name: "nested_geo_wannabe",
1133
+ DataType: schema.DataTypeObject.PropString(),
1134
+ NestedProperties: []*models.NestedProperty{
1135
+ {
1136
+ Name: "latitude",
1137
+ DataType: schema.DataTypeNumber.PropString(),
1138
+ },
1139
+ {
1140
+ Name: "longitude",
1141
+ DataType: schema.DataTypeNumber.PropString(),
1142
+ },
1143
+ },
1144
+ },
1145
+ {
1146
+ Name: "nested_geo_wannabes",
1147
+ DataType: schema.DataTypeObjectArray.PropString(),
1148
+ NestedProperties: []*models.NestedProperty{
1149
+ {
1150
+ Name: "latitude",
1151
+ DataType: schema.DataTypeNumber.PropString(),
1152
+ },
1153
+ {
1154
+ Name: "longitude",
1155
+ DataType: schema.DataTypeNumber.PropString(),
1156
+ },
1157
+ },
1158
+ },
1159
+ {
1160
+ Name: "nested_objects",
1161
+ DataType: schema.DataTypeObjectArray.PropString(),
1162
+ NestedProperties: []*models.NestedProperty{
1163
+ {
1164
+ Name: "nested_geo_wannabe_lvl2",
1165
+ DataType: schema.DataTypeObject.PropString(),
1166
+ NestedProperties: []*models.NestedProperty{
1167
+ {
1168
+ Name: "latitude",
1169
+ DataType: schema.DataTypeNumber.PropString(),
1170
+ },
1171
+ {
1172
+ Name: "longitude",
1173
+ DataType: schema.DataTypeNumber.PropString(),
1174
+ },
1175
+ },
1176
+ },
1177
+ {
1178
+ Name: "nested_geo_wannabes_lvl2",
1179
+ DataType: schema.DataTypeObjectArray.PropString(),
1180
+ NestedProperties: []*models.NestedProperty{
1181
+ {
1182
+ Name: "latitude",
1183
+ DataType: schema.DataTypeNumber.PropString(),
1184
+ },
1185
+ {
1186
+ Name: "longitude",
1187
+ DataType: schema.DataTypeNumber.PropString(),
1188
+ },
1189
+ },
1190
+ },
1191
+ },
1192
+ },
1193
+ },
1194
+ },
1195
+ {
1196
+ Name: "geo",
1197
+ DataType: schema.DataTypeGeoCoordinates.PropString(),
1198
+ },
1199
+ {
1200
+ Name: "geo_wannabes",
1201
+ DataType: schema.DataTypeObjectArray.PropString(),
1202
+ NestedProperties: []*models.NestedProperty{
1203
+ {
1204
+ Name: "latitude",
1205
+ DataType: schema.DataTypeNumber.PropString(),
1206
+ },
1207
+ {
1208
+ Name: "longitude",
1209
+ DataType: schema.DataTypeNumber.PropString(),
1210
+ },
1211
+ },
1212
+ },
1213
+ },
1214
+ },
1215
+ {
1216
+ name: "case more than 1 item in slice",
1217
+ valProperties: map[string]interface{}{
1218
+ "name": "someName",
1219
+ "objectProperty": map[string]interface{}{
1220
+ "nested_int": json.Number("123"),
1221
+ "nested_text": "some text",
1222
+ "nested_objects": []interface{}{
1223
+ map[string]interface{}{
1224
+ "nested_bool_lvl2": false,
1225
+ "nested_numbers_lvl2": []interface{}{
1226
+ json.Number("11.11"),
1227
+ float64(100),
1228
+ },
1229
+ },
1230
+ map[string]interface{}{
1231
+ "nested_bool_lvl3": false,
1232
+ "nested_numbers_lvl3": []interface{}{
1233
+ float64(100),
1234
+ },
1235
+ },
1236
+ },
1237
+ },
1238
+ },
1239
+ expectedProperties: []*models.Property{
1240
+ {
1241
+ Name: "name",
1242
+ DataType: schema.DataTypeText.PropString(),
1243
+ },
1244
+ {
1245
+ Name: "objectProperty",
1246
+ DataType: schema.DataTypeObject.PropString(),
1247
+ NestedProperties: []*models.NestedProperty{
1248
+ {
1249
+ Name: "nested_int",
1250
+ DataType: schema.DataTypeNumber.PropString(),
1251
+ },
1252
+ {
1253
+ Name: "nested_text",
1254
+ DataType: schema.DataTypeText.PropString(),
1255
+ },
1256
+ {
1257
+ Name: "nested_objects",
1258
+ DataType: schema.DataTypeObjectArray.PropString(),
1259
+ NestedProperties: []*models.NestedProperty{
1260
+ {
1261
+ Name: "nested_bool_lvl2",
1262
+ DataType: schema.DataTypeBoolean.PropString(),
1263
+ },
1264
+ {
1265
+ Name: "nested_numbers_lvl2",
1266
+ DataType: schema.DataTypeNumberArray.PropString(),
1267
+ },
1268
+ {
1269
+ Name: "nested_bool_lvl3",
1270
+ DataType: schema.DataTypeBoolean.PropString(),
1271
+ },
1272
+ {
1273
+ Name: "nested_numbers_lvl3",
1274
+ DataType: schema.DataTypeNumberArray.PropString(),
1275
+ },
1276
+ },
1277
+ },
1278
+ },
1279
+ },
1280
+ },
1281
+ },
1282
+ }
1283
+
1284
+ manager := &AutoSchemaManager{
1285
+ schemaManager: &fakeSchemaManager{},
1286
+ vectorRepo: &fakeVectorRepo{},
1287
+ config: config.AutoSchema{
1288
+ Enabled: runtime.NewDynamicValue(true),
1289
+ DefaultNumber: schema.DataTypeNumber.String(),
1290
+ DefaultString: schema.DataTypeText.String(),
1291
+ DefaultDate: schema.DataTypeDate.String(),
1292
+ },
1293
+ authorizer: fakeAuthorizer{},
1294
+ }
1295
+
1296
+ for i, tc := range testCases {
1297
+ t.Run(fmt.Sprintf("testCase_%d", i), func(t *testing.T) {
1298
+ properties, _ := manager.getProperties(&models.Object{
1299
+ Class: "ClassWithObjectProps",
1300
+ Properties: tc.valProperties,
1301
+ })
1302
+
1303
+ assertPropsMatch(t, tc.expectedProperties, properties)
1304
+ })
1305
+ }
1306
+ }
1307
+
1308
+ func Test_autoSchemaManager_perform_withNested(t *testing.T) {
1309
+ logger, _ := test.NewNullLogger()
1310
+ className := "ClassWithObjectProps"
1311
+
1312
+ class := &models.Class{
1313
+ Class: className,
1314
+ Properties: []*models.Property{
1315
+ {
1316
+ Name: "name",
1317
+ DataType: schema.DataTypeText.PropString(),
1318
+ },
1319
+ {
1320
+ Name: "objectProperty",
1321
+ DataType: schema.DataTypeObject.PropString(),
1322
+ NestedProperties: []*models.NestedProperty{
1323
+ {
1324
+ Name: "nested_int",
1325
+ DataType: schema.DataTypeNumber.PropString(),
1326
+ },
1327
+ {
1328
+ Name: "nested_text",
1329
+ DataType: schema.DataTypeText.PropString(),
1330
+ },
1331
+ {
1332
+ Name: "nested_objects",
1333
+ DataType: schema.DataTypeObjectArray.PropString(),
1334
+ NestedProperties: []*models.NestedProperty{
1335
+ {
1336
+ Name: "nested_bool_lvl2",
1337
+ DataType: schema.DataTypeBoolean.PropString(),
1338
+ },
1339
+ {
1340
+ Name: "nested_numbers_lvl2",
1341
+ DataType: schema.DataTypeNumberArray.PropString(),
1342
+ },
1343
+ },
1344
+ },
1345
+ },
1346
+ },
1347
+ },
1348
+ }
1349
+ object := &models.Object{
1350
+ Class: className,
1351
+ Properties: map[string]interface{}{
1352
+ "name": "someName",
1353
+ "objectProperty": map[string]interface{}{
1354
+ "nested_number": json.Number("123"),
1355
+ "nested_text": "some text",
1356
+ "nested_objects": []interface{}{
1357
+ map[string]interface{}{
1358
+ "nested_date_lvl2": "2022-01-01T00:00:00+02:00",
1359
+ "nested_numbers_lvl2": []interface{}{
1360
+ json.Number("11.11"),
1361
+ },
1362
+ "nested_phone_wannabe_lvl2": map[string]interface{}{
1363
+ "input": "020 1234567",
1364
+ "defaultCountry": "nl",
1365
+ },
1366
+ "nested_phone_wannabes_lvl2": []interface{}{
1367
+ map[string]interface{}{
1368
+ "input": "020 1234567",
1369
+ "defaultCountry": "nl",
1370
+ },
1371
+ },
1372
+ },
1373
+ },
1374
+ "nested_phone_wannabe": map[string]interface{}{
1375
+ "input": "020 1234567",
1376
+ "defaultCountry": "nl",
1377
+ },
1378
+ "nested_phone_wannabes": []interface{}{
1379
+ map[string]interface{}{
1380
+ "input": "020 1234567",
1381
+ "defaultCountry": "nl",
1382
+ },
1383
+ },
1384
+ },
1385
+ "phone": map[string]interface{}{
1386
+ "input": "020 1234567",
1387
+ "defaultCountry": "nl",
1388
+ },
1389
+ "phone_wannabes": []interface{}{
1390
+ map[string]interface{}{
1391
+ "input": "020 1234567",
1392
+ "defaultCountry": "nl",
1393
+ },
1394
+ },
1395
+ "objectPropertyGeo": map[string]interface{}{
1396
+ "nested_objects": []interface{}{
1397
+ map[string]interface{}{
1398
+ "nested_geo_wannabe_lvl2": map[string]interface{}{
1399
+ "latitude": json.Number("1.1"),
1400
+ "longitude": json.Number("2.2"),
1401
+ },
1402
+ "nested_geo_wannabes_lvl2": []interface{}{
1403
+ map[string]interface{}{
1404
+ "latitude": json.Number("1.1"),
1405
+ "longitude": json.Number("2.2"),
1406
+ },
1407
+ },
1408
+ },
1409
+ },
1410
+ "nested_geo_wannabe": map[string]interface{}{
1411
+ "latitude": json.Number("1.1"),
1412
+ "longitude": json.Number("2.2"),
1413
+ },
1414
+ "nested_geo_wannabes": []interface{}{
1415
+ map[string]interface{}{
1416
+ "latitude": json.Number("1.1"),
1417
+ "longitude": json.Number("2.2"),
1418
+ },
1419
+ },
1420
+ },
1421
+ "geo": map[string]interface{}{
1422
+ "latitude": json.Number("1.1"),
1423
+ "longitude": json.Number("2.2"),
1424
+ },
1425
+ "geo_wannabes": []interface{}{
1426
+ map[string]interface{}{
1427
+ "latitude": json.Number("1.1"),
1428
+ "longitude": json.Number("2.2"),
1429
+ },
1430
+ },
1431
+ },
1432
+ }
1433
+ expectedClass := &models.Class{
1434
+ Class: className,
1435
+ Properties: []*models.Property{
1436
+ {
1437
+ Name: "name",
1438
+ DataType: schema.DataTypeText.PropString(),
1439
+ },
1440
+ {
1441
+ Name: "objectProperty",
1442
+ DataType: schema.DataTypeObject.PropString(),
1443
+ NestedProperties: []*models.NestedProperty{
1444
+ {
1445
+ Name: "nested_int",
1446
+ DataType: schema.DataTypeNumber.PropString(),
1447
+ },
1448
+ {
1449
+ Name: "nested_number",
1450
+ DataType: schema.DataTypeNumber.PropString(),
1451
+ },
1452
+ {
1453
+ Name: "nested_text",
1454
+ DataType: schema.DataTypeText.PropString(),
1455
+ },
1456
+ {
1457
+ Name: "nested_phone_wannabe",
1458
+ DataType: schema.DataTypeObject.PropString(),
1459
+ NestedProperties: []*models.NestedProperty{
1460
+ {
1461
+ Name: "input",
1462
+ DataType: schema.DataTypeText.PropString(),
1463
+ },
1464
+ {
1465
+ Name: "defaultCountry",
1466
+ DataType: schema.DataTypeText.PropString(),
1467
+ },
1468
+ },
1469
+ },
1470
+ {
1471
+ Name: "nested_phone_wannabes",
1472
+ DataType: schema.DataTypeObjectArray.PropString(),
1473
+ NestedProperties: []*models.NestedProperty{
1474
+ {
1475
+ Name: "input",
1476
+ DataType: schema.DataTypeText.PropString(),
1477
+ },
1478
+ {
1479
+ Name: "defaultCountry",
1480
+ DataType: schema.DataTypeText.PropString(),
1481
+ },
1482
+ },
1483
+ },
1484
+ {
1485
+ Name: "nested_objects",
1486
+ DataType: schema.DataTypeObjectArray.PropString(),
1487
+ NestedProperties: []*models.NestedProperty{
1488
+ {
1489
+ Name: "nested_bool_lvl2",
1490
+ DataType: schema.DataTypeBoolean.PropString(),
1491
+ },
1492
+ {
1493
+ Name: "nested_date_lvl2",
1494
+ DataType: schema.DataTypeDate.PropString(),
1495
+ },
1496
+ {
1497
+ Name: "nested_numbers_lvl2",
1498
+ DataType: schema.DataTypeNumberArray.PropString(),
1499
+ },
1500
+ {
1501
+ Name: "nested_phone_wannabe_lvl2",
1502
+ DataType: schema.DataTypeObject.PropString(),
1503
+ NestedProperties: []*models.NestedProperty{
1504
+ {
1505
+ Name: "input",
1506
+ DataType: schema.DataTypeText.PropString(),
1507
+ },
1508
+ {
1509
+ Name: "defaultCountry",
1510
+ DataType: schema.DataTypeText.PropString(),
1511
+ },
1512
+ },
1513
+ },
1514
+ {
1515
+ Name: "nested_phone_wannabes_lvl2",
1516
+ DataType: schema.DataTypeObjectArray.PropString(),
1517
+ NestedProperties: []*models.NestedProperty{
1518
+ {
1519
+ Name: "input",
1520
+ DataType: schema.DataTypeText.PropString(),
1521
+ },
1522
+ {
1523
+ Name: "defaultCountry",
1524
+ DataType: schema.DataTypeText.PropString(),
1525
+ },
1526
+ },
1527
+ },
1528
+ },
1529
+ },
1530
+ },
1531
+ },
1532
+ {
1533
+ Name: "phone",
1534
+ DataType: schema.DataTypePhoneNumber.PropString(),
1535
+ },
1536
+ {
1537
+ Name: "phone_wannabes",
1538
+ DataType: schema.DataTypeObjectArray.PropString(),
1539
+ NestedProperties: []*models.NestedProperty{
1540
+ {
1541
+ Name: "input",
1542
+ DataType: schema.DataTypeText.PropString(),
1543
+ },
1544
+ {
1545
+ Name: "defaultCountry",
1546
+ DataType: schema.DataTypeText.PropString(),
1547
+ },
1548
+ },
1549
+ },
1550
+ {
1551
+ Name: "objectPropertyGeo",
1552
+ DataType: schema.DataTypeObject.PropString(),
1553
+ NestedProperties: []*models.NestedProperty{
1554
+ {
1555
+ Name: "nested_geo_wannabe",
1556
+ DataType: schema.DataTypeObject.PropString(),
1557
+ NestedProperties: []*models.NestedProperty{
1558
+ {
1559
+ Name: "latitude",
1560
+ DataType: schema.DataTypeNumber.PropString(),
1561
+ },
1562
+ {
1563
+ Name: "longitude",
1564
+ DataType: schema.DataTypeNumber.PropString(),
1565
+ },
1566
+ },
1567
+ },
1568
+ {
1569
+ Name: "nested_geo_wannabes",
1570
+ DataType: schema.DataTypeObjectArray.PropString(),
1571
+ NestedProperties: []*models.NestedProperty{
1572
+ {
1573
+ Name: "latitude",
1574
+ DataType: schema.DataTypeNumber.PropString(),
1575
+ },
1576
+ {
1577
+ Name: "longitude",
1578
+ DataType: schema.DataTypeNumber.PropString(),
1579
+ },
1580
+ },
1581
+ },
1582
+ {
1583
+ Name: "nested_objects",
1584
+ DataType: schema.DataTypeObjectArray.PropString(),
1585
+ NestedProperties: []*models.NestedProperty{
1586
+ {
1587
+ Name: "nested_geo_wannabe_lvl2",
1588
+ DataType: schema.DataTypeObject.PropString(),
1589
+ NestedProperties: []*models.NestedProperty{
1590
+ {
1591
+ Name: "latitude",
1592
+ DataType: schema.DataTypeNumber.PropString(),
1593
+ },
1594
+ {
1595
+ Name: "longitude",
1596
+ DataType: schema.DataTypeNumber.PropString(),
1597
+ },
1598
+ },
1599
+ },
1600
+ {
1601
+ Name: "nested_geo_wannabes_lvl2",
1602
+ DataType: schema.DataTypeObjectArray.PropString(),
1603
+ NestedProperties: []*models.NestedProperty{
1604
+ {
1605
+ Name: "latitude",
1606
+ DataType: schema.DataTypeNumber.PropString(),
1607
+ },
1608
+ {
1609
+ Name: "longitude",
1610
+ DataType: schema.DataTypeNumber.PropString(),
1611
+ },
1612
+ },
1613
+ },
1614
+ },
1615
+ },
1616
+ },
1617
+ },
1618
+ {
1619
+ Name: "geo",
1620
+ DataType: schema.DataTypeGeoCoordinates.PropString(),
1621
+ },
1622
+ {
1623
+ Name: "geo_wannabes",
1624
+ DataType: schema.DataTypeObjectArray.PropString(),
1625
+ NestedProperties: []*models.NestedProperty{
1626
+ {
1627
+ Name: "latitude",
1628
+ DataType: schema.DataTypeNumber.PropString(),
1629
+ },
1630
+ {
1631
+ Name: "longitude",
1632
+ DataType: schema.DataTypeNumber.PropString(),
1633
+ },
1634
+ },
1635
+ },
1636
+ },
1637
+ }
1638
+
1639
+ schemaManager := &fakeSchemaManager{
1640
+ GetSchemaResponse: schema.Schema{
1641
+ Objects: &models.Schema{
1642
+ Classes: []*models.Class{class},
1643
+ },
1644
+ },
1645
+ }
1646
+ manager := &AutoSchemaManager{
1647
+ schemaManager: schemaManager,
1648
+ vectorRepo: &fakeVectorRepo{},
1649
+ config: config.AutoSchema{
1650
+ Enabled: runtime.NewDynamicValue(true),
1651
+ DefaultNumber: schema.DataTypeNumber.String(),
1652
+ DefaultString: schema.DataTypeText.String(),
1653
+ DefaultDate: schema.DataTypeDate.String(),
1654
+ },
1655
+ logger: logger,
1656
+ authorizer: fakeAuthorizer{},
1657
+ }
1658
+
1659
+ knownClasses := map[string]versioned.Class{
1660
+ class.Class: {Version: 0, Class: class},
1661
+ }
1662
+
1663
+ _, err := manager.autoSchema(context.Background(), &models.Principal{}, true, knownClasses, object)
1664
+ require.NoError(t, err)
1665
+
1666
+ schemaAfter := schemaManager.GetSchemaResponse
1667
+ require.NotNil(t, schemaAfter.Objects)
1668
+ require.Len(t, schemaAfter.Objects.Classes, 1)
1669
+ require.Equal(t, className, schemaAfter.Objects.Classes[0].Class)
1670
+
1671
+ assertPropsMatch(t, expectedClass.Properties, schemaAfter.Objects.Classes[0].Properties)
1672
+ }
1673
+
1674
+ func getProperty(properties []*models.Property, name string) *models.Property {
1675
+ for _, prop := range properties {
1676
+ if prop.Name == name {
1677
+ return prop
1678
+ }
1679
+ }
1680
+ return nil
1681
+ }
1682
+
1683
+ func assertPropsMatch(t *testing.T, propsA, propsB []*models.Property) {
1684
+ require.Len(t, propsB, len(propsA), "props: different length")
1685
+
1686
+ pMap := map[string]int{}
1687
+ for index, p := range propsA {
1688
+ pMap[p.Name] = index
1689
+ }
1690
+
1691
+ for _, pB := range propsB {
1692
+ require.Contains(t, pMap, pB.Name)
1693
+ pA := propsA[pMap[pB.Name]]
1694
+
1695
+ assert.Equal(t, pA.DataType, pB.DataType)
1696
+ test_utils.AssertNestedPropsMatch(t, pA.NestedProperties, pB.NestedProperties)
1697
+ }
1698
+ }
1699
+
1700
+ type fakeAuthorizer struct{}
1701
+
1702
+ func (f fakeAuthorizer) Authorize(ctx context.Context, _ *models.Principal, _ string, _ ...string) error {
1703
+ return nil
1704
+ }
1705
+
1706
+ func (f fakeAuthorizer) AuthorizeSilent(ctx context.Context, _ *models.Principal, _ string, _ ...string) error {
1707
+ return nil
1708
+ }
1709
+
1710
+ func (f fakeAuthorizer) FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error) {
1711
+ return resources, nil
1712
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_add.go ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "time"
19
+
20
+ "github.com/weaviate/weaviate/entities/schema"
21
+ "github.com/weaviate/weaviate/entities/versioned"
22
+
23
+ "github.com/google/uuid"
24
+ "github.com/weaviate/weaviate/entities/additional"
25
+ "github.com/weaviate/weaviate/entities/classcache"
26
+ "github.com/weaviate/weaviate/entities/models"
27
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
28
+ "github.com/weaviate/weaviate/usecases/objects/validation"
29
+ )
30
+
31
+ var errEmptyObjects = NewErrInvalidUserInput("invalid param 'objects': cannot be empty, need at least one object for batching")
32
+
33
+ // AddObjects Class Instances in batch to the connected DB
34
+ func (b *BatchManager) AddObjects(ctx context.Context, principal *models.Principal,
35
+ objects []*models.Object, fields []*string, repl *additional.ReplicationProperties,
36
+ ) (BatchObjects, error) {
37
+ ctx = classcache.ContextWithClassCache(ctx)
38
+
39
+ classesShards := make(map[string][]string)
40
+ for _, obj := range objects {
41
+ obj.Class = schema.UppercaseClassName(obj.Class)
42
+ cls, _ := b.resolveAlias(obj.Class)
43
+ obj.Class = cls
44
+ classesShards[obj.Class] = append(classesShards[obj.Class], obj.Tenant)
45
+ }
46
+ knownClasses := map[string]versioned.Class{}
47
+
48
+ // whole request fails if permissions for any collection are not present
49
+ for className, shards := range classesShards {
50
+ // we don't leak any info that someone who inserts data does not have anyway
51
+ vClass, err := b.schemaManager.GetCachedClassNoAuth(ctx, className)
52
+ if err != nil {
53
+ return nil, err
54
+ }
55
+ knownClasses[className] = vClass[className]
56
+
57
+ if err := b.authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.ShardsData(className, shards...)...); err != nil {
58
+ return nil, err
59
+ }
60
+
61
+ if err := b.authorizer.Authorize(ctx, principal, authorization.CREATE, authorization.ShardsData(className, shards...)...); err != nil {
62
+ return nil, err
63
+ }
64
+ }
65
+
66
+ return b.addObjects(ctx, principal, objects, repl, knownClasses)
67
+ }
68
+
69
+ // AddObjectsGRPCAfterAuth bypasses the authentication in the REST endpoint as GRPC has its own checking
70
+ func (b *BatchManager) AddObjectsGRPCAfterAuth(ctx context.Context, principal *models.Principal,
71
+ objects []*models.Object, repl *additional.ReplicationProperties, fetchedClasses map[string]versioned.Class,
72
+ ) (BatchObjects, error) {
73
+ return b.addObjects(ctx, principal, objects, repl, fetchedClasses)
74
+ }
75
+
76
+ func (b *BatchManager) addObjects(ctx context.Context, principal *models.Principal,
77
+ objects []*models.Object, repl *additional.ReplicationProperties, fetchedClasses map[string]versioned.Class,
78
+ ) (BatchObjects, error) {
79
+ ctx = classcache.ContextWithClassCache(ctx)
80
+
81
+ before := time.Now()
82
+ b.metrics.BatchInc()
83
+ defer b.metrics.BatchOp("total_uc_level", before.UnixNano())
84
+ defer b.metrics.BatchDec()
85
+
86
+ beforePreProcessing := time.Now()
87
+ if len(objects) == 0 {
88
+ return nil, errEmptyObjects
89
+ }
90
+
91
+ var maxSchemaVersion uint64
92
+ batchObjects, maxSchemaVersion := b.validateAndGetVector(ctx, principal, objects, repl, fetchedClasses)
93
+ schemaVersion, tenantCount, err := b.autoSchemaManager.autoTenants(ctx, principal, objects, fetchedClasses)
94
+ if err != nil {
95
+ return nil, fmt.Errorf("auto create tenants: %w", err)
96
+ }
97
+ if schemaVersion > maxSchemaVersion {
98
+ maxSchemaVersion = schemaVersion
99
+ }
100
+
101
+ b.metrics.BatchTenants(tenantCount)
102
+ b.metrics.BatchObjects(len(objects))
103
+ b.metrics.BatchOp("total_preprocessing", beforePreProcessing.UnixNano())
104
+
105
+ var res BatchObjects
106
+
107
+ beforePersistence := time.Now()
108
+ defer b.metrics.BatchOp("total_persistence_level", beforePersistence.UnixNano())
109
+
110
+ // Ensure that the local schema has caught up to the version we used to validate
111
+ if err := b.schemaManager.WaitForUpdate(ctx, maxSchemaVersion); err != nil {
112
+ return nil, fmt.Errorf("error waiting for local schema to catch up to version %d: %w", maxSchemaVersion, err)
113
+ }
114
+ if res, err = b.vectorRepo.BatchPutObjects(ctx, batchObjects, repl, maxSchemaVersion); err != nil {
115
+ return nil, NewErrInternal("batch objects: %#v", err)
116
+ }
117
+
118
+ return res, nil
119
+ }
120
+
121
+ func (b *BatchManager) validateAndGetVector(ctx context.Context, principal *models.Principal,
122
+ objects []*models.Object, repl *additional.ReplicationProperties, fetchedClasses map[string]versioned.Class,
123
+ ) (BatchObjects, uint64) {
124
+ var (
125
+ now = time.Now().UnixNano() / int64(time.Millisecond)
126
+ batchObjects = make(BatchObjects, len(objects))
127
+
128
+ objectsPerClass = make(map[string][]*models.Object)
129
+ originalIndexPerClass = make(map[string][]int)
130
+ validator = validation.New(b.vectorRepo.Exists, b.config, repl)
131
+ )
132
+
133
+ // validate each object and sort by class (==vectorizer)
134
+ var maxSchemaVersion uint64
135
+ for i, obj := range objects {
136
+ batchObjects[i].OriginalIndex = i
137
+
138
+ if obj.Class == "" {
139
+ batchObjects[i].Err = errors.New("object has an empty class")
140
+ continue
141
+ }
142
+
143
+ schemaVersion, err := b.autoSchemaManager.autoSchema(ctx, principal, true, fetchedClasses, obj)
144
+ if err != nil {
145
+ batchObjects[i].Err = err
146
+ }
147
+ if schemaVersion > maxSchemaVersion {
148
+ maxSchemaVersion = schemaVersion
149
+ }
150
+
151
+ if obj.ID == "" {
152
+ // Generate UUID for the new object
153
+ uid, err := generateUUID()
154
+ obj.ID = uid
155
+ batchObjects[i].Err = err
156
+ } else {
157
+ if _, err := uuid.Parse(obj.ID.String()); err != nil {
158
+ batchObjects[i].Err = err
159
+ }
160
+ }
161
+ if obj.Properties == nil {
162
+ obj.Properties = map[string]interface{}{}
163
+ }
164
+ obj.CreationTimeUnix = now
165
+ obj.LastUpdateTimeUnix = now
166
+ batchObjects[i].Object = obj
167
+ batchObjects[i].UUID = obj.ID
168
+ if batchObjects[i].Err != nil {
169
+ continue
170
+ }
171
+
172
+ if len(fetchedClasses) == 0 || fetchedClasses[obj.Class].Class == nil {
173
+ batchObjects[i].Err = fmt.Errorf("class '%v' not present in schema", obj.Class)
174
+ continue
175
+ }
176
+ class := fetchedClasses[obj.Class].Class
177
+
178
+ if err := validator.Object(ctx, class, obj, nil); err != nil {
179
+ batchObjects[i].Err = err
180
+ continue
181
+ }
182
+
183
+ if objectsPerClass[obj.Class] == nil {
184
+ objectsPerClass[obj.Class] = make([]*models.Object, 0)
185
+ originalIndexPerClass[obj.Class] = make([]int, 0)
186
+ }
187
+ objectsPerClass[obj.Class] = append(objectsPerClass[obj.Class], obj)
188
+ originalIndexPerClass[obj.Class] = append(originalIndexPerClass[obj.Class], i)
189
+ }
190
+
191
+ for className, objectsForClass := range objectsPerClass {
192
+ class := fetchedClasses[className]
193
+ errorsPerObj, err := b.modulesProvider.BatchUpdateVector(ctx, class.Class, objectsForClass, b.findObject, b.logger)
194
+ if err != nil {
195
+ for i := range objectsForClass {
196
+ origIndex := originalIndexPerClass[className][i]
197
+ batchObjects[origIndex].Err = err
198
+ }
199
+ }
200
+ for i, err := range errorsPerObj {
201
+ origIndex := originalIndexPerClass[className][i]
202
+ batchObjects[origIndex].Err = err
203
+ }
204
+ }
205
+
206
+ return batchObjects, maxSchemaVersion
207
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_add_test.go ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "testing"
18
+
19
+ "github.com/go-openapi/strfmt"
20
+ "github.com/prometheus/client_golang/prometheus"
21
+ "github.com/sirupsen/logrus/hooks/test"
22
+ "github.com/stretchr/testify/assert"
23
+ "github.com/stretchr/testify/mock"
24
+ "github.com/stretchr/testify/require"
25
+
26
+ "github.com/weaviate/weaviate/entities/models"
27
+ "github.com/weaviate/weaviate/entities/schema"
28
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
29
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
30
+ "github.com/weaviate/weaviate/usecases/config"
31
+ "github.com/weaviate/weaviate/usecases/config/runtime"
32
+ )
33
+
34
+ func Test_BatchManager_AddObjects_WithNoVectorizerModule(t *testing.T) {
35
+ var (
36
+ vectorRepo *fakeVectorRepo
37
+ modulesProvider *fakeModulesProvider
38
+ manager *BatchManager
39
+ )
40
+
41
+ schema := schema.Schema{
42
+ Objects: &models.Schema{
43
+ Classes: []*models.Class{
44
+ {
45
+ Vectorizer: config.VectorizerModuleNone,
46
+ Class: "Foo",
47
+ VectorIndexConfig: hnsw.UserConfig{},
48
+ },
49
+ {
50
+ Vectorizer: config.VectorizerModuleNone,
51
+ Class: "FooSkipped",
52
+ VectorIndexConfig: hnsw.UserConfig{
53
+ Skip: true,
54
+ },
55
+ },
56
+ },
57
+ },
58
+ }
59
+
60
+ resetAutoSchema := func(autoSchema bool) {
61
+ vectorRepo = &fakeVectorRepo{}
62
+ config := &config.WeaviateConfig{
63
+ Config: config.Config{
64
+ AutoSchema: config.AutoSchema{
65
+ Enabled: runtime.NewDynamicValue(autoSchema),
66
+ },
67
+ TrackVectorDimensions: true,
68
+ },
69
+ }
70
+ schemaManager := &fakeSchemaManager{
71
+ GetSchemaResponse: schema,
72
+ }
73
+ logger, _ := test.NewNullLogger()
74
+ authorizer := mocks.NewMockAuthorizer()
75
+ modulesProvider = getFakeModulesProvider()
76
+ manager = NewBatchManager(vectorRepo, modulesProvider, schemaManager, config, logger, authorizer, nil,
77
+ NewAutoSchemaManager(schemaManager, vectorRepo, config, authorizer, logger, prometheus.NewPedanticRegistry()))
78
+ }
79
+
80
+ reset := func() {
81
+ resetAutoSchema(false)
82
+ }
83
+ ctx := context.Background()
84
+
85
+ t.Run("without any objects", func(t *testing.T) {
86
+ reset()
87
+ expectedErr := NewErrInvalidUserInput("invalid param 'objects': cannot be empty, need at least" +
88
+ " one object for batching")
89
+
90
+ _, err := manager.AddObjects(ctx, nil, []*models.Object{}, []*string{}, nil)
91
+
92
+ assert.Equal(t, expectedErr, err)
93
+ })
94
+
95
+ t.Run("with objects without IDs", func(t *testing.T) {
96
+ reset()
97
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
98
+ objects := []*models.Object{
99
+ {
100
+ Class: "Foo",
101
+ Vector: []float32{0.1, 0.1, 0.1111},
102
+ },
103
+ {
104
+ Class: "Foo",
105
+ Vector: []float32{0.2, 0.2, 0.2222},
106
+ },
107
+ }
108
+
109
+ for range objects {
110
+ modulesProvider.On("BatchUpdateVector").
111
+ Return(nil, nil)
112
+ }
113
+
114
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
115
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
116
+
117
+ assert.Nil(t, err)
118
+ require.Len(t, repoCalledWithObjects, 2)
119
+ assert.Len(t, repoCalledWithObjects[0].UUID, 36,
120
+ "a uuid was set for the first object")
121
+ assert.Len(t, repoCalledWithObjects[1].UUID, 36,
122
+ "a uuid was set for the second object")
123
+ assert.Nil(t, repoCalledWithObjects[0].Err)
124
+ assert.Nil(t, repoCalledWithObjects[1].Err)
125
+ assert.Equal(t, models.C11yVector{0.1, 0.1, 0.1111}, repoCalledWithObjects[0].Object.Vector,
126
+ "the correct vector was used")
127
+ assert.Equal(t, models.C11yVector{0.2, 0.2, 0.2222}, repoCalledWithObjects[1].Object.Vector,
128
+ "the correct vector was used")
129
+ })
130
+
131
+ t.Run("object without class", func(t *testing.T) {
132
+ reset()
133
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
134
+ objects := []*models.Object{
135
+ {
136
+ Class: "",
137
+ Vector: []float32{0.1, 0.1, 0.1111},
138
+ },
139
+ {
140
+ Class: "Foo",
141
+ Vector: []float32{0.2, 0.2, 0.2222},
142
+ },
143
+ }
144
+
145
+ for range objects {
146
+ modulesProvider.On("BatchUpdateVector").
147
+ Return(nil, nil)
148
+ }
149
+
150
+ resp, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
151
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
152
+ assert.Nil(t, err)
153
+ assert.NotNil(t, resp)
154
+ require.Len(t, repoCalledWithObjects, 2)
155
+
156
+ require.NotNil(t, resp[0].Err)
157
+ require.Equal(t, resp[0].Err.Error(), "object has an empty class")
158
+ require.Nil(t, resp[1].Err)
159
+ })
160
+
161
+ t.Run("with objects without IDs and nonexistent class and auto schema enabled", func(t *testing.T) {
162
+ resetAutoSchema(true)
163
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
164
+ objects := []*models.Object{
165
+ {
166
+ Class: "NonExistentFoo",
167
+ Vector: []float32{0.1, 0.1, 0.1111},
168
+ },
169
+ {
170
+ Class: "NonExistentFoo",
171
+ Vector: []float32{0.2, 0.2, 0.2222},
172
+ },
173
+ }
174
+
175
+ for range objects {
176
+ modulesProvider.On("BatchUpdateVector").
177
+ Return(nil, nil)
178
+ }
179
+
180
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
181
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
182
+
183
+ assert.Nil(t, err)
184
+ require.Len(t, repoCalledWithObjects, 2)
185
+ assert.Len(t, repoCalledWithObjects[0].UUID, 36,
186
+ "a uuid was set for the first object")
187
+ assert.Len(t, repoCalledWithObjects[1].UUID, 36,
188
+ "a uuid was set for the second object")
189
+ assert.Nil(t, repoCalledWithObjects[0].Err)
190
+ assert.Nil(t, repoCalledWithObjects[1].Err)
191
+ assert.Equal(t, models.C11yVector{0.1, 0.1, 0.1111}, repoCalledWithObjects[0].Object.Vector,
192
+ "the correct vector was used")
193
+ assert.Equal(t, models.C11yVector{0.2, 0.2, 0.2222}, repoCalledWithObjects[1].Object.Vector,
194
+ "the correct vector was used")
195
+ })
196
+
197
+ t.Run("with user-specified IDs", func(t *testing.T) {
198
+ reset()
199
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
200
+ id1 := strfmt.UUID("2d3942c3-b412-4d80-9dfa-99a646629cd2")
201
+ id2 := strfmt.UUID("cf918366-3d3b-4b90-9bc6-bc5ea8762ff6")
202
+ objects := []*models.Object{
203
+ {
204
+ ID: id1,
205
+ Class: "Foo",
206
+ Vector: []float32{0.1, 0.1, 0.1111},
207
+ },
208
+ {
209
+ ID: id2,
210
+ Class: "Foo",
211
+ Vector: []float32{0.2, 0.2, 0.2222},
212
+ },
213
+ }
214
+
215
+ for range objects {
216
+ modulesProvider.On("BatchUpdateVector").
217
+ Return(nil, nil)
218
+ }
219
+
220
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
221
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
222
+
223
+ assert.Nil(t, err)
224
+ require.Len(t, repoCalledWithObjects, 2)
225
+ assert.Equal(t, id1, repoCalledWithObjects[0].UUID, "the user-specified uuid was used")
226
+ assert.Equal(t, id2, repoCalledWithObjects[1].UUID, "the user-specified uuid was used")
227
+ assert.Nil(t, repoCalledWithObjects[0].Err)
228
+ assert.Nil(t, repoCalledWithObjects[1].Err)
229
+ assert.Equal(t, models.C11yVector{0.1, 0.1, 0.1111}, repoCalledWithObjects[0].Object.Vector,
230
+ "the correct vector was used")
231
+ assert.Equal(t, models.C11yVector{0.2, 0.2, 0.2222}, repoCalledWithObjects[1].Object.Vector,
232
+ "the correct vector was used")
233
+ })
234
+
235
+ t.Run("with an invalid user-specified IDs", func(t *testing.T) {
236
+ reset()
237
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
238
+ id1 := strfmt.UUID("invalid")
239
+ id2 := strfmt.UUID("cf918366-3d3b-4b90-9bc6-bc5ea8762ff6")
240
+ objects := []*models.Object{
241
+ {
242
+ ID: id1,
243
+ Class: "Foo",
244
+ Vector: []float32{0.1, 0.1, 0.1111},
245
+ },
246
+ {
247
+ ID: id2,
248
+ Class: "Foo",
249
+ Vector: []float32{0.2, 0.2, 0.2222},
250
+ },
251
+ }
252
+
253
+ for range objects {
254
+ modulesProvider.On("BatchUpdateVector").
255
+ Return(nil, nil)
256
+ }
257
+
258
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
259
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
260
+
261
+ assert.Nil(t, err)
262
+ require.Len(t, repoCalledWithObjects, 2)
263
+ assert.Equal(t, repoCalledWithObjects[0].Err.Error(), fmt.Sprintf("invalid UUID length: %d", len(id1)))
264
+ assert.Equal(t, id2, repoCalledWithObjects[1].UUID, "the user-specified uuid was used")
265
+ })
266
+
267
+ t.Run("without any vectors", func(t *testing.T) {
268
+ // prior to v1.10 this was the desired behavior:
269
+ // note that this should fail on class Foo, but be accepted on class
270
+ // FooSkipped
271
+ //
272
+ // However, since v1.10, it is acceptable to exclude a vector, even if
273
+ // indexing is not skipped. In this case only the individual element is
274
+ // skipped. See https://github.com/weaviate/weaviate/issues/1800
275
+ reset()
276
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
277
+ objects := []*models.Object{
278
+ {
279
+ Class: "Foo",
280
+ },
281
+ {
282
+ Class: "FooSkipped",
283
+ },
284
+ }
285
+
286
+ for range objects {
287
+ modulesProvider.On("BatchUpdateVector").
288
+ Return(nil, nil)
289
+ }
290
+
291
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
292
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
293
+
294
+ assert.Nil(t, err)
295
+ require.Len(t, repoCalledWithObjects, 2)
296
+ assert.Nil(t, repoCalledWithObjects[0].Err)
297
+ assert.Nil(t, repoCalledWithObjects[1].Err)
298
+ })
299
+ }
300
+
301
+ func Test_BatchManager_AddObjects_WithExternalVectorizerModule(t *testing.T) {
302
+ var (
303
+ vectorRepo *fakeVectorRepo
304
+ modulesProvider *fakeModulesProvider
305
+ manager *BatchManager
306
+ )
307
+
308
+ schema := schema.Schema{
309
+ Objects: &models.Schema{
310
+ Classes: []*models.Class{
311
+ {
312
+ Vectorizer: config.VectorizerModuleText2VecContextionary,
313
+ VectorIndexConfig: hnsw.UserConfig{},
314
+ Class: "Foo",
315
+ },
316
+ },
317
+ },
318
+ }
319
+
320
+ reset := func() {
321
+ vectorRepo = &fakeVectorRepo{}
322
+ config := &config.WeaviateConfig{}
323
+ schemaManager := &fakeSchemaManager{
324
+ GetSchemaResponse: schema,
325
+ }
326
+ logger, _ := test.NewNullLogger()
327
+ authorizer := mocks.NewMockAuthorizer()
328
+ modulesProvider = getFakeModulesProvider()
329
+ manager = NewBatchManager(vectorRepo, modulesProvider, schemaManager, config, logger, authorizer, nil,
330
+ NewAutoSchemaManager(schemaManager, vectorRepo, config, authorizer, logger, prometheus.NewPedanticRegistry()))
331
+ }
332
+
333
+ ctx := context.Background()
334
+
335
+ t.Run("without any objects", func(t *testing.T) {
336
+ reset()
337
+ expectedErr := NewErrInvalidUserInput("invalid param 'objects': cannot be empty, need at least" +
338
+ " one object for batching")
339
+
340
+ _, err := manager.AddObjects(ctx, nil, []*models.Object{}, []*string{}, nil)
341
+
342
+ assert.Equal(t, expectedErr, err)
343
+ })
344
+
345
+ t.Run("with objects without IDs", func(t *testing.T) {
346
+ reset()
347
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
348
+ expectedVector := models.C11yVector{0, 1, 2}
349
+ objects := []*models.Object{
350
+ {
351
+ Class: "Foo",
352
+ },
353
+ {
354
+ Class: "Foo",
355
+ },
356
+ }
357
+
358
+ for range objects {
359
+ modulesProvider.On("BatchUpdateVector").
360
+ Return(expectedVector, nil)
361
+ }
362
+
363
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
364
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
365
+
366
+ assert.Nil(t, err)
367
+ require.Len(t, repoCalledWithObjects, 2)
368
+ assert.Len(t, repoCalledWithObjects[0].UUID, 36, "a uuid was set for the first object")
369
+ assert.Len(t, repoCalledWithObjects[1].UUID, 36, "a uuid was set for the second object")
370
+ assert.Nil(t, repoCalledWithObjects[0].Err)
371
+ assert.Nil(t, repoCalledWithObjects[1].Err)
372
+ assert.Equal(t, expectedVector, repoCalledWithObjects[0].Object.Vector,
373
+ "the correct vector was used")
374
+ assert.Equal(t, expectedVector, repoCalledWithObjects[1].Object.Vector,
375
+ "the correct vector was used")
376
+ })
377
+
378
+ t.Run("with user-specified IDs", func(t *testing.T) {
379
+ reset()
380
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
381
+ id1 := strfmt.UUID("2d3942c3-b412-4d80-9dfa-99a646629cd2")
382
+ id2 := strfmt.UUID("cf918366-3d3b-4b90-9bc6-bc5ea8762ff6")
383
+ objects := []*models.Object{
384
+ {
385
+ ID: id1,
386
+ Class: "Foo",
387
+ },
388
+ {
389
+ ID: id2,
390
+ Class: "Foo",
391
+ },
392
+ }
393
+
394
+ for range objects {
395
+ modulesProvider.On("BatchUpdateVector").
396
+ Return(nil, nil)
397
+ }
398
+
399
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
400
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
401
+
402
+ assert.Nil(t, err)
403
+ require.Len(t, repoCalledWithObjects, 2)
404
+ assert.Equal(t, id1, repoCalledWithObjects[0].UUID, "the user-specified uuid was used")
405
+ assert.Equal(t, id2, repoCalledWithObjects[1].UUID, "the user-specified uuid was used")
406
+ })
407
+
408
+ t.Run("with an invalid user-specified IDs", func(t *testing.T) {
409
+ reset()
410
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
411
+ id1 := strfmt.UUID("invalid")
412
+ id2 := strfmt.UUID("cf918366-3d3b-4b90-9bc6-bc5ea8762ff6")
413
+ objects := []*models.Object{
414
+ {
415
+ ID: id1,
416
+ Class: "Foo",
417
+ },
418
+ {
419
+ ID: id2,
420
+ Class: "Foo",
421
+ },
422
+ }
423
+
424
+ for range objects {
425
+ modulesProvider.On("BatchUpdateVector").
426
+ Return(nil, nil)
427
+ }
428
+
429
+ _, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
430
+ repoCalledWithObjects := vectorRepo.Calls[0].Arguments[0].(BatchObjects)
431
+
432
+ assert.Nil(t, err)
433
+ require.Len(t, repoCalledWithObjects, 2)
434
+ assert.Equal(t, repoCalledWithObjects[0].Err.Error(), fmt.Sprintf("invalid UUID length: %d", len(id1)))
435
+ assert.Equal(t, id2, repoCalledWithObjects[1].UUID, "the user-specified uuid was used")
436
+ })
437
+ }
438
+
439
+ func Test_BatchManager_AddObjectsEmptyProperties(t *testing.T) {
440
+ var (
441
+ vectorRepo *fakeVectorRepo
442
+ modulesProvider *fakeModulesProvider
443
+ manager *BatchManager
444
+ )
445
+ schema := schema.Schema{
446
+ Objects: &models.Schema{
447
+ Classes: []*models.Class{
448
+ {
449
+ Class: "TestClass",
450
+ VectorIndexConfig: hnsw.UserConfig{},
451
+
452
+ Properties: []*models.Property{
453
+ {
454
+ Name: "strings",
455
+ DataType: schema.DataTypeTextArray.PropString(),
456
+ Tokenization: models.PropertyTokenizationWhitespace,
457
+ },
458
+ },
459
+ },
460
+ },
461
+ },
462
+ }
463
+ reset := func() {
464
+ vectorRepo = &fakeVectorRepo{}
465
+ vectorRepo.On("BatchPutObjects", mock.Anything).Return(nil).Once()
466
+ config := &config.WeaviateConfig{}
467
+ schemaManager := &fakeSchemaManager{
468
+ GetSchemaResponse: schema,
469
+ }
470
+ logger, _ := test.NewNullLogger()
471
+ authorizer := mocks.NewMockAuthorizer()
472
+ modulesProvider = getFakeModulesProvider()
473
+ manager = NewBatchManager(vectorRepo, modulesProvider, schemaManager, config, logger, authorizer, nil,
474
+ NewAutoSchemaManager(schemaManager, vectorRepo, config, authorizer, logger, prometheus.NewPedanticRegistry()))
475
+ }
476
+ reset()
477
+ objects := []*models.Object{
478
+ {
479
+ ID: strfmt.UUID("cf918366-3d3b-4b90-9bc6-bc5ea8762ff6"),
480
+ Class: "TestClass",
481
+ },
482
+ {
483
+ ID: strfmt.UUID("cf918366-3d3b-4b90-9bc6-bc5ea8762ff3"),
484
+ Class: "TestClass",
485
+ Properties: map[string]interface{}{
486
+ "name": "testName",
487
+ },
488
+ },
489
+ }
490
+ require.Nil(t, objects[0].Properties)
491
+ require.NotNil(t, objects[1].Properties)
492
+
493
+ ctx := context.Background()
494
+ for range objects {
495
+ modulesProvider.On("BatchUpdateVector").
496
+ Return(nil, nil)
497
+ }
498
+ addedObjects, err := manager.AddObjects(ctx, nil, objects, []*string{}, nil)
499
+ assert.Nil(t, err)
500
+ require.Len(t, addedObjects, 2)
501
+ require.NotNil(t, addedObjects[0].Object.Properties)
502
+ require.NotNil(t, addedObjects[1].Object.Properties)
503
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_delete.go ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "time"
18
+
19
+ "github.com/pkg/errors"
20
+
21
+ "github.com/weaviate/weaviate/adapters/handlers/rest/filterext"
22
+ "github.com/weaviate/weaviate/entities/additional"
23
+ "github.com/weaviate/weaviate/entities/classcache"
24
+ "github.com/weaviate/weaviate/entities/filters"
25
+ "github.com/weaviate/weaviate/entities/models"
26
+ "github.com/weaviate/weaviate/entities/schema"
27
+ "github.com/weaviate/weaviate/entities/verbosity"
28
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
29
+ )
30
+
31
+ // DeleteObjects deletes objects in batch based on the match filter
32
+ func (b *BatchManager) DeleteObjects(ctx context.Context, principal *models.Principal,
33
+ match *models.BatchDeleteMatch, deletionTimeUnixMilli *int64, dryRun *bool, output *string,
34
+ repl *additional.ReplicationProperties, tenant string,
35
+ ) (*BatchDeleteResponse, error) {
36
+ class := "*"
37
+ if match != nil {
38
+ match.Class, _ = b.resolveAlias(match.Class)
39
+ class = match.Class
40
+ }
41
+
42
+ err := b.authorizer.Authorize(ctx, principal, authorization.DELETE, authorization.ShardsData(class, tenant)...)
43
+ if err != nil {
44
+ return nil, err
45
+ }
46
+
47
+ ctx = classcache.ContextWithClassCache(ctx)
48
+
49
+ b.metrics.BatchDeleteInc()
50
+ defer b.metrics.BatchDeleteDec()
51
+
52
+ return b.deleteObjects(ctx, principal, match, deletionTimeUnixMilli, dryRun, output, repl, tenant)
53
+ }
54
+
55
+ // DeleteObjectsFromGRPCAfterAuth deletes objects in batch based on the match filter
56
+ func (b *BatchManager) DeleteObjectsFromGRPCAfterAuth(ctx context.Context, principal *models.Principal,
57
+ params BatchDeleteParams,
58
+ repl *additional.ReplicationProperties, tenant string,
59
+ ) (BatchDeleteResult, error) {
60
+ b.metrics.BatchDeleteInc()
61
+ defer b.metrics.BatchDeleteDec()
62
+
63
+ deletionTime := time.UnixMilli(b.timeSource.Now())
64
+ return b.vectorRepo.BatchDeleteObjects(ctx, params, deletionTime, repl, tenant, 0)
65
+ }
66
+
67
+ func (b *BatchManager) deleteObjects(ctx context.Context, principal *models.Principal,
68
+ match *models.BatchDeleteMatch, deletionTimeUnixMilli *int64, dryRun *bool, output *string,
69
+ repl *additional.ReplicationProperties, tenant string,
70
+ ) (*BatchDeleteResponse, error) {
71
+ params, schemaVersion, err := b.validateBatchDelete(ctx, principal, match, dryRun, output)
72
+ if err != nil {
73
+ return nil, errors.Wrap(err, "validate")
74
+ }
75
+
76
+ // Ensure that the local schema has caught up to the version we used to validate
77
+ if err := b.schemaManager.WaitForUpdate(ctx, schemaVersion); err != nil {
78
+ return nil, fmt.Errorf("error waiting for local schema to catch up to version %d: %w", schemaVersion, err)
79
+ }
80
+ var deletionTime time.Time
81
+ if deletionTimeUnixMilli != nil {
82
+ deletionTime = time.UnixMilli(*deletionTimeUnixMilli)
83
+ }
84
+
85
+ result, err := b.vectorRepo.BatchDeleteObjects(ctx, *params, deletionTime, repl, tenant, schemaVersion)
86
+ if err != nil {
87
+ return nil, fmt.Errorf("batch delete objects: %w", err)
88
+ }
89
+
90
+ return b.toResponse(match, params.Output, result)
91
+ }
92
+
93
+ func (b *BatchManager) toResponse(match *models.BatchDeleteMatch, output string,
94
+ result BatchDeleteResult,
95
+ ) (*BatchDeleteResponse, error) {
96
+ response := &BatchDeleteResponse{
97
+ Match: match,
98
+ Output: output,
99
+ DeletionTime: result.DeletionTime,
100
+ DryRun: result.DryRun,
101
+ Result: BatchDeleteResult{
102
+ Matches: result.Matches,
103
+ Limit: result.Limit,
104
+ Objects: result.Objects,
105
+ },
106
+ }
107
+ return response, nil
108
+ }
109
+
110
+ func (b *BatchManager) validateBatchDelete(ctx context.Context, principal *models.Principal,
111
+ match *models.BatchDeleteMatch, dryRun *bool, output *string,
112
+ ) (*BatchDeleteParams, uint64, error) {
113
+ if match == nil {
114
+ return nil, 0, errors.New("empty match clause")
115
+ }
116
+
117
+ if len(match.Class) == 0 {
118
+ return nil, 0, errors.New("empty match.class clause")
119
+ }
120
+
121
+ if match.Where == nil {
122
+ return nil, 0, errors.New("empty match.where clause")
123
+ }
124
+
125
+ // Validate schema given in body with the weaviate schema
126
+ vclasses, err := b.schemaManager.GetCachedClass(ctx, principal, match.Class)
127
+ if err != nil {
128
+ return nil, 0, fmt.Errorf("failed to get class: %s: %w", match.Class, err)
129
+ }
130
+ if vclasses[match.Class].Class == nil {
131
+ return nil, 0, fmt.Errorf("failed to get class: %s", match.Class)
132
+ }
133
+ class := vclasses[match.Class].Class
134
+
135
+ filter, err := filterext.Parse(match.Where, class.Class)
136
+ if err != nil {
137
+ return nil, 0, fmt.Errorf("failed to parse where filter: %w", err)
138
+ }
139
+
140
+ err = filters.ValidateFilters(b.classGetterFunc(ctx, principal), filter)
141
+ if err != nil {
142
+ return nil, 0, fmt.Errorf("invalid where filter: %w", err)
143
+ }
144
+
145
+ dryRunParam := false
146
+ if dryRun != nil {
147
+ dryRunParam = *dryRun
148
+ }
149
+
150
+ outputParam, err := verbosity.ParseOutput(output)
151
+ if err != nil {
152
+ return nil, 0, err
153
+ }
154
+
155
+ params := &BatchDeleteParams{
156
+ ClassName: schema.ClassName(class.Class),
157
+ Filters: filter,
158
+ DryRun: dryRunParam,
159
+ Output: outputParam,
160
+ }
161
+ return params, vclasses[match.Class].Version, nil
162
+ }
163
+
164
+ func (b *BatchManager) classGetterFunc(ctx context.Context, principal *models.Principal) func(string) (*models.Class, error) {
165
+ return func(name string) (*models.Class, error) {
166
+ if err := b.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Collections(name)...); err != nil {
167
+ return nil, err
168
+ }
169
+ class := b.schemaManager.ReadOnlyClass(name)
170
+ if class == nil {
171
+ return nil, fmt.Errorf("could not find class %s in schema", name)
172
+ }
173
+ return class, nil
174
+ }
175
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_delete_test.go ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "testing"
17
+
18
+ "github.com/prometheus/client_golang/prometheus"
19
+ "github.com/sirupsen/logrus/hooks/test"
20
+ "github.com/stretchr/testify/assert"
21
+
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/schema"
24
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
25
+ "github.com/weaviate/weaviate/entities/verbosity"
26
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
27
+ "github.com/weaviate/weaviate/usecases/config"
28
+ "github.com/weaviate/weaviate/usecases/config/runtime"
29
+ )
30
+
31
+ func Test_BatchDelete_RequestValidation(t *testing.T) {
32
+ var (
33
+ vectorRepo *fakeVectorRepo
34
+ manager *BatchManager
35
+ )
36
+
37
+ schema := schema.Schema{
38
+ Objects: &models.Schema{
39
+ Classes: []*models.Class{
40
+ {
41
+ Class: "Foo",
42
+ Properties: []*models.Property{
43
+ {
44
+ Name: "name",
45
+ DataType: schema.DataTypeText.PropString(),
46
+ Tokenization: models.PropertyTokenizationWhitespace,
47
+ },
48
+ },
49
+ VectorIndexConfig: hnsw.UserConfig{},
50
+ Vectorizer: config.VectorizerModuleNone,
51
+ },
52
+ },
53
+ },
54
+ }
55
+
56
+ resetAutoSchema := func(autoSchema bool) {
57
+ vectorRepo = &fakeVectorRepo{}
58
+ config := &config.WeaviateConfig{
59
+ Config: config.Config{
60
+ AutoSchema: config.AutoSchema{
61
+ Enabled: runtime.NewDynamicValue(autoSchema),
62
+ },
63
+ },
64
+ }
65
+ schemaManager := &fakeSchemaManager{
66
+ GetSchemaResponse: schema,
67
+ }
68
+ logger, _ := test.NewNullLogger()
69
+ authorizer := mocks.NewMockAuthorizer()
70
+ modulesProvider := getFakeModulesProvider()
71
+ manager = NewBatchManager(vectorRepo, modulesProvider, schemaManager, config, logger, authorizer, nil,
72
+ NewAutoSchemaManager(schemaManager, vectorRepo, config, authorizer, logger, prometheus.NewPedanticRegistry()))
73
+ }
74
+
75
+ reset := func() {
76
+ resetAutoSchema(false)
77
+ }
78
+ ctx := context.Background()
79
+
80
+ reset()
81
+
82
+ t.Run("with invalid input", func(t *testing.T) {
83
+ tests := []struct {
84
+ input *models.BatchDelete
85
+ expectedError string
86
+ }{
87
+ {
88
+ input: &models.BatchDelete{
89
+ DryRun: ptBool(false),
90
+ Output: ptString(verbosity.OutputVerbose),
91
+ Match: &models.BatchDeleteMatch{
92
+ Class: "SomeClass",
93
+ Where: &models.WhereFilter{
94
+ Path: []string{"some", "path"},
95
+ Operator: "Equal",
96
+ ValueText: ptString("value"),
97
+ },
98
+ },
99
+ },
100
+ expectedError: "validate: failed to get class: SomeClass",
101
+ },
102
+ {
103
+ input: &models.BatchDelete{
104
+ DryRun: ptBool(false),
105
+ Output: ptString(verbosity.OutputVerbose),
106
+ Match: &models.BatchDeleteMatch{
107
+ Class: "Foo",
108
+ Where: &models.WhereFilter{
109
+ Path: []string{"some"},
110
+ Operator: "Equal",
111
+ ValueText: ptString("value"),
112
+ },
113
+ },
114
+ },
115
+ expectedError: "validate: invalid where filter: no such prop with name 'some' found in class 'Foo' " +
116
+ "in the schema. Check your schema files for which properties in this class are available",
117
+ },
118
+ {
119
+ input: &models.BatchDelete{
120
+ DryRun: ptBool(false),
121
+ Output: ptString(verbosity.OutputVerbose),
122
+ },
123
+ expectedError: "validate: empty match clause",
124
+ },
125
+ {
126
+ input: &models.BatchDelete{
127
+ DryRun: ptBool(false),
128
+ Output: ptString(verbosity.OutputVerbose),
129
+ Match: &models.BatchDeleteMatch{
130
+ Class: "",
131
+ },
132
+ },
133
+ expectedError: "validate: empty match.class clause",
134
+ },
135
+ {
136
+ input: &models.BatchDelete{
137
+ DryRun: ptBool(false),
138
+ Output: ptString(verbosity.OutputVerbose),
139
+ Match: &models.BatchDeleteMatch{
140
+ Class: "Foo",
141
+ },
142
+ },
143
+ expectedError: "validate: empty match.where clause",
144
+ },
145
+ {
146
+ input: &models.BatchDelete{
147
+ DryRun: ptBool(false),
148
+ Output: ptString(verbosity.OutputVerbose),
149
+ Match: &models.BatchDeleteMatch{
150
+ Class: "Foo",
151
+ Where: &models.WhereFilter{
152
+ Path: []string{},
153
+ Operator: "Equal",
154
+ ValueText: ptString("name"),
155
+ },
156
+ },
157
+ },
158
+ expectedError: "validate: failed to parse where filter: invalid where filter: field 'path': must have at least one element",
159
+ },
160
+ {
161
+ input: &models.BatchDelete{
162
+ DryRun: ptBool(false),
163
+ Output: ptString("Simplified Chinese"),
164
+ Match: &models.BatchDeleteMatch{
165
+ Class: "Foo",
166
+ Where: &models.WhereFilter{
167
+ Path: []string{"name"},
168
+ Operator: "Equal",
169
+ ValueText: ptString("value"),
170
+ },
171
+ },
172
+ },
173
+ expectedError: "validate: invalid output: \"Simplified Chinese\", possible values are: \"minimal\", \"verbose\"",
174
+ },
175
+ }
176
+
177
+ for _, test := range tests {
178
+ _, err := manager.DeleteObjects(ctx, nil, test.input.Match, test.input.DeletionTimeUnixMilli, test.input.DryRun, test.input.Output, nil, "")
179
+ assert.Equal(t, test.expectedError, err.Error())
180
+ }
181
+ })
182
+ }
183
+
184
+ func ptBool(b bool) *bool {
185
+ return &b
186
+ }
187
+
188
+ func ptString(s string) *string {
189
+ return &s
190
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_manager.go ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "time"
17
+
18
+ "github.com/sirupsen/logrus"
19
+
20
+ "github.com/weaviate/weaviate/entities/additional"
21
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
22
+ "github.com/weaviate/weaviate/usecases/config"
23
+ "github.com/weaviate/weaviate/usecases/monitoring"
24
+ "github.com/weaviate/weaviate/usecases/objects/alias"
25
+ )
26
+
27
+ // BatchManager manages kind changes in batch at a use-case level , i.e.
28
+ // agnostic of underlying databases or storage providers
29
+ type BatchManager struct {
30
+ config *config.WeaviateConfig
31
+ schemaManager schemaManager
32
+ logger logrus.FieldLogger
33
+ authorizer authorization.Authorizer
34
+ vectorRepo BatchVectorRepo
35
+ timeSource timeSource
36
+ modulesProvider ModulesProvider
37
+ autoSchemaManager *AutoSchemaManager
38
+ metrics *Metrics
39
+ }
40
+
41
+ type BatchVectorRepo interface {
42
+ VectorRepo
43
+ batchRepoNew
44
+ }
45
+
46
+ type batchRepoNew interface {
47
+ BatchPutObjects(ctx context.Context, objects BatchObjects,
48
+ repl *additional.ReplicationProperties, schemaVersion uint64) (BatchObjects, error)
49
+ BatchDeleteObjects(ctx context.Context, params BatchDeleteParams, deletionTime time.Time,
50
+ repl *additional.ReplicationProperties, tenant string, schemaVersion uint64) (BatchDeleteResult, error)
51
+ AddBatchReferences(ctx context.Context, references BatchReferences,
52
+ repl *additional.ReplicationProperties, schemaVersion uint64) (BatchReferences, error)
53
+ }
54
+
55
+ // NewBatchManager creates a new manager
56
+ func NewBatchManager(vectorRepo BatchVectorRepo, modulesProvider ModulesProvider,
57
+ schemaManager schemaManager, config *config.WeaviateConfig,
58
+ logger logrus.FieldLogger, authorizer authorization.Authorizer,
59
+ prom *monitoring.PrometheusMetrics, autoSchemaManager *AutoSchemaManager,
60
+ ) *BatchManager {
61
+ return &BatchManager{
62
+ config: config,
63
+ schemaManager: schemaManager,
64
+ logger: logger,
65
+ vectorRepo: vectorRepo,
66
+ timeSource: defaultTimeSource{},
67
+ modulesProvider: modulesProvider,
68
+ authorizer: authorizer,
69
+ autoSchemaManager: autoSchemaManager,
70
+ metrics: NewMetrics(prom),
71
+ }
72
+ }
73
+
74
+ // Alias support
75
+ func (m *BatchManager) resolveAlias(class string) (className, aliasName string) {
76
+ return alias.ResolveAlias(m.schemaManager, class)
77
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_references_add.go ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "strings"
18
+ "sync"
19
+
20
+ "github.com/weaviate/weaviate/entities/versioned"
21
+
22
+ "github.com/go-openapi/strfmt"
23
+ "github.com/sirupsen/logrus"
24
+
25
+ "github.com/weaviate/weaviate/entities/additional"
26
+ "github.com/weaviate/weaviate/entities/classcache"
27
+ enterrors "github.com/weaviate/weaviate/entities/errors"
28
+ "github.com/weaviate/weaviate/entities/models"
29
+ "github.com/weaviate/weaviate/entities/schema"
30
+ "github.com/weaviate/weaviate/entities/schema/crossref"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
32
+ )
33
+
34
+ // AddReferences Class Instances in batch to the connected DB
35
+ func (b *BatchManager) AddReferences(ctx context.Context, principal *models.Principal,
36
+ refs []*models.BatchReference, repl *additional.ReplicationProperties,
37
+ ) (BatchReferences, error) {
38
+ // only validates form of input, no schema access
39
+ if err := validateReferenceForm(refs); err != nil {
40
+ return nil, NewErrInvalidUserInput("invalid params: %v", err)
41
+ }
42
+
43
+ ctx = classcache.ContextWithClassCache(ctx)
44
+
45
+ batchReferences := validateReferencesConcurrently(ctx, refs, b.logger)
46
+
47
+ uniqueClass := map[string]struct{}{}
48
+ type classAndShard struct {
49
+ Class string
50
+ Shard string
51
+ }
52
+ uniqueClassShard := map[string]classAndShard{}
53
+ for idx := range batchReferences {
54
+ if batchReferences[idx].Err != nil {
55
+ continue
56
+ }
57
+ class := batchReferences[idx].From.Class.String()
58
+ uniqueClass[class] = struct{}{}
59
+ uniqueClassShard[class+"#"+batchReferences[idx].Tenant] = classAndShard{Class: class, Shard: batchReferences[idx].Tenant}
60
+ }
61
+
62
+ allClasses := make([]string, 0, len(uniqueClass))
63
+ for classname := range uniqueClass {
64
+ allClasses = append(allClasses, classname)
65
+ }
66
+ fetchedClasses, err := b.schemaManager.GetCachedClass(ctx, principal, allClasses...)
67
+ if err != nil {
68
+ return nil, err
69
+ }
70
+
71
+ var pathsData []string
72
+ for _, val := range uniqueClassShard {
73
+ pathsData = append(pathsData, authorization.ShardsData(val.Class, val.Shard)...)
74
+ }
75
+
76
+ if err := b.authorizer.Authorize(ctx, principal, authorization.UPDATE, pathsData...); err != nil {
77
+ return nil, err
78
+ }
79
+
80
+ b.metrics.BatchRefInc()
81
+ defer b.metrics.BatchRefDec()
82
+
83
+ return b.addReferences(ctx, principal, batchReferences, repl, fetchedClasses)
84
+ }
85
+
86
+ func (b *BatchManager) addReferences(ctx context.Context, principal *models.Principal,
87
+ refs BatchReferences, repl *additional.ReplicationProperties, fetchedClasses map[string]versioned.Class,
88
+ ) (BatchReferences, error) {
89
+ if err := b.autodetectToClass(refs, fetchedClasses); err != nil {
90
+ return nil, err
91
+ }
92
+
93
+ // MT validation must be done after auto-detection as we cannot know the target class beforehand in all cases
94
+ type classAndShard struct {
95
+ Class string
96
+ Shard string
97
+ }
98
+ uniqueClassShard := map[string]classAndShard{}
99
+ var schemaVersion uint64
100
+ for i, ref := range refs {
101
+ if ref.Err != nil {
102
+ continue
103
+ }
104
+
105
+ if shouldValidateMultiTenantRef(ref.Tenant, ref.From, ref.To) {
106
+ // can only validate multi-tenancy when everything above succeeds
107
+ classVersion, err := validateReferenceMultiTenancy(ctx, principal, b.schemaManager, b.vectorRepo, ref.From, ref.To, ref.Tenant, fetchedClasses)
108
+ if err != nil {
109
+ refs[i].Err = err
110
+ }
111
+ if classVersion > schemaVersion {
112
+ schemaVersion = classVersion
113
+ }
114
+ }
115
+
116
+ uniqueClassShard[ref.To.Class+"#"+ref.Tenant] = classAndShard{Class: ref.To.Class, Shard: ref.Tenant}
117
+ }
118
+
119
+ shardsDataPaths := make([]string, 0, len(uniqueClassShard))
120
+ for _, val := range uniqueClassShard {
121
+ shardsDataPaths = append(shardsDataPaths, authorization.ShardsData(val.Class, val.Shard)...)
122
+ }
123
+
124
+ // target object is checked for existence - this is currently ONLY done with tenants enabled, but we should require
125
+ // the permission for everything, to not complicate things too much
126
+ if err := b.authorizer.Authorize(ctx, principal, authorization.READ, shardsDataPaths...); err != nil {
127
+ return nil, err
128
+ }
129
+
130
+ // Ensure that the local schema has caught up to the version we used to validate
131
+ if err := b.schemaManager.WaitForUpdate(ctx, schemaVersion); err != nil {
132
+ return nil, fmt.Errorf("error waiting for local schema to catch up to version %d: %w", schemaVersion, err)
133
+ }
134
+ if res, err := b.vectorRepo.AddBatchReferences(ctx, refs, repl, schemaVersion); err != nil {
135
+ return nil, NewErrInternal("could not add batch request to connector: %v", err)
136
+ } else {
137
+ return res, nil
138
+ }
139
+ }
140
+
141
+ func validateReferenceForm(refs []*models.BatchReference) error {
142
+ if len(refs) == 0 {
143
+ return fmt.Errorf("length cannot be 0, need at least one reference for batching")
144
+ }
145
+
146
+ return nil
147
+ }
148
+
149
+ func validateReferencesConcurrently(ctx context.Context, refs []*models.BatchReference, logger logrus.FieldLogger) BatchReferences {
150
+ c := make(chan BatchReference, len(refs))
151
+ wg := new(sync.WaitGroup)
152
+
153
+ // Generate a goroutine for each separate request
154
+ for i, ref := range refs {
155
+ i := i
156
+ ref := ref
157
+ wg.Add(1)
158
+ enterrors.GoWrapper(func() { validateReference(ctx, wg, ref, i, &c) }, logger)
159
+ }
160
+
161
+ wg.Wait()
162
+ close(c)
163
+
164
+ return referencesChanToSlice(c)
165
+ }
166
+
167
+ // autodetectToClass gets the class name of the referenced class through the schema definition
168
+ func (b *BatchManager) autodetectToClass(batchReferences BatchReferences, fetchedClasses map[string]versioned.Class) error {
169
+ classPropTarget := make(map[string]string, len(batchReferences))
170
+ for i, ref := range batchReferences {
171
+ // get to class from property datatype
172
+ if ref.To.Class != "" || ref.Err != nil {
173
+ continue
174
+ }
175
+ className := string(ref.From.Class)
176
+ propName := schema.LowercaseFirstLetter(string(ref.From.Property))
177
+
178
+ target, ok := classPropTarget[className+propName]
179
+ if !ok {
180
+ class := fetchedClasses[className]
181
+ if class.Class == nil {
182
+ batchReferences[i].Err = fmt.Errorf("source class %q not found in schema", className)
183
+ continue
184
+ }
185
+
186
+ prop, err := schema.GetPropertyByName(class.Class, propName)
187
+ if err != nil {
188
+ batchReferences[i].Err = fmt.Errorf("property %s does not exist for class %s", propName, className)
189
+ continue
190
+ }
191
+ if len(prop.DataType) > 1 {
192
+ continue // can't auto-detect for multi-target
193
+ }
194
+ target = prop.DataType[0] // datatype is the name of the class that is referenced
195
+ classPropTarget[className+propName] = target
196
+ }
197
+ batchReferences[i].To.Class = target
198
+ }
199
+ return nil
200
+ }
201
+
202
+ func validateReference(ctx context.Context,
203
+ wg *sync.WaitGroup, ref *models.BatchReference, i int, resultsC *chan BatchReference,
204
+ ) {
205
+ defer wg.Done()
206
+ var validateErrors []error
207
+ source, err := crossref.ParseSource(string(ref.From))
208
+ if err != nil {
209
+ validateErrors = append(validateErrors, err)
210
+ } else if !source.Local {
211
+ validateErrors = append(validateErrors, fmt.Errorf("source class must always point to the local peer, but got %s",
212
+ source.PeerName))
213
+ }
214
+
215
+ target, err := crossref.Parse(string(ref.To))
216
+ if err != nil {
217
+ validateErrors = append(validateErrors, err)
218
+ } else if !target.Local {
219
+ validateErrors = append(validateErrors, fmt.Errorf("importing network references in batch is not possible. "+
220
+ "Please perform a regular non-batch import for network references, got peer %s",
221
+ target.PeerName))
222
+ }
223
+
224
+ // target id must be lowercase
225
+ if target != nil {
226
+ target.TargetID = strfmt.UUID(strings.ToLower(target.TargetID.String()))
227
+ }
228
+
229
+ if len(validateErrors) == 0 {
230
+ err = nil
231
+ } else {
232
+ err = joinErrors(validateErrors)
233
+ }
234
+
235
+ *resultsC <- BatchReference{
236
+ From: source,
237
+ To: target,
238
+ Err: err,
239
+ OriginalIndex: i,
240
+ Tenant: ref.Tenant,
241
+ }
242
+ }
243
+
244
+ func validateReferenceMultiTenancy(ctx context.Context,
245
+ principal *models.Principal, schemaManager schemaManager,
246
+ repo VectorRepo, source *crossref.RefSource, target *crossref.Ref,
247
+ tenant string, fetchedClasses map[string]versioned.Class,
248
+ ) (uint64, error) {
249
+ if source == nil || target == nil {
250
+ return 0, fmt.Errorf("can't validate multi-tenancy for nil refs")
251
+ }
252
+
253
+ sourceClass, targetClass, schemaVersion, err := getReferenceClasses(
254
+ ctx, principal, schemaManager, source.Class.String(), source.Property.String(), target.Class, fetchedClasses)
255
+ if err != nil {
256
+ return 0, err
257
+ }
258
+
259
+ sourceEnabled := schema.MultiTenancyEnabled(sourceClass)
260
+ targetEnabled := schema.MultiTenancyEnabled(targetClass)
261
+
262
+ if !sourceEnabled && targetEnabled {
263
+ return 0, fmt.Errorf("invalid reference: cannot reference a multi-tenant " +
264
+ "enabled class from a non multi-tenant enabled class")
265
+ }
266
+ if sourceEnabled && !targetEnabled {
267
+ if err := validateTenantRefObject(ctx, repo, sourceClass, source.TargetID, tenant); err != nil {
268
+ return 0, fmt.Errorf("source: %w", err)
269
+ }
270
+ if err := validateTenantRefObject(ctx, repo, targetClass, target.TargetID, ""); err != nil {
271
+ return 0, fmt.Errorf("target: %w", err)
272
+ }
273
+ }
274
+ // if both classes have MT enabled but different tenant keys,
275
+ // no cross-tenant references can be made
276
+ if sourceEnabled && targetEnabled {
277
+ if err := validateTenantRefObject(ctx, repo, sourceClass, source.TargetID, tenant); err != nil {
278
+ return 0, fmt.Errorf("source: %w", err)
279
+ }
280
+ if err := validateTenantRefObject(ctx, repo, targetClass, target.TargetID, tenant); err != nil {
281
+ return 0, fmt.Errorf("target: %w", err)
282
+ }
283
+ }
284
+
285
+ return schemaVersion, nil
286
+ }
287
+
288
+ func getReferenceClasses(ctx context.Context,
289
+ principal *models.Principal, schemaManager schemaManager,
290
+ classFrom, fromProperty, toClassName string, fetchedClasses map[string]versioned.Class,
291
+ ) (sourceClass *models.Class, targetClass *models.Class, schemaVersion uint64, err error) {
292
+ if classFrom == "" {
293
+ err = fmt.Errorf("references involving a multi-tenancy enabled class " +
294
+ "requires class name in the source beacon url")
295
+ return
296
+ }
297
+
298
+ fromClass := fetchedClasses[classFrom]
299
+ if fromClass.Class == nil {
300
+ err = fmt.Errorf("source class %q not found in schema", classFrom)
301
+ return
302
+ }
303
+
304
+ sourceClass = fromClass.Class
305
+ schemaVersion = fromClass.Version
306
+
307
+ // we can auto-detect the to class from the schema if it is a single target reference
308
+ if toClassName == "" {
309
+ refProp, err2 := schema.GetPropertyByName(sourceClass, fromProperty)
310
+ if err2 != nil {
311
+ err = fmt.Errorf("get source refprop %q: %w", classFrom, err2)
312
+ return
313
+ }
314
+
315
+ if len(refProp.DataType) != 1 {
316
+ err = fmt.Errorf("multi-target references require the class name in the target beacon url")
317
+ return
318
+ }
319
+ toClassName = refProp.DataType[0]
320
+ }
321
+
322
+ toClass, ok := fetchedClasses[toClassName]
323
+ if !ok {
324
+ targetVclasses, err2 := schemaManager.GetCachedClass(ctx, principal, toClassName)
325
+ if err2 != nil {
326
+ err = fmt.Errorf("get target class %q: %w", toClassName, err2)
327
+ return
328
+ }
329
+ toClass = targetVclasses[toClassName]
330
+ fetchedClasses[toClassName] = toClass
331
+ }
332
+ if toClass.Class == nil {
333
+ err = fmt.Errorf("target class %q not found in schema", classFrom)
334
+ return
335
+ }
336
+ targetClass = toClass.Class
337
+
338
+ return
339
+ }
340
+
341
+ // validateTenantRefObject ensures that object exist for the given tenant key.
342
+ // This asserts that no cross-tenant references can occur,
343
+ // as a class+id which belongs to a different
344
+ // tenant will not be found in the searched tenant shard
345
+ func validateTenantRefObject(ctx context.Context, repo VectorRepo,
346
+ class *models.Class, ID strfmt.UUID, tenant string,
347
+ ) error {
348
+ exists, err := repo.Exists(ctx, class.Class, ID, nil, tenant)
349
+ if err != nil {
350
+ return fmt.Errorf("get object %s/%s: %w", class.Class, ID, err)
351
+ }
352
+ if !exists {
353
+ return fmt.Errorf("object %s/%s not found for tenant %q", class.Class, ID, tenant)
354
+ }
355
+ return nil
356
+ }
357
+
358
+ func referencesChanToSlice(c chan BatchReference) BatchReferences {
359
+ result := make([]BatchReference, len(c))
360
+ for reference := range c {
361
+ result[reference.OriginalIndex] = reference
362
+ }
363
+
364
+ return result
365
+ }
366
+
367
+ func joinErrors(errors []error) error {
368
+ errorStrings := []string{}
369
+ for _, err := range errors {
370
+ if err != nil {
371
+ errorStrings = append(errorStrings, err.Error())
372
+ }
373
+ }
374
+
375
+ if len(errorStrings) == 0 {
376
+ return nil
377
+ }
378
+
379
+ return fmt.Errorf("%s", strings.Join(errorStrings, ", "))
380
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/batch_types.go ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "time"
16
+
17
+ "github.com/go-openapi/strfmt"
18
+ "github.com/weaviate/weaviate/entities/filters"
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/entities/schema"
21
+ "github.com/weaviate/weaviate/entities/schema/crossref"
22
+ )
23
+
24
+ // BatchObject is a helper type that groups all the info about one object in a
25
+ // batch that belongs together, i.e. uuid, object body and error state.
26
+ //
27
+ // Consumers of an Object (i.e. database connector) should always check
28
+ // whether an error is already present by the time they receive a batch object.
29
+ // Errors can be introduced at all levels, e.g. validation.
30
+ //
31
+ // However, error'd objects are not removed to make sure that the list in
32
+ // Objects matches the order and content of the incoming batch request
33
+ type BatchObject struct {
34
+ OriginalIndex int
35
+ Err error
36
+ Object *models.Object
37
+ UUID strfmt.UUID
38
+ }
39
+
40
+ // BatchObjects groups many Object items together. The order matches the
41
+ // order from the original request. It can be turned into the expected response
42
+ // type using the .Response() method
43
+ type BatchObjects []BatchObject
44
+
45
+ // BatchReference is a helper type that groups all the info about one references in a
46
+ // batch that belongs together, i.e. from, to, original index and error state
47
+ //
48
+ // Consumers of an Object (i.e. database connector) should always check
49
+ // whether an error is already present by the time they receive a batch object.
50
+ // Errors can be introduced at all levels, e.g. validation.
51
+ //
52
+ // However, error'd objects are not removed to make sure that the list in
53
+ // Objects matches the order and content of the incoming batch request
54
+ type BatchReference struct {
55
+ OriginalIndex int `json:"originalIndex"`
56
+ Err error `json:"err"`
57
+ From *crossref.RefSource `json:"from"`
58
+ To *crossref.Ref `json:"to"`
59
+ Tenant string `json:"tenant"`
60
+ }
61
+
62
+ // BatchReferences groups many Reference items together. The order matches the
63
+ // order from the original request. It can be turned into the expected response
64
+ // type using the .Response() method
65
+ type BatchReferences []BatchReference
66
+
67
+ type BatchSimpleObject struct {
68
+ UUID strfmt.UUID
69
+ Err error
70
+ }
71
+
72
+ type BatchSimpleObjects []BatchSimpleObject
73
+
74
+ type BatchDeleteParams struct {
75
+ ClassName schema.ClassName `json:"className"`
76
+ Filters *filters.LocalFilter `json:"filters"`
77
+ DeletionTime time.Time
78
+ DryRun bool
79
+ Output string
80
+ }
81
+
82
+ type BatchDeleteResult struct {
83
+ Matches int64
84
+ Limit int64
85
+ DeletionTime time.Time
86
+ DryRun bool
87
+ Objects BatchSimpleObjects
88
+ }
89
+
90
+ type BatchDeleteResponse struct {
91
+ Match *models.BatchDeleteMatch
92
+ DeletionTime time.Time
93
+ DryRun bool
94
+ Output string
95
+ Params BatchDeleteParams
96
+ Result BatchDeleteResult
97
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/delete.go ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "time"
19
+
20
+ "github.com/weaviate/weaviate/entities/classcache"
21
+ "github.com/weaviate/weaviate/entities/schema"
22
+
23
+ "github.com/go-openapi/strfmt"
24
+
25
+ "github.com/weaviate/weaviate/entities/additional"
26
+ "github.com/weaviate/weaviate/entities/models"
27
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
28
+ authzerrs "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
29
+ "github.com/weaviate/weaviate/usecases/memwatch"
30
+ )
31
+
32
+ // DeleteObject Class Instance from the connected DB
33
+ //
34
+ // if class == "" it will delete all object with same id regardless of the class name.
35
+ // This is due to backward compatibility reasons and should be removed in the future
36
+ func (m *Manager) DeleteObject(ctx context.Context,
37
+ principal *models.Principal, className string, id strfmt.UUID,
38
+ repl *additional.ReplicationProperties, tenant string,
39
+ ) error {
40
+ className = schema.UppercaseClassName(className)
41
+ className, _ = m.resolveAlias(className)
42
+
43
+ err := m.authorizer.Authorize(ctx, principal, authorization.DELETE, authorization.Objects(className, tenant, id))
44
+ if err != nil {
45
+ return err
46
+ }
47
+ ctx = classcache.ContextWithClassCache(ctx)
48
+
49
+ if err := m.allocChecker.CheckAlloc(memwatch.EstimateObjectDeleteMemory()); err != nil {
50
+ m.logger.WithError(err).Errorf("memory pressure: cannot process delete object")
51
+ return fmt.Errorf("cannot process delete object: %w", err)
52
+ }
53
+
54
+ m.metrics.DeleteObjectInc()
55
+ defer m.metrics.DeleteObjectDec()
56
+
57
+ if className == "" { // deprecated
58
+ return m.deleteObjectFromRepo(ctx, id, time.UnixMilli(m.timeSource.Now()))
59
+ }
60
+
61
+ // we only use the schemaVersion in this endpoint
62
+ fetchedClasses, err := m.schemaManager.GetCachedClassNoAuth(ctx, className)
63
+ if err != nil {
64
+ return fmt.Errorf("could not get class %s: %w", className, err)
65
+ }
66
+
67
+ // Ensure that the local schema has caught up to the version we used to validate
68
+ if err := m.schemaManager.WaitForUpdate(ctx, fetchedClasses[className].Version); err != nil {
69
+ return fmt.Errorf("error waiting for local schema to catch up to version %d: %w", fetchedClasses[className].Version, err)
70
+ }
71
+ if err = m.vectorRepo.DeleteObject(ctx, className, id, time.UnixMilli(m.timeSource.Now()), repl, tenant, fetchedClasses[className].Version); err != nil {
72
+ var e1 ErrMultiTenancy
73
+ if errors.As(err, &e1) {
74
+ return NewErrMultiTenancy(fmt.Errorf("delete object from vector repo: %w", err))
75
+ }
76
+ var e2 ErrInvalidUserInput
77
+ if errors.As(err, &e2) {
78
+ return NewErrMultiTenancy(fmt.Errorf("delete object from vector repo: %w", err))
79
+ }
80
+ var e3 authzerrs.Forbidden
81
+ if errors.As(err, &e3) {
82
+ return fmt.Errorf("delete object from vector repo: %w", err)
83
+ }
84
+ return NewErrInternal("could not delete object from vector repo: %v", err)
85
+ }
86
+
87
+ return nil
88
+ }
89
+
90
+ // deleteObjectFromRepo deletes objects with same id and different classes.
91
+ //
92
+ // Deprecated
93
+ func (m *Manager) deleteObjectFromRepo(ctx context.Context, id strfmt.UUID, deletionTime time.Time) error {
94
+ // There might be a situation to have UUIDs which are not unique across classes.
95
+ // Added loop in order to delete all of the objects with given UUID across all classes.
96
+ // This change is added in response to this issue:
97
+ // https://github.com/weaviate/weaviate/issues/1836
98
+ deleteCounter := 0
99
+ for {
100
+ objectRes, err := m.getObjectFromRepo(ctx, "", id, additional.Properties{}, nil, "")
101
+ if err != nil {
102
+ if errors.As(err, &ErrNotFound{}) {
103
+ if deleteCounter == 0 {
104
+ return err
105
+ }
106
+ return nil
107
+ }
108
+ return err
109
+ }
110
+
111
+ object := objectRes.Object()
112
+ err = m.vectorRepo.DeleteObject(ctx, object.Class, id, deletionTime, nil, "", 0)
113
+ if err != nil {
114
+ return NewErrInternal("could not delete object from vector repo: %v", err)
115
+ }
116
+ deleteCounter++
117
+ }
118
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/delete_test.go ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "testing"
18
+
19
+ "github.com/go-openapi/strfmt"
20
+ "github.com/prometheus/client_golang/prometheus"
21
+ "github.com/sirupsen/logrus/hooks/test"
22
+ "github.com/stretchr/testify/assert"
23
+ "github.com/stretchr/testify/mock"
24
+ "github.com/stretchr/testify/require"
25
+
26
+ "github.com/weaviate/weaviate/entities/search"
27
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
28
+ "github.com/weaviate/weaviate/usecases/config"
29
+ )
30
+
31
+ func Test_DeleteObjectsWithSameId(t *testing.T) {
32
+ var (
33
+ cls = "MyClass"
34
+ id = strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
35
+ )
36
+
37
+ manager, vectorRepo, _, _ := newDeleteDependency()
38
+ vectorRepo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything).Return(&search.Result{
39
+ ClassName: cls,
40
+ }, nil).Once()
41
+ vectorRepo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil).Once()
42
+ vectorRepo.On("DeleteObject", cls, id, mock.Anything).Return(nil).Once()
43
+
44
+ err := manager.DeleteObject(context.Background(), nil, "", id, nil, "")
45
+ assert.Nil(t, err)
46
+ vectorRepo.AssertExpectations(t)
47
+ }
48
+
49
+ func Test_DeleteObject(t *testing.T) {
50
+ var (
51
+ cls = "MyClass"
52
+ id = strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
53
+ errNotFound = errors.New("object not found")
54
+ )
55
+
56
+ manager, repo, _, _ := newDeleteDependency()
57
+
58
+ repo.On("DeleteObject", cls, id, mock.Anything).Return(nil).Once()
59
+ err := manager.DeleteObject(context.Background(), nil, cls, id, nil, "")
60
+ assert.Nil(t, err)
61
+ repo.AssertExpectations(t)
62
+
63
+ // return internal error if deleteObject() fails
64
+ repo.On("DeleteObject", cls, id, mock.Anything).Return(errNotFound).Once()
65
+ err = manager.DeleteObject(context.Background(), nil, cls, id, nil, "")
66
+ if !errors.As(err, &ErrInternal{}) {
67
+ t.Errorf("error type got: %T want: ErrInternal", err)
68
+ }
69
+ repo.AssertExpectations(t)
70
+ }
71
+
72
+ // TestDeleteObject_RbacResolveAlias is to make sure alias is resolved to correct
73
+ // collection before doing RBAC check on original class.
74
+ func TestDeleteObject_RbacResolveAlias(t *testing.T) {
75
+ manager, repo, auth, schema := newDeleteDependency()
76
+
77
+ var (
78
+ class = "SomeClass"
79
+ alias = "SomeAlias"
80
+ id = strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
81
+ ctx = context.Background()
82
+ )
83
+
84
+ repo.On("DeleteObject", class, id, mock.Anything).Return(nil).Once()
85
+
86
+ // we mock `resolveAlias`.
87
+ // And we make sure the "resource" name we got in rbac's Authorize is
88
+ // what returned from `resolveAlias`, so that we can confirm, resolveAlias
89
+ // always happens before rbac authorize.
90
+ schema.resolveAliasTo = class
91
+
92
+ err := manager.DeleteObject(ctx, nil, alias, id, nil, "")
93
+ require.NoError(t, err)
94
+ assert.Len(t, auth.Calls(), 1)
95
+ assert.Contains(t, auth.Calls()[0].Resources[0], class) // make sure rbac is called with "resolved class" name
96
+ }
97
+
98
+ func newDeleteDependency() (*Manager, *fakeVectorRepo, *mocks.FakeAuthorizer, *fakeSchemaManager) {
99
+ vectorRepo := new(fakeVectorRepo)
100
+ logger, _ := test.NewNullLogger()
101
+ authorizer := mocks.NewMockAuthorizer()
102
+ smanager := new(fakeSchemaManager)
103
+ manager := NewManager(
104
+ smanager,
105
+ new(config.WeaviateConfig),
106
+ logger,
107
+ authorizer,
108
+ vectorRepo,
109
+ getFakeModulesProvider(),
110
+ new(fakeMetrics), nil,
111
+ NewAutoSchemaManager(new(fakeSchemaManager), vectorRepo, new(config.WeaviateConfig), mocks.NewMockAuthorizer(), logger, prometheus.NewPedanticRegistry()))
112
+ return manager, vectorRepo, authorizer, smanager
113
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/errors.go ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "fmt"
16
+ )
17
+
18
+ // objects status code
19
+ const (
20
+ StatusForbidden = 403
21
+ StatusBadRequest = 400
22
+ StatusNotFound = 404
23
+ StatusUnprocessableEntity = 422
24
+ StatusInternalServerError = 500
25
+ )
26
+
27
+ type Error struct {
28
+ Msg string
29
+ Code int
30
+ Err error
31
+ }
32
+
33
+ // Error implements error interface
34
+ func (e *Error) Error() string {
35
+ return fmt.Sprintf("msg:%s code:%v err:%v", e.Msg, e.Code, e.Err)
36
+ }
37
+
38
+ // Unwrap underlying error
39
+ func (e *Error) Unwrap() error {
40
+ return e.Err
41
+ }
42
+
43
+ func (e *Error) NotFound() bool {
44
+ return e.Code == StatusNotFound
45
+ }
46
+
47
+ func (e *Error) Forbidden() bool {
48
+ return e.Code == StatusForbidden
49
+ }
50
+
51
+ func (e *Error) BadRequest() bool {
52
+ return e.Code == StatusBadRequest
53
+ }
54
+
55
+ func (e *Error) UnprocessableEntity() bool {
56
+ return e.Code == StatusUnprocessableEntity
57
+ }
58
+
59
+ // ErrInvalidUserInput indicates a client-side error
60
+ type ErrInvalidUserInput struct {
61
+ msg string
62
+ }
63
+
64
+ func (e ErrInvalidUserInput) Error() string {
65
+ return e.msg
66
+ }
67
+
68
+ // NewErrInvalidUserInput with Errorf signature
69
+ func NewErrInvalidUserInput(format string, args ...interface{}) ErrInvalidUserInput {
70
+ return ErrInvalidUserInput{msg: fmt.Sprintf(format, args...)}
71
+ }
72
+
73
+ // ErrInternal indicates something went wrong during processing
74
+ type ErrInternal struct {
75
+ msg string
76
+ }
77
+
78
+ func (e ErrInternal) Error() string {
79
+ return e.msg
80
+ }
81
+
82
+ // NewErrInternal with Errorf signature
83
+ func NewErrInternal(format string, args ...interface{}) ErrInternal {
84
+ return ErrInternal{msg: fmt.Sprintf(format, args...)}
85
+ }
86
+
87
+ // ErrNotFound indicates the desired resource doesn't exist
88
+ type ErrNotFound struct {
89
+ msg string
90
+ }
91
+
92
+ func (e ErrNotFound) Error() string {
93
+ return e.msg
94
+ }
95
+
96
+ // NewErrNotFound with Errorf signature
97
+ func NewErrNotFound(format string, args ...interface{}) ErrNotFound {
98
+ return ErrNotFound{msg: fmt.Sprintf(format, args...)}
99
+ }
100
+
101
+ type ErrMultiTenancy struct {
102
+ err error
103
+ }
104
+
105
+ func (e ErrMultiTenancy) Error() string {
106
+ return e.err.Error()
107
+ }
108
+
109
+ func (e ErrMultiTenancy) Unwrap() error {
110
+ return e.err
111
+ }
112
+
113
+ // NewErrMultiTenancy with error signature
114
+ func NewErrMultiTenancy(err error) ErrMultiTenancy {
115
+ return ErrMultiTenancy{err}
116
+ }
117
+
118
+ // This error is thrown by the replication logic when an object has either:
119
+ //
120
+ // 1. been deleted locally but exists remotely
121
+ //
122
+ // 2. been deleted remotely but exists locally
123
+ //
124
+ // signifying that the current operation is happening simultaneously to another operation
125
+ // on the same replicated resource.
126
+ //
127
+ // This error is used to bubble up the error from the replication logic so that it can be handled
128
+ // depending on the context of the higher level operation.
129
+ //
130
+ // This was introduced originally to handle
131
+ // cases where concurrent delete_many and single_patch operations were happening on the same object
132
+ // across multiple replicas. The read repair of the patch method would fail with a 500 conflict error
133
+ // if the delete operation was not propagated to all replicas before the patch operation was attempted.
134
+ // By using this error and handling it in func (m *Manager) MergeObject, any patch updates will assume that
135
+ // the object has been deleted everywhere, despite it only being deleted in one place, and will therefore
136
+ // return a 404 not found error.
137
+ type ErrDirtyReadOfDeletedObject struct {
138
+ err error
139
+ }
140
+
141
+ func (e ErrDirtyReadOfDeletedObject) Error() string {
142
+ return e.err.Error()
143
+ }
144
+
145
+ func (e ErrDirtyReadOfDeletedObject) Unwrap() error {
146
+ return e.err
147
+ }
148
+
149
+ // It depends on the order of operations
150
+ //
151
+ // Created -> Deleted => It is safe in this case to propagate deletion to all replicas
152
+ // Created -> Deleted -> Created => propagating deletion will result in data lost
153
+ //
154
+ // Updated -> Deleted => It is safe in this case to propagate deletion to all replicas
155
+ // Updated -> Deleted -> Updated => It is also safe in this case since updating a deleted object makes no logical sense
156
+ func NewErrDirtyReadOfDeletedObject(err error) ErrDirtyReadOfDeletedObject {
157
+ return ErrDirtyReadOfDeletedObject{err}
158
+ }
159
+
160
+ type ErrDirtyWriteOfDeletedObject struct {
161
+ err error
162
+ }
163
+
164
+ func (e ErrDirtyWriteOfDeletedObject) Error() string {
165
+ return e.err.Error()
166
+ }
167
+
168
+ func (e ErrDirtyWriteOfDeletedObject) Unwrap() error {
169
+ return e.err
170
+ }
171
+
172
+ func NewErrDirtyWriteOfDeletedObject(err error) ErrDirtyWriteOfDeletedObject {
173
+ return ErrDirtyWriteOfDeletedObject{err}
174
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/fakes_for_test.go ADDED
@@ -0,0 +1,887 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "strings"
18
+ "time"
19
+
20
+ "github.com/go-openapi/strfmt"
21
+ "github.com/pkg/errors"
22
+ "github.com/sirupsen/logrus"
23
+ "github.com/stretchr/testify/mock"
24
+ "github.com/tailor-inc/graphql"
25
+ "github.com/tailor-inc/graphql/language/ast"
26
+
27
+ "github.com/weaviate/weaviate/adapters/handlers/graphql/descriptions"
28
+ "github.com/weaviate/weaviate/entities/additional"
29
+ "github.com/weaviate/weaviate/entities/dto"
30
+ "github.com/weaviate/weaviate/entities/filters"
31
+ "github.com/weaviate/weaviate/entities/models"
32
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
33
+ "github.com/weaviate/weaviate/entities/moduletools"
34
+ "github.com/weaviate/weaviate/entities/schema"
35
+ "github.com/weaviate/weaviate/entities/schema/crossref"
36
+ "github.com/weaviate/weaviate/entities/search"
37
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
38
+ "github.com/weaviate/weaviate/entities/versioned"
39
+ )
40
+
41
+ const FindObjectFn = "func(context.Context, string, strfmt.UUID, " +
42
+ "search.SelectProperties, additional.Properties, string) (*search.Result, error)"
43
+
44
+ type fakeSchemaManager struct {
45
+ CalledWith struct {
46
+ fromClass string
47
+ property string
48
+ toClass string
49
+ }
50
+ GetSchemaResponse schema.Schema
51
+ GetschemaErr error
52
+ tenantsEnabled bool
53
+ resolveAliasTo string
54
+ }
55
+
56
+ func (f *fakeSchemaManager) UpdatePropertyAddDataType(ctx context.Context, principal *models.Principal,
57
+ fromClass, property, toClass string,
58
+ ) error {
59
+ f.CalledWith = struct {
60
+ fromClass string
61
+ property string
62
+ toClass string
63
+ }{
64
+ fromClass: fromClass,
65
+ property: property,
66
+ toClass: toClass,
67
+ }
68
+ return nil
69
+ }
70
+
71
+ func (f *fakeSchemaManager) GetSchema(principal *models.Principal) (schema.Schema, error) {
72
+ return f.GetSchemaResponse, f.GetschemaErr
73
+ }
74
+
75
+ func (f *fakeSchemaManager) GetConsistentSchema(ctx context.Context, principal *models.Principal, consistency bool) (schema.Schema, error) {
76
+ return f.GetSchema(principal)
77
+ }
78
+
79
+ func (f *fakeSchemaManager) ShardOwner(class, shard string) (string, error) { return "", nil }
80
+
81
+ func (f *fakeSchemaManager) ShardFromUUID(class string, uuid []byte) string { return "" }
82
+
83
+ func (f *fakeSchemaManager) GetClass(ctx context.Context, principal *models.Principal,
84
+ name string,
85
+ ) (*models.Class, error) {
86
+ if f.GetSchemaResponse.Objects == nil {
87
+ return nil, f.GetschemaErr
88
+ }
89
+ for _, class := range f.GetSchemaResponse.Objects.Classes {
90
+ if class.Class == name {
91
+ return class, f.GetschemaErr
92
+ }
93
+ }
94
+ return nil, f.GetschemaErr
95
+ }
96
+
97
+ func (f *fakeSchemaManager) GetConsistentClass(ctx context.Context, principal *models.Principal,
98
+ name string, consistency bool,
99
+ ) (*models.Class, uint64, error) {
100
+ cls, err := f.GetClass(ctx, principal, name)
101
+ return cls, 0, err
102
+ }
103
+
104
+ func (f *fakeSchemaManager) GetCachedClass(ctx context.Context,
105
+ principal *models.Principal, names ...string,
106
+ ) (map[string]versioned.Class, error) {
107
+ res := map[string]versioned.Class{}
108
+ for _, name := range names {
109
+ cls, err := f.GetClass(ctx, principal, name)
110
+ if err != nil {
111
+ return res, err
112
+ }
113
+ res[name] = versioned.Class{Class: cls}
114
+ }
115
+ return res, nil
116
+ }
117
+
118
+ func (f *fakeSchemaManager) GetCachedClassNoAuth(ctx context.Context, names ...string,
119
+ ) (map[string]versioned.Class, error) {
120
+ res := map[string]versioned.Class{}
121
+ for _, name := range names {
122
+ cls, err := f.GetClass(ctx, nil, name)
123
+ if err != nil {
124
+ return res, err
125
+ }
126
+ res[name] = versioned.Class{Class: cls}
127
+ }
128
+ return f.GetCachedClass(ctx, nil, names...)
129
+ }
130
+
131
+ func (f *fakeSchemaManager) ReadOnlyClass(name string) *models.Class {
132
+ c, err := f.GetClass(context.TODO(), nil, name)
133
+ if err != nil {
134
+ return nil
135
+ }
136
+ return c
137
+ }
138
+
139
+ func (f *fakeSchemaManager) AddClass(ctx context.Context, principal *models.Principal,
140
+ class *models.Class,
141
+ ) (*models.Class, uint64, error) {
142
+ if f.GetSchemaResponse.Objects == nil {
143
+ f.GetSchemaResponse.Objects = schema.Empty().Objects
144
+ }
145
+ class.VectorIndexConfig = hnsw.UserConfig{}
146
+ class.VectorIndexType = "hnsw"
147
+ class.Vectorizer = "none"
148
+ classes := f.GetSchemaResponse.Objects.Classes
149
+ if classes != nil {
150
+ classes = append(classes, class)
151
+ } else {
152
+ classes = []*models.Class{class}
153
+ }
154
+ f.GetSchemaResponse.Objects.Classes = classes
155
+ return class, 0, nil
156
+ }
157
+
158
+ func (f *fakeSchemaManager) AddClassProperty(ctx context.Context, principal *models.Principal,
159
+ class *models.Class, className string, merge bool, newProps ...*models.Property,
160
+ ) (*models.Class, uint64, error) {
161
+ existing := map[string]int{}
162
+ var existedClass *models.Class
163
+ for _, c := range f.GetSchemaResponse.Objects.Classes {
164
+ if c.Class == class.Class {
165
+ existedClass = c
166
+ for idx, p := range c.Properties {
167
+ existing[strings.ToLower(p.Name)] = idx
168
+ }
169
+ break
170
+ }
171
+ }
172
+
173
+ // update existed
174
+ for _, prop := range newProps {
175
+ if idx, exists := existing[strings.ToLower(prop.Name)]; exists {
176
+ prop.NestedProperties, _ = schema.MergeRecursivelyNestedProperties(existedClass.Properties[idx].NestedProperties,
177
+ prop.NestedProperties)
178
+ existedClass.Properties[idx] = prop
179
+ } else {
180
+ existedClass.Properties = append(existedClass.Properties, prop)
181
+ }
182
+ }
183
+
184
+ return class, 0, nil
185
+ }
186
+
187
+ func (f *fakeSchemaManager) AddTenants(ctx context.Context,
188
+ principal *models.Principal, class string, tenants []*models.Tenant,
189
+ ) (uint64, error) {
190
+ f.tenantsEnabled = true
191
+ return 0, nil
192
+ }
193
+
194
+ func (f *fakeSchemaManager) WaitForUpdate(ctx context.Context, schemaVersion uint64) error {
195
+ return nil
196
+ }
197
+
198
+ func (f *fakeSchemaManager) StorageCandidates() []string {
199
+ return []string{}
200
+ }
201
+
202
+ func (f *fakeSchemaManager) ResolveAlias(alias string) string {
203
+ return f.resolveAliasTo
204
+ }
205
+
206
+ type fakeVectorRepo struct {
207
+ mock.Mock
208
+ }
209
+
210
+ func (f *fakeVectorRepo) Exists(ctx context.Context, class string, id strfmt.UUID, repl *additional.ReplicationProperties, tenant string) (bool, error) {
211
+ args := f.Called(class, id)
212
+ return args.Bool(0), args.Error(1)
213
+ }
214
+
215
+ func (f *fakeVectorRepo) Object(ctx context.Context, cls string, id strfmt.UUID,
216
+ props search.SelectProperties, additional additional.Properties,
217
+ repl *additional.ReplicationProperties, tenant string,
218
+ ) (*search.Result, error) {
219
+ args := f.Called(cls, id, props, additional, tenant)
220
+ if args.Get(0) != nil {
221
+ return args.Get(0).(*search.Result), args.Error(1)
222
+ }
223
+ return nil, args.Error(1)
224
+ }
225
+
226
+ func (f *fakeVectorRepo) ObjectByID(ctx context.Context, id strfmt.UUID,
227
+ props search.SelectProperties, additional additional.Properties,
228
+ tenant string,
229
+ ) (*search.Result, error) {
230
+ args := f.Called(id, props, additional)
231
+ if args.Get(0) != nil {
232
+ return args.Get(0).(*search.Result), args.Error(1)
233
+ }
234
+ return nil, args.Error(1)
235
+ }
236
+
237
+ func (f *fakeVectorRepo) ObjectSearch(ctx context.Context, offset, limit int, filters *filters.LocalFilter,
238
+ sort []filters.Sort, additional additional.Properties, tenant string,
239
+ ) (search.Results, error) {
240
+ args := f.Called(offset, limit, sort, filters, additional)
241
+ return args.Get(0).([]search.Result), args.Error(1)
242
+ }
243
+
244
+ func (f *fakeVectorRepo) Query(ctx context.Context, q *QueryInput) (search.Results, *Error) {
245
+ args := f.Called(q)
246
+ var customEr *Error
247
+ errors.As(args.Error(1), &customEr)
248
+ return args.Get(0).([]search.Result), customEr
249
+ }
250
+
251
+ func (f *fakeVectorRepo) PutObject(ctx context.Context, concept *models.Object, vector []float32,
252
+ vectors map[string][]float32, multiVectors map[string][][]float32, repl *additional.ReplicationProperties, schemaVersion uint64,
253
+ ) error {
254
+ args := f.Called(concept, vector)
255
+ return args.Error(0)
256
+ }
257
+
258
+ func (f *fakeVectorRepo) BatchPutObjects(ctx context.Context, batch BatchObjects,
259
+ repl *additional.ReplicationProperties, schemaVersion uint64,
260
+ ) (BatchObjects, error) {
261
+ args := f.Called(batch)
262
+ return batch, args.Error(0)
263
+ }
264
+
265
+ func (f *fakeVectorRepo) AddBatchReferences(ctx context.Context, batch BatchReferences,
266
+ repl *additional.ReplicationProperties, schemaVersion uint64,
267
+ ) (BatchReferences, error) {
268
+ args := f.Called(batch)
269
+ return batch, args.Error(0)
270
+ }
271
+
272
+ func (f *fakeVectorRepo) BatchDeleteObjects(ctx context.Context, params BatchDeleteParams,
273
+ deletionTime time.Time, repl *additional.ReplicationProperties, tenant string, schemaVersion uint64,
274
+ ) (BatchDeleteResult, error) {
275
+ args := f.Called(params)
276
+ return args.Get(0).(BatchDeleteResult), args.Error(1)
277
+ }
278
+
279
+ func (f *fakeVectorRepo) Merge(ctx context.Context, merge MergeDocument, repl *additional.ReplicationProperties, tenant string, schemaVersion uint64) error {
280
+ args := f.Called(merge)
281
+ return args.Error(0)
282
+ }
283
+
284
+ func (f *fakeVectorRepo) DeleteObject(ctx context.Context, className string,
285
+ id strfmt.UUID, deletionTime time.Time, repl *additional.ReplicationProperties, tenant string, schemaVersion uint64,
286
+ ) error {
287
+ args := f.Called(className, id, deletionTime)
288
+ return args.Error(0)
289
+ }
290
+
291
+ func (f *fakeVectorRepo) AddReference(ctx context.Context, source *crossref.RefSource,
292
+ target *crossref.Ref, repl *additional.ReplicationProperties, tenant string, schemaVersion uint64,
293
+ ) error {
294
+ args := f.Called(source, target)
295
+ return args.Error(0)
296
+ }
297
+
298
+ func (f *fakeVectorRepo) ReferenceVectorSearch(ctx context.Context,
299
+ obj *models.Object, refProps map[string]struct{},
300
+ ) ([][]float32, error) {
301
+ return nil, nil
302
+ }
303
+
304
+ type fakeExtender struct {
305
+ multi []search.Result
306
+ }
307
+
308
+ func (f *fakeExtender) AdditionalPropertyFn(ctx context.Context,
309
+ in []search.Result, params interface{}, limit *int,
310
+ argumentModuleParams map[string]interface{}, cfg moduletools.ClassConfig,
311
+ ) ([]search.Result, error) {
312
+ return f.multi, nil
313
+ }
314
+
315
+ func (f *fakeExtender) ExtractAdditionalFn(param []*ast.Argument, class *models.Class) interface{} {
316
+ return nil
317
+ }
318
+
319
+ func (f *fakeExtender) AdditionalPropertyDefaultValue() interface{} {
320
+ return getDefaultParam("nearestNeighbors")
321
+ }
322
+
323
+ type fakeProjector struct {
324
+ multi []search.Result
325
+ }
326
+
327
+ func (f *fakeProjector) AdditionalPropertyFn(ctx context.Context,
328
+ in []search.Result, params interface{}, limit *int,
329
+ argumentModuleParams map[string]interface{}, cfg moduletools.ClassConfig,
330
+ ) ([]search.Result, error) {
331
+ return f.multi, nil
332
+ }
333
+
334
+ func (f *fakeProjector) ExtractAdditionalFn(param []*ast.Argument, class *models.Class) interface{} {
335
+ return nil
336
+ }
337
+
338
+ func (f *fakeProjector) AdditionalPropertyDefaultValue() interface{} {
339
+ return getDefaultParam("featureProjection")
340
+ }
341
+
342
+ type fakePathBuilder struct {
343
+ multi []search.Result
344
+ }
345
+
346
+ func (f *fakePathBuilder) AdditionalPropertyFn(ctx context.Context,
347
+ in []search.Result, params interface{}, limit *int,
348
+ argumentModuleParams map[string]interface{}, cfg moduletools.ClassConfig,
349
+ ) ([]search.Result, error) {
350
+ return f.multi, nil
351
+ }
352
+
353
+ func (f *fakePathBuilder) ExtractAdditionalFn(param []*ast.Argument, class *models.Class) interface{} {
354
+ return nil
355
+ }
356
+
357
+ func (f *fakePathBuilder) AdditionalPropertyDefaultValue() interface{} {
358
+ return getDefaultParam("semanticPath")
359
+ }
360
+
361
+ type fakeModulesProvider struct {
362
+ mock.Mock
363
+ customExtender *fakeExtender
364
+ customProjector *fakeProjector
365
+ }
366
+
367
+ func (p *fakeModulesProvider) GetObjectAdditionalExtend(ctx context.Context,
368
+ in *search.Result, moduleParams map[string]interface{},
369
+ ) (*search.Result, error) {
370
+ res, err := p.additionalExtend(ctx, search.Results{*in}, moduleParams, "ObjectGet")
371
+ if err != nil {
372
+ return nil, err
373
+ }
374
+ return &res[0], nil
375
+ }
376
+
377
+ func (p *fakeModulesProvider) ListObjectsAdditionalExtend(ctx context.Context,
378
+ in search.Results, moduleParams map[string]interface{},
379
+ ) (search.Results, error) {
380
+ return p.additionalExtend(ctx, in, moduleParams, "ObjectList")
381
+ }
382
+
383
+ func (p *fakeModulesProvider) UsingRef2Vec(moduleName string) bool {
384
+ args := p.Called(moduleName)
385
+ return args.Bool(0)
386
+ }
387
+
388
+ func (p *fakeModulesProvider) UpdateVector(ctx context.Context, object *models.Object, class *models.Class,
389
+ findObjFn modulecapabilities.FindObjectFn, logger logrus.FieldLogger,
390
+ ) error {
391
+ args := p.Called(object, findObjFn)
392
+ switch vec := args.Get(0).(type) {
393
+ case models.C11yVector:
394
+ object.Vector = vec
395
+ return args.Error(1)
396
+ case []float32:
397
+ object.Vector = vec
398
+ return args.Error(1)
399
+ default:
400
+ return args.Error(1)
401
+ }
402
+ }
403
+
404
+ func (p *fakeModulesProvider) BatchUpdateVector(ctx context.Context, class *models.Class, objects []*models.Object,
405
+ findObjectFn modulecapabilities.FindObjectFn,
406
+ logger logrus.FieldLogger,
407
+ ) (map[int]error, error) {
408
+ args := p.Called()
409
+
410
+ for _, obj := range objects {
411
+ switch vec := args.Get(0).(type) {
412
+ case models.C11yVector:
413
+ obj.Vector = vec
414
+ case []float32:
415
+ obj.Vector = vec
416
+ default:
417
+ }
418
+ }
419
+
420
+ return nil, nil
421
+ }
422
+
423
+ func (p *fakeModulesProvider) VectorizerName(className string) (string, error) {
424
+ args := p.Called(className)
425
+ return args.String(0), args.Error(1)
426
+ }
427
+
428
+ func (p *fakeModulesProvider) additionalExtend(ctx context.Context,
429
+ in search.Results, moduleParams map[string]interface{}, capability string,
430
+ ) (search.Results, error) {
431
+ txt2vec := newNearCustomTextModule(p.getExtender(), p.getProjector(), &fakePathBuilder{})
432
+ additionalProperties := txt2vec.AdditionalProperties()
433
+ if err := p.checkCapabilities(additionalProperties, moduleParams, capability); err != nil {
434
+ return nil, err
435
+ }
436
+ for name, value := range moduleParams {
437
+ additionalPropertyFn := p.getAdditionalPropertyFn(additionalProperties[name], capability)
438
+ if additionalPropertyFn != nil && value != nil {
439
+ resArray, err := additionalPropertyFn(ctx, in, nil, nil, nil, nil)
440
+ if err != nil {
441
+ return nil, err
442
+ }
443
+ in = resArray
444
+ }
445
+ }
446
+ return in, nil
447
+ }
448
+
449
+ func (p *fakeModulesProvider) checkCapabilities(additionalProperties map[string]modulecapabilities.AdditionalProperty,
450
+ moduleParams map[string]interface{}, capability string,
451
+ ) error {
452
+ for name := range moduleParams {
453
+ additionalPropertyFn := p.getAdditionalPropertyFn(additionalProperties[name], capability)
454
+ if additionalPropertyFn == nil {
455
+ return errors.Errorf("unknown capability: %s", name)
456
+ }
457
+ }
458
+ return nil
459
+ }
460
+
461
+ func (p *fakeModulesProvider) getAdditionalPropertyFn(additionalProperty modulecapabilities.AdditionalProperty,
462
+ capability string,
463
+ ) modulecapabilities.AdditionalPropertyFn {
464
+ switch capability {
465
+ case "ObjectGet":
466
+ return additionalProperty.SearchFunctions.ObjectGet
467
+ case "ObjectList":
468
+ return additionalProperty.SearchFunctions.ObjectList
469
+ case "ExploreGet":
470
+ return additionalProperty.SearchFunctions.ExploreGet
471
+ case "ExploreList":
472
+ return additionalProperty.SearchFunctions.ExploreList
473
+ default:
474
+ return nil
475
+ }
476
+ }
477
+
478
+ func (p *fakeModulesProvider) getExtender() *fakeExtender {
479
+ if p.customExtender != nil {
480
+ return p.customExtender
481
+ }
482
+ return &fakeExtender{}
483
+ }
484
+
485
+ func (p *fakeModulesProvider) getProjector() *fakeProjector {
486
+ if p.customProjector != nil {
487
+ return p.customProjector
488
+ }
489
+ return &fakeProjector{}
490
+ }
491
+
492
+ type nearCustomTextParams struct {
493
+ Values []string
494
+ MoveTo nearExploreMove
495
+ Certainty float64
496
+ }
497
+
498
+ type nearExploreMove struct {
499
+ Values []string
500
+ Force float32
501
+ Objects []nearObjectMove
502
+ }
503
+
504
+ type nearObjectMove struct {
505
+ ID string
506
+ Beacon string
507
+ }
508
+
509
+ type nearCustomTextModule struct {
510
+ fakeExtender *fakeExtender
511
+ fakeProjector *fakeProjector
512
+ fakePathBuilder *fakePathBuilder
513
+ }
514
+
515
+ func newNearCustomTextModule(
516
+ fakeExtender *fakeExtender,
517
+ fakeProjector *fakeProjector,
518
+ fakePathBuilder *fakePathBuilder,
519
+ ) *nearCustomTextModule {
520
+ return &nearCustomTextModule{fakeExtender, fakeProjector, fakePathBuilder}
521
+ }
522
+
523
+ func (m *nearCustomTextModule) Name() string {
524
+ return "mock-custom-near-text-module"
525
+ }
526
+
527
+ func (m *nearCustomTextModule) Init(params moduletools.ModuleInitParams) error {
528
+ return nil
529
+ }
530
+
531
+ func (m *nearCustomTextModule) getNearCustomTextArgument(classname string) *graphql.ArgumentConfig {
532
+ prefix := classname
533
+ return &graphql.ArgumentConfig{
534
+ Type: graphql.NewInputObject(
535
+ graphql.InputObjectConfig{
536
+ Name: fmt.Sprintf("%sNearCustomTextInpObj", prefix),
537
+ Fields: graphql.InputObjectConfigFieldMap{
538
+ "concepts": &graphql.InputObjectFieldConfig{
539
+ Type: graphql.NewNonNull(graphql.NewList(graphql.String)),
540
+ },
541
+ "moveTo": &graphql.InputObjectFieldConfig{
542
+ Description: descriptions.VectorMovement,
543
+ Type: graphql.NewInputObject(
544
+ graphql.InputObjectConfig{
545
+ Name: fmt.Sprintf("%sMoveTo", prefix),
546
+ Fields: graphql.InputObjectConfigFieldMap{
547
+ "concepts": &graphql.InputObjectFieldConfig{
548
+ Description: descriptions.Keywords,
549
+ Type: graphql.NewList(graphql.String),
550
+ },
551
+ "objects": &graphql.InputObjectFieldConfig{
552
+ Description: "objects",
553
+ Type: graphql.NewList(graphql.NewInputObject(
554
+ graphql.InputObjectConfig{
555
+ Name: fmt.Sprintf("%sMovementObjectsInpObj", prefix),
556
+ Fields: graphql.InputObjectConfigFieldMap{
557
+ "id": &graphql.InputObjectFieldConfig{
558
+ Type: graphql.String,
559
+ Description: "id of an object",
560
+ },
561
+ "beacon": &graphql.InputObjectFieldConfig{
562
+ Type: graphql.String,
563
+ Description: descriptions.Beacon,
564
+ },
565
+ },
566
+ Description: "Movement Object",
567
+ },
568
+ )),
569
+ },
570
+ "force": &graphql.InputObjectFieldConfig{
571
+ Description: descriptions.Force,
572
+ Type: graphql.NewNonNull(graphql.Float),
573
+ },
574
+ },
575
+ }),
576
+ },
577
+ "certainty": &graphql.InputObjectFieldConfig{
578
+ Description: descriptions.Certainty,
579
+ Type: graphql.Float,
580
+ },
581
+ },
582
+ Description: descriptions.GetWhereInpObj,
583
+ },
584
+ ),
585
+ }
586
+ }
587
+
588
+ func (m *nearCustomTextModule) extractNearCustomTextArgument(source map[string]interface{}) *nearCustomTextParams {
589
+ var args nearCustomTextParams
590
+
591
+ concepts := source["concepts"].([]interface{})
592
+ args.Values = make([]string, len(concepts))
593
+ for i, value := range concepts {
594
+ args.Values[i] = value.(string)
595
+ }
596
+
597
+ certainty, ok := source["certainty"]
598
+ if ok {
599
+ args.Certainty = certainty.(float64)
600
+ }
601
+
602
+ // moveTo is an optional arg, so it could be nil
603
+ moveTo, ok := source["moveTo"]
604
+ if ok {
605
+ moveToMap := moveTo.(map[string]interface{})
606
+ res := nearExploreMove{}
607
+ res.Force = float32(moveToMap["force"].(float64))
608
+
609
+ concepts, ok := moveToMap["concepts"].([]interface{})
610
+ if ok {
611
+ res.Values = make([]string, len(concepts))
612
+ for i, value := range concepts {
613
+ res.Values[i] = value.(string)
614
+ }
615
+ }
616
+
617
+ objects, ok := moveToMap["objects"].([]interface{})
618
+ if ok {
619
+ res.Objects = make([]nearObjectMove, len(objects))
620
+ for i, value := range objects {
621
+ v, ok := value.(map[string]interface{})
622
+ if ok {
623
+ if v["id"] != nil {
624
+ res.Objects[i].ID = v["id"].(string)
625
+ }
626
+ if v["beacon"] != nil {
627
+ res.Objects[i].Beacon = v["beacon"].(string)
628
+ }
629
+ }
630
+ }
631
+ }
632
+
633
+ args.MoveTo = res
634
+ }
635
+
636
+ return &args
637
+ }
638
+
639
+ func (m *nearCustomTextModule) Arguments() map[string]modulecapabilities.GraphQLArgument {
640
+ arguments := map[string]modulecapabilities.GraphQLArgument{}
641
+ // define nearCustomText argument
642
+ arguments["nearCustomText"] = modulecapabilities.GraphQLArgument{
643
+ GetArgumentsFunction: func(classname string) *graphql.ArgumentConfig {
644
+ return m.getNearCustomTextArgument(classname)
645
+ },
646
+ ExtractFunction: func(source map[string]interface{}) (interface{}, *dto.TargetCombination, error) {
647
+ params := m.extractNearCustomTextArgument(source)
648
+ return params, nil, nil
649
+ },
650
+ ValidateFunction: func(param interface{}) error {
651
+ // all is valid
652
+ return nil
653
+ },
654
+ }
655
+ return arguments
656
+ }
657
+
658
+ // additional properties
659
+ func (m *nearCustomTextModule) AdditionalProperties() map[string]modulecapabilities.AdditionalProperty {
660
+ additionalProperties := map[string]modulecapabilities.AdditionalProperty{}
661
+ additionalProperties["featureProjection"] = m.getFeatureProjection()
662
+ additionalProperties["nearestNeighbors"] = m.getNearestNeighbors()
663
+ additionalProperties["semanticPath"] = m.getSemanticPath()
664
+ return additionalProperties
665
+ }
666
+
667
+ func (m *nearCustomTextModule) getFeatureProjection() modulecapabilities.AdditionalProperty {
668
+ return modulecapabilities.AdditionalProperty{
669
+ DefaultValue: m.fakeProjector.AdditionalPropertyDefaultValue(),
670
+ GraphQLNames: []string{"featureProjection"},
671
+ GraphQLFieldFunction: func(classname string) *graphql.Field {
672
+ return &graphql.Field{
673
+ Args: graphql.FieldConfigArgument{
674
+ "algorithm": &graphql.ArgumentConfig{
675
+ Type: graphql.String,
676
+ DefaultValue: nil,
677
+ },
678
+ "dimensions": &graphql.ArgumentConfig{
679
+ Type: graphql.Int,
680
+ DefaultValue: nil,
681
+ },
682
+ "learningRate": &graphql.ArgumentConfig{
683
+ Type: graphql.Int,
684
+ DefaultValue: nil,
685
+ },
686
+ "iterations": &graphql.ArgumentConfig{
687
+ Type: graphql.Int,
688
+ DefaultValue: nil,
689
+ },
690
+ "perplexity": &graphql.ArgumentConfig{
691
+ Type: graphql.Int,
692
+ DefaultValue: nil,
693
+ },
694
+ },
695
+ Type: graphql.NewObject(graphql.ObjectConfig{
696
+ Name: fmt.Sprintf("%sAdditionalFeatureProjection", classname),
697
+ Fields: graphql.Fields{
698
+ "vector": &graphql.Field{Type: graphql.NewList(graphql.Float)},
699
+ },
700
+ }),
701
+ }
702
+ },
703
+ GraphQLExtractFunction: m.fakeProjector.ExtractAdditionalFn,
704
+ SearchFunctions: modulecapabilities.AdditionalSearch{
705
+ ObjectList: m.fakeProjector.AdditionalPropertyFn,
706
+ ExploreGet: m.fakeProjector.AdditionalPropertyFn,
707
+ ExploreList: m.fakeProjector.AdditionalPropertyFn,
708
+ },
709
+ }
710
+ }
711
+
712
+ func (m *nearCustomTextModule) getNearestNeighbors() modulecapabilities.AdditionalProperty {
713
+ return modulecapabilities.AdditionalProperty{
714
+ DefaultValue: m.fakeExtender.AdditionalPropertyDefaultValue(),
715
+ GraphQLNames: []string{"nearestNeighbors"},
716
+ GraphQLFieldFunction: func(classname string) *graphql.Field {
717
+ return &graphql.Field{
718
+ Type: graphql.NewObject(graphql.ObjectConfig{
719
+ Name: fmt.Sprintf("%sAdditionalNearestNeighbors", classname),
720
+ Fields: graphql.Fields{
721
+ "neighbors": &graphql.Field{Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{
722
+ Name: fmt.Sprintf("%sAdditionalNearestNeighborsNeighbors", classname),
723
+ Fields: graphql.Fields{
724
+ "concept": &graphql.Field{Type: graphql.String},
725
+ "distance": &graphql.Field{Type: graphql.Float},
726
+ },
727
+ }))},
728
+ },
729
+ }),
730
+ }
731
+ },
732
+ GraphQLExtractFunction: m.fakeExtender.ExtractAdditionalFn,
733
+ SearchFunctions: modulecapabilities.AdditionalSearch{
734
+ ObjectGet: m.fakeExtender.AdditionalPropertyFn,
735
+ ObjectList: m.fakeExtender.AdditionalPropertyFn,
736
+ ExploreGet: m.fakeExtender.AdditionalPropertyFn,
737
+ ExploreList: m.fakeExtender.AdditionalPropertyFn,
738
+ },
739
+ }
740
+ }
741
+
742
+ func (m *nearCustomTextModule) getSemanticPath() modulecapabilities.AdditionalProperty {
743
+ return modulecapabilities.AdditionalProperty{
744
+ DefaultValue: m.fakePathBuilder.AdditionalPropertyDefaultValue(),
745
+ GraphQLNames: []string{"semanticPath"},
746
+ GraphQLFieldFunction: func(classname string) *graphql.Field {
747
+ return &graphql.Field{
748
+ Type: graphql.NewObject(graphql.ObjectConfig{
749
+ Name: fmt.Sprintf("%sAdditionalSemanticPath", classname),
750
+ Fields: graphql.Fields{
751
+ "path": &graphql.Field{Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{
752
+ Name: fmt.Sprintf("%sAdditionalSemanticPathElement", classname),
753
+ Fields: graphql.Fields{
754
+ "concept": &graphql.Field{Type: graphql.String},
755
+ "distanceToQuery": &graphql.Field{Type: graphql.Float},
756
+ "distanceToResult": &graphql.Field{Type: graphql.Float},
757
+ "distanceToNext": &graphql.Field{Type: graphql.Float},
758
+ "distanceToPrevious": &graphql.Field{Type: graphql.Float},
759
+ },
760
+ }))},
761
+ },
762
+ }),
763
+ }
764
+ },
765
+ GraphQLExtractFunction: m.fakePathBuilder.ExtractAdditionalFn,
766
+ SearchFunctions: modulecapabilities.AdditionalSearch{
767
+ ExploreGet: m.fakePathBuilder.AdditionalPropertyFn,
768
+ },
769
+ }
770
+ }
771
+
772
+ type fakeParams struct{}
773
+
774
+ func getDefaultParam(name string) interface{} {
775
+ switch name {
776
+ case "featureProjection", "semanticPath":
777
+ return &fakeParams{}
778
+ case "nearestNeighbors":
779
+ return true
780
+ default:
781
+ return nil
782
+ }
783
+ }
784
+
785
+ func getFakeModulesProvider(opts ...func(p *fakeModulesProvider)) *fakeModulesProvider {
786
+ p := &fakeModulesProvider{}
787
+ p.applyOptions(opts...)
788
+ return p
789
+ }
790
+
791
+ func (p *fakeModulesProvider) applyOptions(opts ...func(provider *fakeModulesProvider)) {
792
+ for _, opt := range opts {
793
+ opt(p)
794
+ }
795
+ }
796
+
797
+ func getFakeModulesProviderWithCustomExtenders(
798
+ customExtender *fakeExtender,
799
+ customProjector *fakeProjector,
800
+ opts ...func(provider *fakeModulesProvider),
801
+ ) *fakeModulesProvider {
802
+ p := &fakeModulesProvider{mock.Mock{}, customExtender, customProjector}
803
+ p.applyOptions(opts...)
804
+ return p
805
+ }
806
+
807
+ type fakeMetrics struct {
808
+ // Note: only those metric functions that relate to usage-related metrics are
809
+ // covered by this mock, others are empty shells
810
+ mock.Mock
811
+ }
812
+
813
+ func (f *fakeMetrics) BatchInc() {
814
+ }
815
+
816
+ func (f *fakeMetrics) BatchDec() {
817
+ }
818
+
819
+ func (f *fakeMetrics) BatchRefInc() {
820
+ }
821
+
822
+ func (f *fakeMetrics) BatchRefDec() {
823
+ }
824
+
825
+ func (f *fakeMetrics) BatchDeleteInc() {
826
+ }
827
+
828
+ func (f *fakeMetrics) BatchDeleteDec() {
829
+ }
830
+
831
+ func (f *fakeMetrics) AddObjectInc() {
832
+ }
833
+
834
+ func (f *fakeMetrics) AddObjectDec() {
835
+ }
836
+
837
+ func (f *fakeMetrics) UpdateObjectInc() {
838
+ }
839
+
840
+ func (f *fakeMetrics) UpdateObjectDec() {
841
+ }
842
+
843
+ func (f *fakeMetrics) MergeObjectInc() {
844
+ }
845
+
846
+ func (f *fakeMetrics) MergeObjectDec() {
847
+ }
848
+
849
+ func (f *fakeMetrics) DeleteObjectInc() {
850
+ }
851
+
852
+ func (f *fakeMetrics) DeleteObjectDec() {
853
+ }
854
+
855
+ func (f *fakeMetrics) GetObjectInc() {
856
+ }
857
+
858
+ func (f *fakeMetrics) GetObjectDec() {
859
+ }
860
+
861
+ func (f *fakeMetrics) HeadObjectInc() {
862
+ }
863
+
864
+ func (f *fakeMetrics) HeadObjectDec() {
865
+ }
866
+
867
+ func (f *fakeMetrics) AddReferenceInc() {
868
+ }
869
+
870
+ func (f *fakeMetrics) AddReferenceDec() {
871
+ }
872
+
873
+ func (f *fakeMetrics) UpdateReferenceInc() {
874
+ }
875
+
876
+ func (f *fakeMetrics) UpdateReferenceDec() {
877
+ }
878
+
879
+ func (f *fakeMetrics) DeleteReferenceInc() {
880
+ }
881
+
882
+ func (f *fakeMetrics) DeleteReferenceDec() {
883
+ }
884
+
885
+ func (f *fakeMetrics) AddUsageDimensions(className, queryType, op string, dims int) {
886
+ f.Mock.MethodCalled("AddUsageDimensions", className, queryType, op, dims)
887
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/get.go ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "strings"
19
+
20
+ "github.com/go-openapi/strfmt"
21
+
22
+ "github.com/weaviate/weaviate/entities/additional"
23
+ "github.com/weaviate/weaviate/entities/filters"
24
+ "github.com/weaviate/weaviate/entities/models"
25
+ "github.com/weaviate/weaviate/entities/schema"
26
+ "github.com/weaviate/weaviate/entities/search"
27
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
28
+ authzerrs "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
29
+ "github.com/weaviate/weaviate/usecases/auth/authorization/filter"
30
+ )
31
+
32
+ // GetObject Class from the connected DB
33
+ func (m *Manager) GetObject(ctx context.Context, principal *models.Principal,
34
+ class string, id strfmt.UUID, additional additional.Properties,
35
+ replProps *additional.ReplicationProperties, tenant string,
36
+ ) (*models.Object, error) {
37
+ class = schema.UppercaseClassName(class)
38
+ class, _ = m.resolveAlias(class)
39
+
40
+ err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Objects(class, tenant, id))
41
+ if err != nil {
42
+ return nil, err
43
+ }
44
+
45
+ m.metrics.GetObjectInc()
46
+ defer m.metrics.GetObjectDec()
47
+
48
+ res, err := m.getObjectFromRepo(ctx, class, id, additional, replProps, tenant)
49
+ if err != nil {
50
+ return nil, err
51
+ }
52
+
53
+ if additional.Vector {
54
+ m.trackUsageSingle(res)
55
+ }
56
+
57
+ obj := res.ObjectWithVector(additional.Vector)
58
+ return obj, nil
59
+ }
60
+
61
+ // GetObjects Class from the connected DB
62
+ func (m *Manager) GetObjects(ctx context.Context, principal *models.Principal,
63
+ offset *int64, limit *int64, sort *string, order *string, after *string,
64
+ addl additional.Properties, tenant string,
65
+ ) ([]*models.Object, error) {
66
+ err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Objects("", tenant, ""))
67
+ if err != nil {
68
+ return nil, err
69
+ }
70
+
71
+ m.metrics.GetObjectInc()
72
+ defer m.metrics.GetObjectDec()
73
+
74
+ objects, err := m.getObjectsFromRepo(ctx, offset, limit, sort, order, after, addl, tenant)
75
+ if err != nil {
76
+ return nil, err
77
+ }
78
+
79
+ // Filter objects based on authorization
80
+ resourceFilter := filter.New[*models.Object](m.authorizer, m.config.Config.Authorization.Rbac)
81
+ filteredObjects := resourceFilter.Filter(
82
+ ctx,
83
+ m.logger,
84
+ principal,
85
+ objects,
86
+ authorization.READ,
87
+ func(obj *models.Object) string {
88
+ return authorization.Objects(obj.Class, tenant, obj.ID)
89
+ },
90
+ )
91
+
92
+ return filteredObjects, nil
93
+ }
94
+
95
+ func (m *Manager) GetObjectsClass(ctx context.Context, principal *models.Principal,
96
+ id strfmt.UUID,
97
+ ) (*models.Class, error) {
98
+ err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Objects("", "", id))
99
+ if err != nil {
100
+ return nil, err
101
+ }
102
+
103
+ m.metrics.GetObjectInc()
104
+ defer m.metrics.GetObjectDec()
105
+
106
+ res, err := m.getObjectFromRepo(ctx, "", id, additional.Properties{}, nil, "")
107
+ if err != nil {
108
+ return nil, err
109
+ }
110
+
111
+ class, err := m.schemaManager.GetClass(ctx, principal, res.ClassName)
112
+ return class, err
113
+ }
114
+
115
+ func (m *Manager) GetObjectClassFromName(ctx context.Context, principal *models.Principal,
116
+ className string,
117
+ ) (*models.Class, error) {
118
+ class, err := m.schemaManager.GetClass(ctx, principal, className)
119
+ return class, err
120
+ }
121
+
122
+ func (m *Manager) getObjectFromRepo(ctx context.Context, class string, id strfmt.UUID,
123
+ adds additional.Properties, repl *additional.ReplicationProperties, tenant string,
124
+ ) (res *search.Result, err error) {
125
+ if class != "" {
126
+ if cls := m.schemaManager.ResolveAlias(class); cls != "" {
127
+ class = cls
128
+ }
129
+ res, err = m.vectorRepo.Object(ctx, class, id, search.SelectProperties{}, adds, repl, tenant)
130
+ } else {
131
+ res, err = m.vectorRepo.ObjectByID(ctx, id, search.SelectProperties{}, adds, tenant)
132
+ }
133
+ if err != nil {
134
+ switch {
135
+ case errors.As(err, &ErrMultiTenancy{}):
136
+ return nil, NewErrMultiTenancy(fmt.Errorf("repo: object by id: %w", err))
137
+ default:
138
+ if errors.As(err, &authzerrs.Forbidden{}) {
139
+ return nil, fmt.Errorf("repo: object by id: %w", err)
140
+ }
141
+ return nil, NewErrInternal("repo: object by id: %v", err)
142
+ }
143
+ }
144
+
145
+ if res == nil {
146
+ return nil, NewErrNotFound("no object with id '%s'", id)
147
+ }
148
+
149
+ if m.modulesProvider != nil {
150
+ res, err = m.modulesProvider.GetObjectAdditionalExtend(ctx, res, adds.ModuleParams)
151
+ if err != nil {
152
+ return nil, fmt.Errorf("get extend: %w", err)
153
+ }
154
+ }
155
+
156
+ return res, nil
157
+ }
158
+
159
+ func (m *Manager) getObjectsFromRepo(ctx context.Context,
160
+ offset, limit *int64, sort, order *string, after *string,
161
+ additional additional.Properties, tenant string,
162
+ ) ([]*models.Object, error) {
163
+ smartOffset, smartLimit, err := m.localOffsetLimit(offset, limit)
164
+ if err != nil {
165
+ return nil, NewErrInternal("list objects: %v", err)
166
+ }
167
+ if after != nil {
168
+ return nil, NewErrInternal("list objects: after parameter not allowed, cursor must be specific to one class, set class query param")
169
+ }
170
+ res, err := m.vectorRepo.ObjectSearch(ctx, smartOffset, smartLimit,
171
+ nil, m.getSort(sort, order), additional, tenant)
172
+ if err != nil {
173
+ return nil, NewErrInternal("list objects: %v", err)
174
+ }
175
+
176
+ if m.modulesProvider != nil {
177
+ res, err = m.modulesProvider.ListObjectsAdditionalExtend(ctx, res, additional.ModuleParams)
178
+ if err != nil {
179
+ return nil, NewErrInternal("list extend: %v", err)
180
+ }
181
+ }
182
+
183
+ if additional.Vector {
184
+ m.trackUsageList(res)
185
+ }
186
+
187
+ return res.ObjectsWithVector(additional.Vector), nil
188
+ }
189
+
190
+ func (m *Manager) getSort(sort, order *string) []filters.Sort {
191
+ if sort != nil {
192
+ sortParams := strings.Split(*sort, ",")
193
+ var orderParams []string
194
+ if order != nil {
195
+ orderParams = strings.Split(*order, ",")
196
+ }
197
+ var res []filters.Sort
198
+ for i := range sortParams {
199
+ res = append(res, filters.Sort{
200
+ Path: []string{sortParams[i]},
201
+ Order: m.getOrder(orderParams, i),
202
+ })
203
+ }
204
+ return res
205
+ }
206
+ return nil
207
+ }
208
+
209
+ func (m *Manager) getOrder(order []string, i int) string {
210
+ if len(order) > i {
211
+ switch order[i] {
212
+ case "asc", "desc":
213
+ return order[i]
214
+ default:
215
+ return "asc"
216
+ }
217
+ }
218
+ return "asc"
219
+ }
220
+
221
+ func (m *Manager) localOffsetOrZero(paramOffset *int64) int {
222
+ offset := int64(0)
223
+ if paramOffset != nil {
224
+ offset = *paramOffset
225
+ }
226
+
227
+ return int(offset)
228
+ }
229
+
230
+ func (m *Manager) localLimitOrGlobalLimit(offset int64, paramMaxResults *int64) int {
231
+ limit := int64(m.config.Config.QueryDefaults.Limit)
232
+ // Get the max results from params, if exists
233
+ if paramMaxResults != nil {
234
+ limit = *paramMaxResults
235
+ }
236
+
237
+ return int(limit)
238
+ }
239
+
240
+ func (m *Manager) localOffsetLimit(paramOffset *int64, paramLimit *int64) (int, int, error) {
241
+ offset := m.localOffsetOrZero(paramOffset)
242
+ limit := m.localLimitOrGlobalLimit(int64(offset), paramLimit)
243
+
244
+ if int64(offset+limit) > m.config.Config.QueryMaximumResults {
245
+ return 0, 0, errors.New("query maximum results exceeded")
246
+ }
247
+
248
+ return offset, limit, nil
249
+ }
250
+
251
+ func (m *Manager) trackUsageSingle(res *search.Result) {
252
+ if res == nil {
253
+ return
254
+ }
255
+ m.metrics.AddUsageDimensions(res.ClassName, "get_rest", "single_include_vector", res.Dims)
256
+ }
257
+
258
+ func (m *Manager) trackUsageList(res search.Results) {
259
+ if len(res) == 0 {
260
+ return
261
+ }
262
+ m.metrics.AddUsageDimensions(res[0].ClassName, "get_rest", "list_include_vector", res[0].Dims)
263
+ }
264
+
265
+ func (m *Manager) getCursor(after *string, limit *int64) *filters.Cursor {
266
+ if after != nil {
267
+ if limit == nil {
268
+ // limit -1 means that no limit param was set
269
+ return &filters.Cursor{After: *after, Limit: -1}
270
+ }
271
+ return &filters.Cursor{After: *after, Limit: int(*limit)}
272
+ }
273
+ return nil
274
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/get_test.go ADDED
@@ -0,0 +1,1099 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "testing"
18
+
19
+ "github.com/go-openapi/strfmt"
20
+ "github.com/prometheus/client_golang/prometheus"
21
+ "github.com/sirupsen/logrus/hooks/test"
22
+ "github.com/stretchr/testify/assert"
23
+ "github.com/stretchr/testify/mock"
24
+ "github.com/stretchr/testify/require"
25
+
26
+ "github.com/weaviate/weaviate/entities/additional"
27
+ "github.com/weaviate/weaviate/entities/filters"
28
+ "github.com/weaviate/weaviate/entities/models"
29
+ "github.com/weaviate/weaviate/entities/schema"
30
+ "github.com/weaviate/weaviate/entities/search"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ )
34
+
35
+ func Test_GetAction(t *testing.T) {
36
+ var (
37
+ vectorRepo *fakeVectorRepo
38
+ manager *Manager
39
+ extender *fakeExtender
40
+ projectorFake *fakeProjector
41
+ metrics *fakeMetrics
42
+ )
43
+
44
+ schema := schema.Schema{
45
+ Objects: &models.Schema{
46
+ Classes: []*models.Class{
47
+ {
48
+ Class: "ActionClass",
49
+ },
50
+ },
51
+ },
52
+ }
53
+
54
+ reset := func() {
55
+ vectorRepo = &fakeVectorRepo{}
56
+ schemaManager := &fakeSchemaManager{
57
+ GetSchemaResponse: schema,
58
+ }
59
+ cfg := &config.WeaviateConfig{}
60
+ cfg.Config.QueryDefaults.Limit = 20
61
+ cfg.Config.QueryMaximumResults = 200
62
+ authorizer := mocks.NewMockAuthorizer()
63
+ logger, _ := test.NewNullLogger()
64
+ extender = &fakeExtender{}
65
+ projectorFake = &fakeProjector{}
66
+ metrics = &fakeMetrics{}
67
+ manager = NewManager(schemaManager, cfg, logger,
68
+ authorizer, vectorRepo,
69
+ getFakeModulesProviderWithCustomExtenders(extender, projectorFake), metrics, nil,
70
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
71
+ }
72
+
73
+ t.Run("get non-existing action by id", func(t *testing.T) {
74
+ reset()
75
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
76
+
77
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return((*search.Result)(nil), nil).Once()
78
+
79
+ _, err := manager.GetObject(context.Background(), &models.Principal{}, "",
80
+ id, additional.Properties{}, nil, "")
81
+ assert.Equal(t, NewErrNotFound("no object with id '99ee9968-22ec-416a-9032-cff80f2f7fdf'"), err)
82
+ })
83
+
84
+ t.Run("get existing action by id", func(t *testing.T) {
85
+ reset()
86
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
87
+
88
+ result := &search.Result{
89
+ ID: id,
90
+ ClassName: "ActionClass",
91
+ Schema: map[string]interface{}{"foo": "bar"},
92
+ }
93
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
94
+
95
+ expected := &models.Object{
96
+ ID: id,
97
+ Class: "ActionClass",
98
+ Properties: map[string]interface{}{"foo": "bar"},
99
+ VectorWeights: (map[string]string)(nil),
100
+ }
101
+
102
+ res, err := manager.GetObject(context.Background(), &models.Principal{}, "",
103
+ id, additional.Properties{}, nil, "")
104
+ require.Nil(t, err)
105
+ assert.Equal(t, expected, res)
106
+ })
107
+
108
+ t.Run("get existing object by id with vector without classname (deprecated)", func(t *testing.T) {
109
+ reset()
110
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
111
+
112
+ result := &search.Result{
113
+ ID: id,
114
+ ClassName: "ActionClass",
115
+ Schema: map[string]interface{}{"foo": "bar"},
116
+ Vector: []float32{1, 2, 3},
117
+ Dims: 3,
118
+ }
119
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
120
+
121
+ expected := &models.Object{
122
+ ID: id,
123
+ Class: "ActionClass",
124
+ Properties: map[string]interface{}{"foo": "bar"},
125
+ VectorWeights: (map[string]string)(nil),
126
+ Vector: []float32{1, 2, 3},
127
+ }
128
+
129
+ metrics.On("AddUsageDimensions", "ActionClass", "get_rest", "single_include_vector", 3)
130
+
131
+ res, err := manager.GetObject(context.Background(), &models.Principal{}, "",
132
+ id, additional.Properties{Vector: true}, nil, "")
133
+ require.Nil(t, err)
134
+ assert.Equal(t, expected, res)
135
+ })
136
+
137
+ t.Run("get existing object by id with vector with classname", func(t *testing.T) {
138
+ reset()
139
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
140
+
141
+ result := &search.Result{
142
+ ID: id,
143
+ ClassName: "ActionClass",
144
+ Schema: map[string]interface{}{"foo": "bar"},
145
+ Vector: []float32{1, 2, 3},
146
+ Dims: 3,
147
+ }
148
+ vectorRepo.On("Object", "ActionClass", id, mock.Anything, mock.Anything, "").
149
+ Return(result, nil).Once()
150
+
151
+ expected := &models.Object{
152
+ ID: id,
153
+ Class: "ActionClass",
154
+ Properties: map[string]interface{}{"foo": "bar"},
155
+ VectorWeights: (map[string]string)(nil),
156
+ Vector: []float32{1, 2, 3},
157
+ }
158
+
159
+ metrics.On("AddUsageDimensions", "ActionClass", "get_rest", "single_include_vector", 3)
160
+
161
+ res, err := manager.GetObject(context.Background(), &models.Principal{},
162
+ "ActionClass", id, additional.Properties{Vector: true}, nil, "")
163
+ require.Nil(t, err)
164
+ assert.Equal(t, expected, res)
165
+ })
166
+
167
+ t.Run("list all existing actions with all default pagination settings", func(t *testing.T) {
168
+ reset()
169
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
170
+
171
+ results := []search.Result{
172
+ {
173
+ ID: id,
174
+ ClassName: "ActionClass",
175
+ Schema: map[string]interface{}{"foo": "bar"},
176
+ },
177
+ }
178
+ vectorRepo.On("ObjectSearch", 0, 20, mock.Anything, mock.Anything, mock.Anything,
179
+ mock.Anything).Return(results, nil).Once()
180
+
181
+ expected := []*models.Object{
182
+ {
183
+ ID: id,
184
+ Class: "ActionClass",
185
+ Properties: map[string]interface{}{"foo": "bar"},
186
+ VectorWeights: (map[string]string)(nil),
187
+ },
188
+ }
189
+
190
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, nil, nil, nil, nil, additional.Properties{}, "")
191
+ require.Nil(t, err)
192
+ assert.Equal(t, expected, res)
193
+ })
194
+
195
+ t.Run("list all existing objects with vectors", func(t *testing.T) {
196
+ reset()
197
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
198
+
199
+ results := []search.Result{
200
+ {
201
+ ID: id,
202
+ ClassName: "ActionClass",
203
+ Schema: map[string]interface{}{"foo": "bar"},
204
+ Vector: []float32{1, 2, 3},
205
+ Dims: 3,
206
+ },
207
+ }
208
+ vectorRepo.On("ObjectSearch", 0, 20, mock.Anything, mock.Anything, mock.Anything,
209
+ mock.Anything).Return(results, nil).Once()
210
+
211
+ metrics.On("AddUsageDimensions", "ActionClass", "get_rest", "list_include_vector", 3)
212
+
213
+ expected := []*models.Object{
214
+ {
215
+ ID: id,
216
+ Class: "ActionClass",
217
+ Properties: map[string]interface{}{"foo": "bar"},
218
+ VectorWeights: (map[string]string)(nil),
219
+ Vector: []float32{1, 2, 3},
220
+ },
221
+ }
222
+
223
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, nil, nil, nil, nil, additional.Properties{Vector: true}, "")
224
+ require.Nil(t, err)
225
+ assert.Equal(t, expected, res)
226
+ })
227
+
228
+ t.Run("list all existing actions with all explicit offset and limit", func(t *testing.T) {
229
+ reset()
230
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
231
+
232
+ results := []search.Result{
233
+ {
234
+ ID: id,
235
+ ClassName: "ActionClass",
236
+ Schema: map[string]interface{}{"foo": "bar"},
237
+ },
238
+ }
239
+ vectorRepo.On("ObjectSearch", 7, 2, mock.Anything, mock.Anything, mock.Anything,
240
+ mock.Anything).Return(results, nil).Once()
241
+
242
+ expected := []*models.Object{
243
+ {
244
+ ID: id,
245
+ Class: "ActionClass",
246
+ Properties: map[string]interface{}{"foo": "bar"},
247
+ VectorWeights: (map[string]string)(nil),
248
+ },
249
+ }
250
+
251
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, ptInt64(7), ptInt64(2), nil, nil, nil, additional.Properties{}, "")
252
+ require.Nil(t, err)
253
+ assert.Equal(t, expected, res)
254
+ })
255
+
256
+ t.Run("with an offset greater than the maximum", func(t *testing.T) {
257
+ reset()
258
+
259
+ _, err := manager.GetObjects(context.Background(), &models.Principal{}, ptInt64(201), ptInt64(2), nil, nil, nil, additional.Properties{}, "")
260
+ require.NotNil(t, err)
261
+ assert.Contains(t, err.Error(), "query maximum results exceeded")
262
+ })
263
+
264
+ t.Run("with a limit greater than the minimum", func(t *testing.T) {
265
+ reset()
266
+
267
+ _, err := manager.GetObjects(context.Background(), &models.Principal{}, ptInt64(0), ptInt64(202), nil, nil, nil, additional.Properties{}, "")
268
+ require.NotNil(t, err)
269
+ assert.Contains(t, err.Error(), "query maximum results exceeded")
270
+ })
271
+
272
+ t.Run("with limit and offset individually smaller, but combined greater", func(t *testing.T) {
273
+ reset()
274
+
275
+ _, err := manager.GetObjects(context.Background(), &models.Principal{}, ptInt64(150), ptInt64(150), nil, nil, nil, additional.Properties{}, "")
276
+ require.NotNil(t, err)
277
+ assert.Contains(t, err.Error(), "query maximum results exceeded")
278
+ })
279
+
280
+ t.Run("additional props", func(t *testing.T) {
281
+ t.Run("on get single requests", func(t *testing.T) {
282
+ t.Run("feature projection", func(t *testing.T) {
283
+ reset()
284
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
285
+
286
+ result := &search.Result{
287
+ ID: id,
288
+ ClassName: "ActionClass",
289
+ Schema: map[string]interface{}{"foo": "bar"},
290
+ }
291
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
292
+ _, err := manager.GetObject(context.Background(), &models.Principal{}, "",
293
+ id, additional.Properties{
294
+ ModuleParams: map[string]interface{}{
295
+ "featureProjection": getDefaultParam("featureProjection"),
296
+ },
297
+ }, nil, "")
298
+ assert.Equal(t, errors.New("get extend: unknown capability: featureProjection").Error(), err.Error())
299
+ })
300
+
301
+ t.Run("semantic path", func(t *testing.T) {
302
+ reset()
303
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
304
+
305
+ result := &search.Result{
306
+ ID: id,
307
+ ClassName: "ActionClass",
308
+ Schema: map[string]interface{}{"foo": "bar"},
309
+ }
310
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
311
+ _, err := manager.GetObject(context.Background(), &models.Principal{}, "",
312
+ id, additional.Properties{
313
+ ModuleParams: map[string]interface{}{
314
+ "semanticPath": getDefaultParam("semanticPath"),
315
+ },
316
+ }, nil, "")
317
+ assert.Equal(t, errors.New("get extend: unknown capability: semanticPath").Error(), err.Error())
318
+ })
319
+
320
+ t.Run("nearest neighbors", func(t *testing.T) {
321
+ reset()
322
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
323
+
324
+ result := &search.Result{
325
+ ID: id,
326
+ ClassName: "ActionClass",
327
+ Schema: map[string]interface{}{"foo": "bar"},
328
+ }
329
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
330
+ extender.multi = []search.Result{
331
+ {
332
+ ID: id,
333
+ ClassName: "ActionClass",
334
+ Schema: map[string]interface{}{"foo": "bar"},
335
+ AdditionalProperties: models.AdditionalProperties{
336
+ "nearestNeighbors": &NearestNeighbors{
337
+ Neighbors: []*NearestNeighbor{
338
+ {
339
+ Concept: "foo",
340
+ Distance: 0.3,
341
+ },
342
+ },
343
+ },
344
+ },
345
+ },
346
+ }
347
+
348
+ expected := &models.Object{
349
+ ID: id,
350
+ Class: "ActionClass",
351
+ Properties: map[string]interface{}{"foo": "bar"},
352
+ VectorWeights: (map[string]string)(nil),
353
+ Additional: models.AdditionalProperties{
354
+ "nearestNeighbors": &NearestNeighbors{
355
+ Neighbors: []*NearestNeighbor{
356
+ {
357
+ Concept: "foo",
358
+ Distance: 0.3,
359
+ },
360
+ },
361
+ },
362
+ },
363
+ }
364
+
365
+ res, err := manager.GetObject(context.Background(), &models.Principal{}, "",
366
+ id, additional.Properties{
367
+ ModuleParams: map[string]interface{}{
368
+ "nearestNeighbors": true,
369
+ },
370
+ }, nil, "")
371
+ require.Nil(t, err)
372
+ assert.Equal(t, expected, res)
373
+ })
374
+ })
375
+
376
+ t.Run("on list requests", func(t *testing.T) {
377
+ t.Run("nearest neighbors", func(t *testing.T) {
378
+ reset()
379
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
380
+
381
+ result := []search.Result{
382
+ {
383
+ ID: id,
384
+ ClassName: "ActionClass",
385
+ Schema: map[string]interface{}{"foo": "bar"},
386
+ },
387
+ }
388
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything,
389
+ mock.Anything).Return(result, nil).Once()
390
+ extender.multi = []search.Result{
391
+ {
392
+ ID: id,
393
+ ClassName: "ActionClass",
394
+ Schema: map[string]interface{}{"foo": "bar"},
395
+ AdditionalProperties: models.AdditionalProperties{
396
+ "nearestNeighbors": &NearestNeighbors{
397
+ Neighbors: []*NearestNeighbor{
398
+ {
399
+ Concept: "foo",
400
+ Distance: 0.3,
401
+ },
402
+ },
403
+ },
404
+ },
405
+ },
406
+ }
407
+
408
+ expected := []*models.Object{
409
+ {
410
+ ID: id,
411
+ Class: "ActionClass",
412
+ Properties: map[string]interface{}{"foo": "bar"},
413
+ VectorWeights: (map[string]string)(nil),
414
+ Additional: models.AdditionalProperties{
415
+ "nearestNeighbors": &NearestNeighbors{
416
+ Neighbors: []*NearestNeighbor{
417
+ {
418
+ Concept: "foo",
419
+ Distance: 0.3,
420
+ },
421
+ },
422
+ },
423
+ },
424
+ },
425
+ }
426
+
427
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), nil, nil, nil, additional.Properties{
428
+ ModuleParams: map[string]interface{}{
429
+ "nearestNeighbors": true,
430
+ },
431
+ }, "")
432
+ require.Nil(t, err)
433
+ assert.Equal(t, expected, res)
434
+ })
435
+
436
+ t.Run("feature projection", func(t *testing.T) {
437
+ reset()
438
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
439
+
440
+ result := []search.Result{
441
+ {
442
+ ID: id,
443
+ ClassName: "ActionClass",
444
+ Schema: map[string]interface{}{"foo": "bar"},
445
+ },
446
+ }
447
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything,
448
+ mock.Anything).Return(result, nil).Once()
449
+ projectorFake.multi = []search.Result{
450
+ {
451
+ ID: id,
452
+ ClassName: "ActionClass",
453
+ Schema: map[string]interface{}{"foo": "bar"},
454
+ AdditionalProperties: models.AdditionalProperties{
455
+ "featureProjection": &FeatureProjection{
456
+ Vector: []float32{1, 2, 3},
457
+ },
458
+ },
459
+ },
460
+ }
461
+
462
+ expected := []*models.Object{
463
+ {
464
+ ID: id,
465
+ Class: "ActionClass",
466
+ Properties: map[string]interface{}{"foo": "bar"},
467
+ VectorWeights: (map[string]string)(nil),
468
+ Additional: models.AdditionalProperties{
469
+ "featureProjection": &FeatureProjection{
470
+ Vector: []float32{1, 2, 3},
471
+ },
472
+ },
473
+ },
474
+ }
475
+
476
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), nil, nil, nil, additional.Properties{
477
+ ModuleParams: map[string]interface{}{
478
+ "featureProjection": getDefaultParam("featureProjection"),
479
+ },
480
+ }, "")
481
+ require.Nil(t, err)
482
+ assert.Equal(t, expected, res)
483
+ })
484
+ })
485
+ })
486
+
487
+ t.Run("sort props", func(t *testing.T) {
488
+ t.Run("sort=foo,number&order=asc,desc", func(t *testing.T) {
489
+ reset()
490
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
491
+ sort := "foo,number"
492
+ asc := "asc,desc"
493
+ expectedSort := []filters.Sort{
494
+ {Path: []string{"foo"}, Order: "asc"},
495
+ {Path: []string{"number"}, Order: "desc"},
496
+ }
497
+
498
+ result := []search.Result{
499
+ {
500
+ ID: id,
501
+ ClassName: "ActionClass",
502
+ Schema: map[string]interface{}{
503
+ "foo": "bar",
504
+ "number": float64(1),
505
+ },
506
+ },
507
+ }
508
+ vectorRepo.On("ObjectSearch", mock.AnythingOfType("int"), mock.AnythingOfType("int"), expectedSort,
509
+ mock.Anything, mock.Anything, mock.Anything).Return(result, nil).Once()
510
+ projectorFake.multi = []search.Result{
511
+ {
512
+ ID: id,
513
+ ClassName: "ActionClass",
514
+ Schema: map[string]interface{}{
515
+ "foo": "bar",
516
+ "number": float64(1),
517
+ },
518
+ },
519
+ }
520
+
521
+ expected := []*models.Object{
522
+ {
523
+ ID: id,
524
+ Class: "ActionClass",
525
+ Properties: map[string]interface{}{
526
+ "foo": "bar",
527
+ "number": float64(1),
528
+ },
529
+ VectorWeights: (map[string]string)(nil),
530
+ },
531
+ }
532
+
533
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), &sort, &asc, nil, additional.Properties{}, "")
534
+ require.Nil(t, err)
535
+ assert.Equal(t, expected, res)
536
+ })
537
+
538
+ t.Run("sort=foo,number,prop1,prop2&order=desc", func(t *testing.T) {
539
+ reset()
540
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
541
+ sort := "foo,number,prop1,prop2"
542
+ asc := "desc"
543
+ expectedSort := []filters.Sort{
544
+ {Path: []string{"foo"}, Order: "desc"},
545
+ {Path: []string{"number"}, Order: "asc"},
546
+ {Path: []string{"prop1"}, Order: "asc"},
547
+ {Path: []string{"prop2"}, Order: "asc"},
548
+ }
549
+
550
+ result := []search.Result{
551
+ {
552
+ ID: id,
553
+ ClassName: "ActionClass",
554
+ Schema: map[string]interface{}{
555
+ "foo": "bar",
556
+ "number": float64(1),
557
+ },
558
+ },
559
+ }
560
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, expectedSort, mock.Anything, mock.Anything,
561
+ mock.Anything).Return(result, nil).Once()
562
+ projectorFake.multi = []search.Result{
563
+ {
564
+ ID: id,
565
+ ClassName: "ActionClass",
566
+ Schema: map[string]interface{}{
567
+ "foo": "bar",
568
+ "number": float64(1),
569
+ },
570
+ },
571
+ }
572
+
573
+ expected := []*models.Object{
574
+ {
575
+ ID: id,
576
+ Class: "ActionClass",
577
+ Properties: map[string]interface{}{
578
+ "foo": "bar",
579
+ "number": float64(1),
580
+ },
581
+ VectorWeights: (map[string]string)(nil),
582
+ },
583
+ }
584
+
585
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), &sort, &asc, nil, additional.Properties{}, "")
586
+ require.Nil(t, err)
587
+ assert.Equal(t, expected, res)
588
+ })
589
+
590
+ t.Run("sort=foo,number", func(t *testing.T) {
591
+ reset()
592
+ sort := "foo,number"
593
+ expectedSort := []filters.Sort{
594
+ {Path: []string{"foo"}, Order: "asc"},
595
+ {Path: []string{"number"}, Order: "asc"},
596
+ }
597
+ result := []search.Result{
598
+ {
599
+ ID: "uuid",
600
+ ClassName: "ActionClass",
601
+ Schema: map[string]interface{}{
602
+ "foo": "bar",
603
+ "number": float64(1),
604
+ },
605
+ },
606
+ }
607
+
608
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, expectedSort, mock.Anything, mock.Anything,
609
+ mock.Anything).Return(result, nil).Once()
610
+
611
+ _, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), &sort, nil, nil, additional.Properties{}, "")
612
+ require.Nil(t, err)
613
+ })
614
+
615
+ t.Run("sort=foo,number,prop", func(t *testing.T) {
616
+ reset()
617
+ sort := "foo,number,prop"
618
+ expectedSort := []filters.Sort{
619
+ {Path: []string{"foo"}, Order: "asc"},
620
+ {Path: []string{"number"}, Order: "asc"},
621
+ {Path: []string{"prop"}, Order: "asc"},
622
+ }
623
+ result := []search.Result{
624
+ {
625
+ ID: "uuid",
626
+ ClassName: "ActionClass",
627
+ Schema: map[string]interface{}{
628
+ "foo": "bar",
629
+ "number": float64(1),
630
+ },
631
+ },
632
+ }
633
+
634
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, expectedSort, mock.Anything, mock.Anything,
635
+ mock.Anything).Return(result, nil).Once()
636
+
637
+ _, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), &sort, nil, nil, additional.Properties{}, "")
638
+ require.Nil(t, err)
639
+ })
640
+
641
+ t.Run("order=asc", func(t *testing.T) {
642
+ reset()
643
+ order := "asc"
644
+ var expectedSort []filters.Sort
645
+ result := []search.Result{
646
+ {
647
+ ID: "uuid",
648
+ ClassName: "ActionClass",
649
+ Schema: map[string]interface{}{
650
+ "foo": "bar",
651
+ "number": float64(1),
652
+ },
653
+ },
654
+ }
655
+
656
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, expectedSort, mock.Anything, mock.Anything,
657
+ mock.Anything).Return(result, nil).Once()
658
+
659
+ _, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), nil, &order, nil, additional.Properties{}, "")
660
+ require.Nil(t, err)
661
+ })
662
+ })
663
+ }
664
+
665
+ func Test_GetThing(t *testing.T) {
666
+ var (
667
+ vectorRepo *fakeVectorRepo
668
+ manager *Manager
669
+ extender *fakeExtender
670
+ projectorFake *fakeProjector
671
+ )
672
+
673
+ schema := schema.Schema{
674
+ Objects: &models.Schema{
675
+ Classes: []*models.Class{
676
+ {
677
+ Class: "ThingClass",
678
+ },
679
+ },
680
+ },
681
+ }
682
+
683
+ reset := func() {
684
+ vectorRepo = &fakeVectorRepo{}
685
+ schemaManager := &fakeSchemaManager{
686
+ GetSchemaResponse: schema,
687
+ }
688
+ cfg := &config.WeaviateConfig{}
689
+ cfg.Config.QueryDefaults.Limit = 20
690
+ cfg.Config.QueryMaximumResults = 200
691
+ authorizer := mocks.NewMockAuthorizer()
692
+ logger, _ := test.NewNullLogger()
693
+ extender = &fakeExtender{}
694
+ projectorFake = &fakeProjector{}
695
+ metrics := &fakeMetrics{}
696
+ manager = NewManager(schemaManager, cfg, logger,
697
+ authorizer, vectorRepo,
698
+ getFakeModulesProviderWithCustomExtenders(extender, projectorFake), metrics, nil,
699
+ NewAutoSchemaManager(schemaManager, vectorRepo, cfg, authorizer, logger, prometheus.NewPedanticRegistry()))
700
+ }
701
+
702
+ t.Run("get non-existing thing by id", func(t *testing.T) {
703
+ reset()
704
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
705
+
706
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return((*search.Result)(nil), nil).Once()
707
+
708
+ _, err := manager.GetObject(context.Background(), &models.Principal{}, "", id,
709
+ additional.Properties{}, nil, "")
710
+ assert.Equal(t, NewErrNotFound("no object with id '99ee9968-22ec-416a-9032-cff80f2f7fdf'"), err)
711
+ })
712
+
713
+ t.Run("get existing thing by id", func(t *testing.T) {
714
+ reset()
715
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
716
+
717
+ result := &search.Result{
718
+ ID: id,
719
+ ClassName: "ThingClass",
720
+ Schema: map[string]interface{}{"foo": "bar"},
721
+ }
722
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
723
+
724
+ expected := &models.Object{
725
+ ID: id,
726
+ Class: "ThingClass",
727
+ Properties: map[string]interface{}{"foo": "bar"},
728
+ VectorWeights: (map[string]string)(nil),
729
+ }
730
+
731
+ res, err := manager.GetObject(context.Background(), &models.Principal{}, "", id,
732
+ additional.Properties{}, nil, "")
733
+ require.Nil(t, err)
734
+ assert.Equal(t, expected, res)
735
+ })
736
+
737
+ t.Run("list all existing things", func(t *testing.T) {
738
+ reset()
739
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
740
+
741
+ results := []search.Result{
742
+ {
743
+ ID: id,
744
+ ClassName: "ThingClass",
745
+ Schema: map[string]interface{}{"foo": "bar"},
746
+ },
747
+ }
748
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything,
749
+ mock.Anything).Return(results, nil).Once()
750
+
751
+ expected := []*models.Object{
752
+ {
753
+ ID: id,
754
+ Class: "ThingClass",
755
+ Properties: map[string]interface{}{"foo": "bar"},
756
+ VectorWeights: (map[string]string)(nil),
757
+ },
758
+ }
759
+
760
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, nil, nil, nil, nil, additional.Properties{}, "")
761
+ require.Nil(t, err)
762
+ assert.Equal(t, expected, res)
763
+ })
764
+
765
+ t.Run("additional props", func(t *testing.T) {
766
+ t.Run("on get single requests", func(t *testing.T) {
767
+ t.Run("feature projection", func(t *testing.T) {
768
+ reset()
769
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
770
+
771
+ result := &search.Result{
772
+ ID: id,
773
+ ClassName: "ThingClass",
774
+ Schema: map[string]interface{}{"foo": "bar"},
775
+ }
776
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
777
+ _, err := manager.GetObject(context.Background(), &models.Principal{}, "",
778
+ id, additional.Properties{
779
+ ModuleParams: map[string]interface{}{
780
+ "featureProjection": getDefaultParam("featureProjection"),
781
+ },
782
+ }, nil, "")
783
+ assert.Equal(t, errors.New("get extend: unknown capability: featureProjection").Error(), err.Error())
784
+ })
785
+
786
+ t.Run("nearest neighbors", func(t *testing.T) {
787
+ reset()
788
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
789
+
790
+ result := &search.Result{
791
+ ID: id,
792
+ ClassName: "ThingClass",
793
+ Schema: map[string]interface{}{"foo": "bar"},
794
+ }
795
+ vectorRepo.On("ObjectByID", id, mock.Anything, mock.Anything).Return(result, nil).Once()
796
+ extender.multi = []search.Result{
797
+ {
798
+ ID: id,
799
+ ClassName: "ThingClass",
800
+ Schema: map[string]interface{}{"foo": "bar"},
801
+ AdditionalProperties: models.AdditionalProperties{
802
+ "nearestNeighbors": &NearestNeighbors{
803
+ Neighbors: []*NearestNeighbor{
804
+ {
805
+ Concept: "foo",
806
+ Distance: 0.3,
807
+ },
808
+ },
809
+ },
810
+ },
811
+ },
812
+ }
813
+
814
+ expected := &models.Object{
815
+ ID: id,
816
+ Class: "ThingClass",
817
+ Properties: map[string]interface{}{"foo": "bar"},
818
+ VectorWeights: (map[string]string)(nil),
819
+ Additional: models.AdditionalProperties{
820
+ "nearestNeighbors": &NearestNeighbors{
821
+ Neighbors: []*NearestNeighbor{
822
+ {
823
+ Concept: "foo",
824
+ Distance: 0.3,
825
+ },
826
+ },
827
+ },
828
+ },
829
+ }
830
+
831
+ res, err := manager.GetObject(context.Background(), &models.Principal{}, "",
832
+ id, additional.Properties{
833
+ ModuleParams: map[string]interface{}{
834
+ "nearestNeighbors": true,
835
+ },
836
+ }, nil, "")
837
+ require.Nil(t, err)
838
+ assert.Equal(t, expected, res)
839
+ })
840
+ })
841
+
842
+ t.Run("on list requests", func(t *testing.T) {
843
+ t.Run("nearest neighbors", func(t *testing.T) {
844
+ reset()
845
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
846
+
847
+ result := []search.Result{
848
+ {
849
+ ID: id,
850
+ ClassName: "ThingClass",
851
+ Schema: map[string]interface{}{"foo": "bar"},
852
+ },
853
+ }
854
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything,
855
+ mock.Anything).Return(result, nil).Once()
856
+ extender.multi = []search.Result{
857
+ {
858
+ ID: id,
859
+ ClassName: "ThingClass",
860
+ Schema: map[string]interface{}{"foo": "bar"},
861
+ AdditionalProperties: models.AdditionalProperties{
862
+ "nearestNeighbors": &NearestNeighbors{
863
+ Neighbors: []*NearestNeighbor{
864
+ {
865
+ Concept: "foo",
866
+ Distance: 0.3,
867
+ },
868
+ },
869
+ },
870
+ },
871
+ },
872
+ }
873
+
874
+ expected := []*models.Object{
875
+ {
876
+ ID: id,
877
+ Class: "ThingClass",
878
+ Properties: map[string]interface{}{"foo": "bar"},
879
+ VectorWeights: (map[string]string)(nil),
880
+ Additional: models.AdditionalProperties{
881
+ "nearestNeighbors": &NearestNeighbors{
882
+ Neighbors: []*NearestNeighbor{
883
+ {
884
+ Concept: "foo",
885
+ Distance: 0.3,
886
+ },
887
+ },
888
+ },
889
+ },
890
+ },
891
+ }
892
+
893
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), nil, nil, nil, additional.Properties{
894
+ ModuleParams: map[string]interface{}{
895
+ "nearestNeighbors": true,
896
+ },
897
+ }, "")
898
+ require.Nil(t, err)
899
+ assert.Equal(t, expected, res)
900
+ })
901
+
902
+ t.Run("feature projection", func(t *testing.T) {
903
+ reset()
904
+ id := strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
905
+
906
+ result := []search.Result{
907
+ {
908
+ ID: id,
909
+ ClassName: "ThingClass",
910
+ Schema: map[string]interface{}{"foo": "bar"},
911
+ },
912
+ }
913
+ vectorRepo.On("ObjectSearch", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything,
914
+ mock.Anything).Return(result, nil).Once()
915
+ projectorFake.multi = []search.Result{
916
+ {
917
+ ID: id,
918
+ ClassName: "ThingClass",
919
+ Schema: map[string]interface{}{"foo": "bar"},
920
+ AdditionalProperties: models.AdditionalProperties{
921
+ "featureProjection": &FeatureProjection{
922
+ Vector: []float32{1, 2, 3},
923
+ },
924
+ },
925
+ },
926
+ }
927
+
928
+ expected := []*models.Object{
929
+ {
930
+ ID: id,
931
+ Class: "ThingClass",
932
+ Properties: map[string]interface{}{"foo": "bar"},
933
+ VectorWeights: (map[string]string)(nil),
934
+ Additional: models.AdditionalProperties{
935
+ "featureProjection": &FeatureProjection{
936
+ Vector: []float32{1, 2, 3},
937
+ },
938
+ },
939
+ },
940
+ }
941
+
942
+ res, err := manager.GetObjects(context.Background(), &models.Principal{}, nil, ptInt64(10), nil, nil, nil, additional.Properties{
943
+ ModuleParams: map[string]interface{}{
944
+ "featureProjection": getDefaultParam("featureProjection"),
945
+ },
946
+ }, "")
947
+ require.Nil(t, err)
948
+ assert.Equal(t, expected, res)
949
+ })
950
+ })
951
+ })
952
+ }
953
+
954
+ func Test_GetObject(t *testing.T) {
955
+ var (
956
+ principal = models.Principal{}
957
+ adds = additional.Properties{}
958
+ className = "MyClass"
959
+ id = strfmt.UUID("99ee9968-22ec-416a-9032-cff80f2f7fdf")
960
+ schema = schema.Schema{
961
+ Objects: &models.Schema{
962
+ Classes: []*models.Class{
963
+ {
964
+ Class: className,
965
+ },
966
+ },
967
+ },
968
+ }
969
+ result = &search.Result{
970
+ ID: id,
971
+ ClassName: className,
972
+ Schema: map[string]interface{}{"foo": "bar"},
973
+ }
974
+ )
975
+
976
+ t.Run("without projection", func(t *testing.T) {
977
+ m := newFakeGetManager(schema)
978
+ m.repo.On("Object", className, id, mock.Anything, mock.Anything, "").Return((*search.Result)(nil), nil).Once()
979
+ _, err := m.GetObject(context.Background(), &principal, className, id, adds, nil, "")
980
+ if err == nil {
981
+ t.Errorf("GetObject() must return an error for non existing object")
982
+ }
983
+
984
+ m.repo.On("Object", className, id, mock.Anything, mock.Anything, "").Return(result, nil).Once()
985
+ expected := &models.Object{
986
+ ID: id,
987
+ Class: className,
988
+ Properties: map[string]interface{}{"foo": "bar"},
989
+ VectorWeights: (map[string]string)(nil),
990
+ }
991
+
992
+ got, err := m.GetObject(context.Background(), &principal, className, id, adds, nil, "")
993
+ require.Nil(t, err)
994
+ assert.Equal(t, expected, got)
995
+ })
996
+
997
+ t.Run("with projection", func(t *testing.T) {
998
+ m := newFakeGetManager(schema)
999
+ m.extender.multi = []search.Result{
1000
+ {
1001
+ ID: id,
1002
+ ClassName: className,
1003
+ Schema: map[string]interface{}{"foo": "bar"},
1004
+ AdditionalProperties: models.AdditionalProperties{
1005
+ "nearestNeighbors": &NearestNeighbors{
1006
+ Neighbors: []*NearestNeighbor{
1007
+ {
1008
+ Concept: "foo",
1009
+ Distance: 0.3,
1010
+ },
1011
+ },
1012
+ },
1013
+ },
1014
+ },
1015
+ }
1016
+ m.repo.On("Object", className, id, mock.Anything, mock.Anything, "").Return(result, nil).Once()
1017
+ _, err := m.GetObject(context.Background(), &principal, className, id,
1018
+ additional.Properties{
1019
+ ModuleParams: map[string]interface{}{
1020
+ "Unknown": getDefaultParam("Unknown"),
1021
+ },
1022
+ }, nil, "")
1023
+ if err == nil {
1024
+ t.Errorf("GetObject() must return unknown feature projection error")
1025
+ }
1026
+
1027
+ m.repo.On("Object", className, id, mock.Anything, mock.Anything, "").Return(result, nil).Once()
1028
+ expected := &models.Object{
1029
+ ID: id,
1030
+ Class: className,
1031
+ Properties: map[string]interface{}{"foo": "bar"},
1032
+ VectorWeights: (map[string]string)(nil),
1033
+ Additional: models.AdditionalProperties{
1034
+ "nearestNeighbors": &NearestNeighbors{
1035
+ Neighbors: []*NearestNeighbor{
1036
+ {
1037
+ Concept: "foo",
1038
+ Distance: 0.3,
1039
+ },
1040
+ },
1041
+ },
1042
+ },
1043
+ }
1044
+
1045
+ res, err := m.GetObject(context.Background(), &principal, className, id,
1046
+ additional.Properties{
1047
+ ModuleParams: map[string]interface{}{
1048
+ "nearestNeighbors": true,
1049
+ },
1050
+ }, nil, "")
1051
+ require.Nil(t, err)
1052
+ assert.Equal(t, expected, res)
1053
+ })
1054
+ }
1055
+
1056
+ func ptInt64(in int64) *int64 {
1057
+ return &in
1058
+ }
1059
+
1060
+ type fakeGetManager struct {
1061
+ *Manager
1062
+ repo *fakeVectorRepo
1063
+ extender *fakeExtender
1064
+ projector *fakeProjector
1065
+ authorizer *mocks.FakeAuthorizer
1066
+ metrics *fakeMetrics
1067
+ modulesProvider *fakeModulesProvider
1068
+ }
1069
+
1070
+ func newFakeGetManager(schema schema.Schema, opts ...func(*fakeGetManager)) fakeGetManager {
1071
+ r := fakeGetManager{
1072
+ repo: new(fakeVectorRepo),
1073
+ extender: new(fakeExtender),
1074
+ projector: new(fakeProjector),
1075
+ authorizer: mocks.NewMockAuthorizer(),
1076
+ metrics: new(fakeMetrics),
1077
+ modulesProvider: new(fakeModulesProvider),
1078
+ }
1079
+
1080
+ for _, opt := range opts {
1081
+ opt(&r)
1082
+ }
1083
+
1084
+ schemaManager := &fakeSchemaManager{
1085
+ GetSchemaResponse: schema,
1086
+ }
1087
+
1088
+ cfg := &config.WeaviateConfig{}
1089
+ cfg.Config.QueryDefaults.Limit = 20
1090
+ cfg.Config.QueryMaximumResults = 200
1091
+ cfg.Config.TrackVectorDimensions = true
1092
+ logger, _ := test.NewNullLogger()
1093
+ r.modulesProvider = getFakeModulesProviderWithCustomExtenders(r.extender, r.projector)
1094
+ r.Manager = NewManager(schemaManager, cfg, logger,
1095
+ r.authorizer, r.repo, r.modulesProvider, r.metrics, nil,
1096
+ NewAutoSchemaManager(schemaManager, r.repo, cfg, r.authorizer, logger, prometheus.NewPedanticRegistry()))
1097
+
1098
+ return r
1099
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/head.go ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+
18
+ "github.com/go-openapi/strfmt"
19
+
20
+ "github.com/weaviate/weaviate/entities/additional"
21
+ "github.com/weaviate/weaviate/entities/models"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
23
+ )
24
+
25
+ // HeadObject check object's existence in the connected DB
26
+ func (m *Manager) HeadObject(ctx context.Context, principal *models.Principal, className string,
27
+ id strfmt.UUID, repl *additional.ReplicationProperties, tenant string,
28
+ ) (bool, *Error) {
29
+ className, _ = m.resolveAlias(className)
30
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Objects(className, tenant, id)); err != nil {
31
+ return false, &Error{err.Error(), StatusForbidden, err}
32
+ }
33
+
34
+ m.metrics.HeadObjectInc()
35
+ defer m.metrics.HeadObjectDec()
36
+
37
+ if cls := m.schemaManager.ResolveAlias(className); cls != "" {
38
+ className = cls
39
+ }
40
+
41
+ ok, err := m.vectorRepo.Exists(ctx, className, id, repl, tenant)
42
+ if err != nil {
43
+ switch {
44
+ case errors.As(err, &ErrMultiTenancy{}):
45
+ return false, &Error{"repo.exists", StatusUnprocessableEntity, err}
46
+ default:
47
+ if (errors.As(err, &ErrDirtyReadOfDeletedObject{})) {
48
+ return false, nil
49
+ }
50
+ return false, &Error{"repo.exists", StatusInternalServerError, err}
51
+ }
52
+ }
53
+ return ok, nil
54
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/head_test.go ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "testing"
17
+
18
+ "github.com/go-openapi/strfmt"
19
+ "github.com/pkg/errors"
20
+ "github.com/weaviate/weaviate/entities/schema"
21
+ )
22
+
23
+ func Test_HeadObject(t *testing.T) {
24
+ t.Parallel()
25
+ var (
26
+ cls = "MyClass"
27
+ id = strfmt.UUID("5a1cd361-1e0d-42ae-bd52-ee09cb5f31cc")
28
+ m = newFakeGetManager(schema.Schema{})
29
+ errAny = errors.New("any")
30
+ )
31
+
32
+ tests := []struct {
33
+ class string
34
+ mockedOk bool
35
+ mockedErr error
36
+ authErr error
37
+ wantOK bool
38
+ wantCode int
39
+ }{
40
+ {
41
+ mockedOk: true,
42
+ wantOK: true,
43
+ },
44
+ {
45
+ class: cls,
46
+ mockedOk: true,
47
+ wantOK: true,
48
+ },
49
+ {
50
+ class: cls,
51
+ mockedOk: false,
52
+ wantOK: false,
53
+ },
54
+ {
55
+ class: cls,
56
+ mockedOk: false,
57
+ mockedErr: errAny,
58
+ wantOK: false,
59
+ wantCode: StatusInternalServerError,
60
+ },
61
+ {
62
+ class: cls,
63
+ authErr: errAny,
64
+ wantOK: false,
65
+ wantCode: StatusForbidden,
66
+ },
67
+ }
68
+ for i, tc := range tests {
69
+ m.authorizer.SetErr(tc.authErr)
70
+ if tc.authErr == nil {
71
+ m.repo.On("Exists", tc.class, id).Return(tc.mockedOk, tc.mockedErr).Once()
72
+ }
73
+ ok, err := m.Manager.HeadObject(context.Background(), nil, tc.class, id, nil, "")
74
+ code := 0
75
+ if err != nil {
76
+ code = err.Code
77
+ }
78
+ if tc.wantOK != ok || tc.wantCode != code {
79
+ t.Errorf("case %d expected:(%v, %v) got:(%v, %v)", i+1, tc.wantOK, tc.wantCode, ok, code)
80
+ }
81
+ }
82
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/manager.go ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ // package objects provides managers for all kind-related items, such as objects.
13
+ // Manager provides methods for "regular" interaction, such as
14
+ // add, get, delete, update, etc. Additionally BatchManager allows for
15
+ // efficient batch-adding of object instances and references.
16
+ package objects
17
+
18
+ import (
19
+ "context"
20
+ "fmt"
21
+ "time"
22
+
23
+ "github.com/go-openapi/strfmt"
24
+ "github.com/google/uuid"
25
+ "github.com/sirupsen/logrus"
26
+
27
+ "github.com/weaviate/weaviate/entities/additional"
28
+ "github.com/weaviate/weaviate/entities/filters"
29
+ "github.com/weaviate/weaviate/entities/models"
30
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
31
+ "github.com/weaviate/weaviate/entities/schema"
32
+ "github.com/weaviate/weaviate/entities/schema/crossref"
33
+ "github.com/weaviate/weaviate/entities/search"
34
+ "github.com/weaviate/weaviate/entities/versioned"
35
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
36
+ "github.com/weaviate/weaviate/usecases/config"
37
+ "github.com/weaviate/weaviate/usecases/memwatch"
38
+ "github.com/weaviate/weaviate/usecases/objects/alias"
39
+ )
40
+
41
+ type schemaManager interface {
42
+ AddClass(ctx context.Context, principal *models.Principal, class *models.Class) (*models.Class, uint64, error)
43
+ AddTenants(ctx context.Context, principal *models.Principal, class string, tenants []*models.Tenant) (uint64, error)
44
+ GetClass(ctx context.Context, principal *models.Principal, name string) (*models.Class, error)
45
+ // ReadOnlyClass return class model.
46
+ ReadOnlyClass(name string) *models.Class
47
+ // AddClassProperty it is upsert operation. it adds properties to a class and updates
48
+ // existing properties if the merge bool passed true.
49
+ AddClassProperty(ctx context.Context, principal *models.Principal, class *models.Class, className string, merge bool, prop ...*models.Property) (*models.Class, uint64, error)
50
+
51
+ // Consistent methods with the consistency flag.
52
+ // This is used to ensure that internal users will not miss-use the flag and it doesn't need to be set to a default
53
+ // value everytime we use the Manager.
54
+
55
+ // GetConsistentClass overrides the default implementation to consider the consistency flag
56
+ GetConsistentClass(ctx context.Context, principal *models.Principal,
57
+ name string, consistency bool,
58
+ ) (*models.Class, uint64, error)
59
+
60
+ // GetCachedClass extracts class from context. If class was not set it is fetched first
61
+ GetCachedClass(ctx context.Context, principal *models.Principal, names ...string,
62
+ ) (map[string]versioned.Class, error)
63
+
64
+ GetCachedClassNoAuth(ctx context.Context, names ...string) (map[string]versioned.Class, error)
65
+
66
+ // WaitForUpdate ensures that the local schema has caught up to schemaVersion
67
+ WaitForUpdate(ctx context.Context, schemaVersion uint64) error
68
+
69
+ // GetConsistentSchema retrieves a locally cached copy of the schema
70
+ GetConsistentSchema(ctx context.Context, principal *models.Principal, consistency bool) (schema.Schema, error)
71
+
72
+ // ResolveAlias returns a class name associated with a given alias, empty string if doesn't exist
73
+ ResolveAlias(alias string) string
74
+ }
75
+
76
+ // Manager manages kind changes at a use-case level, i.e. agnostic of
77
+ // underlying databases or storage providers
78
+ type Manager struct {
79
+ config *config.WeaviateConfig
80
+ schemaManager schemaManager
81
+ logger logrus.FieldLogger
82
+ authorizer authorization.Authorizer
83
+ vectorRepo VectorRepo
84
+ timeSource timeSource
85
+ modulesProvider ModulesProvider
86
+ autoSchemaManager *AutoSchemaManager
87
+ metrics objectsMetrics
88
+ allocChecker *memwatch.Monitor
89
+ }
90
+
91
+ type objectsMetrics interface {
92
+ BatchInc()
93
+ BatchDec()
94
+ BatchRefInc()
95
+ BatchRefDec()
96
+ BatchDeleteInc()
97
+ BatchDeleteDec()
98
+ AddObjectInc()
99
+ AddObjectDec()
100
+ UpdateObjectInc()
101
+ UpdateObjectDec()
102
+ MergeObjectInc()
103
+ MergeObjectDec()
104
+ DeleteObjectInc()
105
+ DeleteObjectDec()
106
+ GetObjectInc()
107
+ GetObjectDec()
108
+ HeadObjectInc()
109
+ HeadObjectDec()
110
+ AddReferenceInc()
111
+ AddReferenceDec()
112
+ UpdateReferenceInc()
113
+ UpdateReferenceDec()
114
+ DeleteReferenceInc()
115
+ DeleteReferenceDec()
116
+ AddUsageDimensions(className, queryType, operation string, dims int)
117
+ }
118
+
119
+ type timeSource interface {
120
+ Now() int64
121
+ }
122
+
123
+ type VectorRepo interface {
124
+ PutObject(ctx context.Context, concept *models.Object, vector []float32,
125
+ vectors map[string][]float32, multiVectors map[string][][]float32,
126
+ repl *additional.ReplicationProperties, schemaVersion uint64) error
127
+ DeleteObject(ctx context.Context, className string, id strfmt.UUID, deletionTime time.Time,
128
+ repl *additional.ReplicationProperties, tenant string, schemaVersion uint64) error
129
+ // Object returns object of the specified class giving by its id
130
+ Object(ctx context.Context, class string, id strfmt.UUID, props search.SelectProperties,
131
+ additional additional.Properties, repl *additional.ReplicationProperties,
132
+ tenant string) (*search.Result, error)
133
+ // Exists returns true if an object of a giving class exists
134
+ Exists(ctx context.Context, class string, id strfmt.UUID,
135
+ repl *additional.ReplicationProperties, tenant string) (bool, error)
136
+ ObjectByID(ctx context.Context, id strfmt.UUID, props search.SelectProperties,
137
+ additional additional.Properties, tenant string) (*search.Result, error)
138
+ ObjectSearch(ctx context.Context, offset, limit int, filters *filters.LocalFilter,
139
+ sort []filters.Sort, additional additional.Properties, tenant string) (search.Results, error)
140
+ AddReference(ctx context.Context, source *crossref.RefSource,
141
+ target *crossref.Ref, repl *additional.ReplicationProperties, tenant string, schemaVersion uint64) error
142
+ Merge(ctx context.Context, merge MergeDocument, repl *additional.ReplicationProperties, tenant string, schemaVersion uint64) error
143
+ Query(context.Context, *QueryInput) (search.Results, *Error)
144
+ }
145
+
146
+ type ModulesProvider interface {
147
+ GetObjectAdditionalExtend(ctx context.Context, in *search.Result,
148
+ moduleParams map[string]interface{}) (*search.Result, error)
149
+ ListObjectsAdditionalExtend(ctx context.Context, in search.Results,
150
+ moduleParams map[string]interface{}) (search.Results, error)
151
+ UsingRef2Vec(className string) bool
152
+ UpdateVector(ctx context.Context, object *models.Object, class *models.Class, repo modulecapabilities.FindObjectFn,
153
+ logger logrus.FieldLogger) error
154
+ BatchUpdateVector(ctx context.Context, class *models.Class, objects []*models.Object,
155
+ findObjectFn modulecapabilities.FindObjectFn,
156
+ logger logrus.FieldLogger) (map[int]error, error)
157
+ VectorizerName(className string) (string, error)
158
+ }
159
+
160
+ // NewManager creates a new manager
161
+ func NewManager(schemaManager schemaManager,
162
+ config *config.WeaviateConfig, logger logrus.FieldLogger,
163
+ authorizer authorization.Authorizer, vectorRepo VectorRepo,
164
+ modulesProvider ModulesProvider, metrics objectsMetrics, allocChecker *memwatch.Monitor,
165
+ autoSchemaManager *AutoSchemaManager,
166
+ ) *Manager {
167
+ if allocChecker == nil {
168
+ allocChecker = memwatch.NewDummyMonitor()
169
+ }
170
+
171
+ return &Manager{
172
+ config: config,
173
+ schemaManager: schemaManager,
174
+ logger: logger,
175
+ authorizer: authorizer,
176
+ vectorRepo: vectorRepo,
177
+ timeSource: defaultTimeSource{},
178
+ modulesProvider: modulesProvider,
179
+ autoSchemaManager: autoSchemaManager,
180
+ metrics: metrics,
181
+ allocChecker: allocChecker,
182
+ }
183
+ }
184
+
185
+ // Alias
186
+ func (m *Manager) resolveAlias(class string) (className, aliasName string) {
187
+ return alias.ResolveAlias(m.schemaManager, class)
188
+ }
189
+
190
+ func generateUUID() (strfmt.UUID, error) {
191
+ id, err := uuid.NewRandom()
192
+ if err != nil {
193
+ return "", fmt.Errorf("could not generate uuid v4: %w", err)
194
+ }
195
+
196
+ return strfmt.UUID(id.String()), nil
197
+ }
198
+
199
+ type defaultTimeSource struct{}
200
+
201
+ func (ts defaultTimeSource) Now() int64 {
202
+ return time.Now().UnixNano() / int64(time.Millisecond)
203
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/merge.go ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+
19
+ "github.com/weaviate/weaviate/entities/versioned"
20
+
21
+ "github.com/weaviate/weaviate/entities/classcache"
22
+
23
+ "github.com/go-openapi/strfmt"
24
+
25
+ "github.com/weaviate/weaviate/entities/additional"
26
+ "github.com/weaviate/weaviate/entities/models"
27
+ "github.com/weaviate/weaviate/entities/schema"
28
+ "github.com/weaviate/weaviate/entities/schema/crossref"
29
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
30
+ authzerrs "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
31
+ "github.com/weaviate/weaviate/usecases/config"
32
+ "github.com/weaviate/weaviate/usecases/memwatch"
33
+ )
34
+
35
+ type MergeDocument struct {
36
+ Class string `json:"class"`
37
+ ID strfmt.UUID `json:"id"`
38
+ PrimitiveSchema map[string]interface{} `json:"primitiveSchema"`
39
+ References BatchReferences `json:"references"`
40
+ Vector []float32 `json:"vector"`
41
+ Vectors models.Vectors `json:"vectors"`
42
+ UpdateTime int64 `json:"updateTime"`
43
+ AdditionalProperties models.AdditionalProperties `json:"additionalProperties"`
44
+ PropertiesToDelete []string `json:"propertiesToDelete"`
45
+ }
46
+
47
+ func (m *Manager) MergeObject(ctx context.Context, principal *models.Principal,
48
+ updates *models.Object, repl *additional.ReplicationProperties,
49
+ ) *Error {
50
+ if err := m.validateInputs(updates); err != nil {
51
+ return &Error{"bad request", StatusBadRequest, err}
52
+ }
53
+ className, aliasName := m.resolveAlias(schema.UppercaseClassName(updates.Class))
54
+ updates.Class = className
55
+ cls, id := updates.Class, updates.ID
56
+ if err := m.authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.Objects(cls, updates.Tenant, id)); err != nil {
57
+ return &Error{err.Error(), StatusForbidden, err}
58
+ }
59
+
60
+ ctx = classcache.ContextWithClassCache(ctx)
61
+
62
+ // we don't reveal any info that the end users cannot get through the structure of the data anyway
63
+ fetchedClass, err := m.schemaManager.GetCachedClassNoAuth(ctx, className)
64
+ if err != nil {
65
+ if errors.As(err, &authzerrs.Forbidden{}) {
66
+ return &Error{err.Error(), StatusForbidden, err}
67
+ }
68
+
69
+ return &Error{err.Error(), StatusBadRequest, NewErrInvalidUserInput("invalid object: %v", err)}
70
+ }
71
+
72
+ m.metrics.MergeObjectInc()
73
+ defer m.metrics.MergeObjectDec()
74
+
75
+ if err := m.allocChecker.CheckAlloc(memwatch.EstimateObjectMemory(updates)); err != nil {
76
+ m.logger.WithError(err).Errorf("memory pressure: cannot process patch object")
77
+ return &Error{err.Error(), StatusInternalServerError, err}
78
+ }
79
+
80
+ obj, err := m.vectorRepo.Object(ctx, cls, id, nil, additional.Properties{}, repl, updates.Tenant)
81
+ if err != nil {
82
+ switch {
83
+ case errors.As(err, &ErrMultiTenancy{}):
84
+ return &Error{"repo.object", StatusUnprocessableEntity, err}
85
+ default:
86
+ if errors.As(err, &ErrDirtyReadOfDeletedObject{}) || errors.As(err, &ErrDirtyWriteOfDeletedObject{}) {
87
+ m.logger.WithError(err).Debugf("object %s/%s not found, possibly due to replication consistency races", cls, id)
88
+ return &Error{"not found", StatusNotFound, err}
89
+ }
90
+ if errors.As(err, &authzerrs.Forbidden{}) {
91
+ return &Error{"forbidden", StatusForbidden, err}
92
+ }
93
+ return &Error{"repo.object", StatusInternalServerError, err}
94
+ }
95
+ }
96
+ if obj == nil {
97
+ return &Error{"not found", StatusNotFound, err}
98
+ }
99
+
100
+ maxSchemaVersion, err := m.autoSchemaManager.autoSchema(ctx, principal, false, fetchedClass, updates)
101
+ if err != nil {
102
+ return &Error{"bad request", StatusBadRequest, NewErrInvalidUserInput("invalid object: %v", err)}
103
+ }
104
+
105
+ var propertiesToDelete []string
106
+ if updates.Properties != nil {
107
+ for key, val := range updates.Properties.(map[string]interface{}) {
108
+ if val == nil {
109
+ propertiesToDelete = append(propertiesToDelete, schema.LowercaseFirstLetter(key))
110
+ }
111
+ }
112
+ }
113
+
114
+ prevObj := obj.Object()
115
+ if err := m.validateObjectAndNormalizeNames(ctx, repl, updates, prevObj, fetchedClass); err != nil {
116
+ return &Error{"bad request", StatusBadRequest, err}
117
+ }
118
+
119
+ if updates.Properties == nil {
120
+ updates.Properties = map[string]interface{}{}
121
+ }
122
+
123
+ pathErr := m.patchObject(ctx, prevObj, updates, repl, propertiesToDelete, updates.Tenant, fetchedClass, maxSchemaVersion)
124
+ if aliasName != "" {
125
+ updates.Class = aliasName
126
+ }
127
+ return pathErr
128
+ }
129
+
130
+ // patchObject patches an existing object obj with updates
131
+ func (m *Manager) patchObject(ctx context.Context, prevObj, updates *models.Object, repl *additional.ReplicationProperties,
132
+ propertiesToDelete []string, tenant string, fetchedClass map[string]versioned.Class, maxSchemaVersion uint64,
133
+ ) *Error {
134
+ cls, id := updates.Class, updates.ID
135
+ class := fetchedClass[cls].Class
136
+ primitive, refs := m.splitPrimitiveAndRefs(updates.Properties.(map[string]interface{}), cls, id)
137
+ objWithVec, err := m.mergeObjectSchemaAndVectorize(ctx, prevObj.Properties,
138
+ primitive, prevObj.Vector, updates.Vector, prevObj.Vectors, updates.Vectors, updates.ID, class)
139
+ if err != nil {
140
+ return &Error{"merge and vectorize", StatusInternalServerError, err}
141
+ }
142
+ mergeDoc := MergeDocument{
143
+ Class: cls,
144
+ ID: id,
145
+ PrimitiveSchema: primitive,
146
+ References: refs,
147
+ Vector: objWithVec.Vector,
148
+ Vectors: objWithVec.Vectors,
149
+ UpdateTime: m.timeSource.Now(),
150
+ PropertiesToDelete: propertiesToDelete,
151
+ }
152
+
153
+ if objWithVec.Additional != nil {
154
+ mergeDoc.AdditionalProperties = objWithVec.Additional
155
+ }
156
+
157
+ // Ensure that the local schema has caught up to the version we used to validate
158
+ if err := m.schemaManager.WaitForUpdate(ctx, maxSchemaVersion); err != nil {
159
+ return &Error{
160
+ Msg: fmt.Sprintf("error waiting for local schema to catch up to version %d", maxSchemaVersion),
161
+ Code: StatusInternalServerError,
162
+ Err: err,
163
+ }
164
+ }
165
+
166
+ if err := m.vectorRepo.Merge(ctx, mergeDoc, repl, tenant, maxSchemaVersion); err != nil {
167
+ if errors.As(err, &ErrDirtyReadOfDeletedObject{}) || errors.As(err, &ErrDirtyWriteOfDeletedObject{}) {
168
+ m.logger.WithError(err).Debugf("object %s/%s not found, possibly due to replication consistency races", cls, id)
169
+ return &Error{"not found", StatusNotFound, err}
170
+ }
171
+ return &Error{"repo.merge", StatusInternalServerError, err}
172
+ }
173
+
174
+ return nil
175
+ }
176
+
177
+ func (m *Manager) validateInputs(updates *models.Object) error {
178
+ if updates == nil {
179
+ return fmt.Errorf("empty updates")
180
+ }
181
+ if updates.Class == "" {
182
+ return fmt.Errorf("empty class")
183
+ }
184
+ if updates.ID == "" {
185
+ return fmt.Errorf("empty uuid")
186
+ }
187
+ return nil
188
+ }
189
+
190
+ func (m *Manager) mergeObjectSchemaAndVectorize(ctx context.Context, prevPropsSch models.PropertySchema,
191
+ nextProps map[string]interface{}, prevVec, nextVec []float32, prevVecs models.Vectors, nextVecs models.Vectors,
192
+ id strfmt.UUID, class *models.Class,
193
+ ) (*models.Object, error) {
194
+ var mergedProps map[string]interface{}
195
+
196
+ vector := nextVec
197
+ vectors := nextVecs
198
+ if prevPropsSch == nil {
199
+ mergedProps = nextProps
200
+ } else {
201
+ prevProps, ok := prevPropsSch.(map[string]interface{})
202
+ if !ok {
203
+ return nil, fmt.Errorf("expected previous schema to be map, but got %#v", prevPropsSch)
204
+ }
205
+
206
+ mergedProps = map[string]interface{}{}
207
+ for propName, propValue := range prevProps {
208
+ mergedProps[propName] = propValue
209
+ }
210
+ for propName, propValue := range nextProps {
211
+ mergedProps[propName] = propValue
212
+ }
213
+ }
214
+
215
+ // Note: vector could be a nil vector in case a vectorizer is configured,
216
+ // then the vectorizer will set it
217
+ obj := &models.Object{Class: class.Class, Properties: mergedProps, Vector: vector, Vectors: vectors, ID: id}
218
+ if err := m.modulesProvider.UpdateVector(ctx, obj, class, m.findObject, m.logger); err != nil {
219
+ return nil, err
220
+ }
221
+
222
+ // If there is no vectorization module and no updated vector, use the previous vector(s)
223
+ if obj.Vector == nil && class.Vectorizer == config.VectorizerModuleNone {
224
+ obj.Vector = prevVec
225
+ }
226
+
227
+ if obj.Vectors == nil {
228
+ obj.Vectors = models.Vectors{}
229
+ }
230
+
231
+ // check for each named vector if the previous vector should be used. This should only happen if
232
+ // - the vectorizer is none
233
+ // - the vector is not set in the update
234
+ // - the vector was set in the previous object
235
+ for name, vectorConfig := range class.VectorConfig {
236
+ if _, ok := vectorConfig.Vectorizer.(map[string]interface{})[config.VectorizerModuleNone]; !ok {
237
+ continue
238
+ }
239
+
240
+ prevTargetVector, ok := prevVecs[name]
241
+ if !ok {
242
+ continue
243
+ }
244
+
245
+ if _, ok := obj.Vectors[name]; !ok {
246
+ obj.Vectors[name] = prevTargetVector
247
+ }
248
+ }
249
+
250
+ return obj, nil
251
+ }
252
+
253
+ func (m *Manager) splitPrimitiveAndRefs(in map[string]interface{}, sourceClass string,
254
+ sourceID strfmt.UUID,
255
+ ) (map[string]interface{}, BatchReferences) {
256
+ primitive := map[string]interface{}{}
257
+ var outRefs BatchReferences
258
+
259
+ for prop, value := range in {
260
+ refs, ok := value.(models.MultipleRef)
261
+
262
+ if !ok {
263
+ // this must be a primitive filed
264
+ primitive[prop] = value
265
+ continue
266
+ }
267
+
268
+ for _, ref := range refs {
269
+ target, _ := crossref.Parse(ref.Beacon.String())
270
+ // safe to ignore error as validation has already been passed
271
+
272
+ source := &crossref.RefSource{
273
+ Local: true,
274
+ PeerName: "localhost",
275
+ Property: schema.PropertyName(prop),
276
+ Class: schema.ClassName(sourceClass),
277
+ TargetID: sourceID,
278
+ }
279
+
280
+ outRefs = append(outRefs, BatchReference{From: source, To: target})
281
+ }
282
+ }
283
+
284
+ return primitive, outRefs
285
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/merge_test.go ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "encoding/json"
17
+ "errors"
18
+ "testing"
19
+ "time"
20
+
21
+ "github.com/go-openapi/strfmt"
22
+ "github.com/stretchr/testify/mock"
23
+ "github.com/weaviate/weaviate/entities/additional"
24
+ "github.com/weaviate/weaviate/entities/models"
25
+ "github.com/weaviate/weaviate/entities/schema/crossref"
26
+ "github.com/weaviate/weaviate/entities/search"
27
+ )
28
+
29
+ type stage int
30
+
31
+ const (
32
+ stageInit = iota
33
+ // stageInputValidation
34
+ stageAuthorization
35
+ stageUpdateValidation
36
+ stageObjectExists
37
+ // stageVectorization
38
+ // stageMerge
39
+ stageCount
40
+ )
41
+
42
+ func Test_MergeObject(t *testing.T) {
43
+ t.Parallel()
44
+ var (
45
+ uuid = strfmt.UUID("dd59815b-142b-4c54-9b12-482434bd54ca")
46
+ cls = "ZooAction"
47
+ lastTime int64 = 12345
48
+ errAny = errors.New("any error")
49
+ )
50
+
51
+ tests := []struct {
52
+ name string
53
+ // inputs
54
+ previous *models.Object
55
+ updated *models.Object
56
+ vectorizerCalledWith *models.Object
57
+
58
+ // outputs
59
+ expectedOutput *MergeDocument
60
+ wantCode int
61
+
62
+ // control return errors
63
+ errMerge error
64
+ errUpdateObject error
65
+ errGetObject error
66
+ errExists error
67
+ stage
68
+ }{
69
+ {
70
+ name: "empty class",
71
+ previous: nil,
72
+ updated: &models.Object{
73
+ ID: uuid,
74
+ },
75
+ wantCode: StatusBadRequest,
76
+ stage: stageInit,
77
+ },
78
+ {
79
+ name: "empty uuid",
80
+ previous: nil,
81
+ updated: &models.Object{
82
+ Class: cls,
83
+ },
84
+ wantCode: StatusBadRequest,
85
+ stage: stageInit,
86
+ },
87
+ {
88
+ name: "empty updates",
89
+ previous: nil,
90
+ wantCode: StatusBadRequest,
91
+ stage: stageInit,
92
+ },
93
+ {
94
+ name: "object not found",
95
+ previous: nil,
96
+ updated: &models.Object{
97
+ Class: cls,
98
+ ID: uuid,
99
+ Properties: map[string]interface{}{
100
+ "name": "My little pony zoo with extra sparkles",
101
+ },
102
+ },
103
+ wantCode: StatusNotFound,
104
+ stage: stageObjectExists,
105
+ },
106
+ {
107
+ name: "object failure",
108
+ previous: nil,
109
+ updated: &models.Object{
110
+ Class: cls,
111
+ ID: uuid,
112
+ Properties: map[string]interface{}{
113
+ "name": "My little pony zoo with extra sparkles",
114
+ },
115
+ },
116
+ wantCode: StatusInternalServerError,
117
+ errGetObject: errAny,
118
+ stage: stageObjectExists,
119
+ },
120
+ {
121
+ name: "cross-ref not found",
122
+ previous: nil,
123
+ updated: &models.Object{
124
+ Class: cls,
125
+ ID: uuid,
126
+ Properties: map[string]interface{}{
127
+ "name": "My little pony zoo with extra sparkles",
128
+ "hasAnimals": []interface{}{
129
+ map[string]interface{}{
130
+ "beacon": "weaviate://localhost/a8ffc82c-9845-4014-876c-11369353c33c",
131
+ },
132
+ },
133
+ },
134
+ },
135
+ wantCode: StatusNotFound,
136
+ errExists: errAny,
137
+ stage: stageAuthorization,
138
+ },
139
+ {
140
+ name: "merge failure",
141
+ previous: &models.Object{
142
+ Class: cls,
143
+ Properties: map[string]interface{}{},
144
+ Vectors: map[string]models.Vector{},
145
+ },
146
+ updated: &models.Object{
147
+ Class: cls,
148
+ ID: uuid,
149
+ Properties: map[string]interface{}{
150
+ "name": "My little pony zoo with extra sparkles",
151
+ },
152
+ },
153
+ vectorizerCalledWith: &models.Object{
154
+ Class: cls,
155
+ Properties: map[string]interface{}{
156
+ "name": "My little pony zoo with extra sparkles",
157
+ },
158
+ },
159
+ expectedOutput: &MergeDocument{
160
+ UpdateTime: lastTime,
161
+ Class: cls,
162
+ ID: uuid,
163
+ Vector: []float32{1, 2, 3},
164
+ PrimitiveSchema: map[string]interface{}{
165
+ "name": "My little pony zoo with extra sparkles",
166
+ },
167
+ Vectors: map[string]models.Vector{},
168
+ },
169
+ errMerge: errAny,
170
+ wantCode: StatusInternalServerError,
171
+ stage: stageCount,
172
+ },
173
+ {
174
+ name: "vectorization failure",
175
+ previous: &models.Object{
176
+ Class: cls,
177
+ Properties: map[string]interface{}{},
178
+ },
179
+ updated: &models.Object{
180
+ Class: cls,
181
+ ID: uuid,
182
+ Properties: map[string]interface{}{
183
+ "name": "My little pony zoo with extra sparkles",
184
+ },
185
+ },
186
+ vectorizerCalledWith: &models.Object{
187
+ Class: cls,
188
+ Properties: map[string]interface{}{
189
+ "name": "My little pony zoo with extra sparkles",
190
+ },
191
+ },
192
+ errUpdateObject: errAny,
193
+ wantCode: StatusInternalServerError,
194
+ stage: stageCount,
195
+ },
196
+ {
197
+ name: "add property",
198
+ previous: &models.Object{
199
+ Class: cls,
200
+ Properties: map[string]interface{}{},
201
+ },
202
+ updated: &models.Object{
203
+ Class: cls,
204
+ ID: uuid,
205
+ Properties: map[string]interface{}{
206
+ "name": "My little pony zoo with extra sparkles",
207
+ },
208
+ },
209
+ vectorizerCalledWith: &models.Object{
210
+ Class: cls,
211
+ Properties: map[string]interface{}{
212
+ "name": "My little pony zoo with extra sparkles",
213
+ },
214
+ },
215
+ expectedOutput: &MergeDocument{
216
+ UpdateTime: lastTime,
217
+ Class: cls,
218
+ ID: uuid,
219
+ Vector: []float32{1, 2, 3},
220
+ PrimitiveSchema: map[string]interface{}{
221
+ "name": "My little pony zoo with extra sparkles",
222
+ },
223
+ Vectors: map[string]models.Vector{},
224
+ },
225
+ stage: stageCount,
226
+ },
227
+ {
228
+ name: "update property",
229
+ previous: &models.Object{
230
+ Class: cls,
231
+ Properties: map[string]interface{}{"name": "this name"},
232
+ Vector: []float32{0.7, 0.3},
233
+ },
234
+ updated: &models.Object{
235
+ Class: cls,
236
+ ID: uuid,
237
+ Properties: map[string]interface{}{
238
+ "name": "another name",
239
+ },
240
+ },
241
+ vectorizerCalledWith: &models.Object{
242
+ Class: cls,
243
+ Properties: map[string]interface{}{
244
+ "name": "another name",
245
+ },
246
+ },
247
+ expectedOutput: &MergeDocument{
248
+ UpdateTime: lastTime,
249
+ Class: cls,
250
+ ID: uuid,
251
+ Vector: []float32{1, 2, 3},
252
+ PrimitiveSchema: map[string]interface{}{
253
+ "name": "another name",
254
+ },
255
+ Vectors: map[string]models.Vector{},
256
+ },
257
+ stage: stageCount,
258
+ },
259
+ {
260
+ name: "without properties",
261
+ previous: &models.Object{
262
+ Class: cls,
263
+ },
264
+ updated: &models.Object{
265
+ Class: cls,
266
+ ID: uuid,
267
+ },
268
+ vectorizerCalledWith: &models.Object{
269
+ Class: cls,
270
+ Properties: map[string]interface{}{},
271
+ },
272
+ expectedOutput: &MergeDocument{
273
+ UpdateTime: lastTime,
274
+ Class: cls,
275
+ ID: uuid,
276
+ Vector: []float32{1, 2, 3},
277
+ PrimitiveSchema: map[string]interface{}{},
278
+ Vectors: map[string]models.Vector{},
279
+ },
280
+ stage: stageCount,
281
+ },
282
+ {
283
+ name: "add primitive properties of different types",
284
+ previous: &models.Object{
285
+ Class: cls,
286
+ Properties: map[string]interface{}{},
287
+ },
288
+ updated: &models.Object{
289
+ Class: cls,
290
+ ID: uuid,
291
+ Properties: map[string]interface{}{
292
+ "name": "My little pony zoo with extra sparkles",
293
+ "area": 3.222,
294
+ "employees": json.Number("70"),
295
+ "located": map[string]interface{}{
296
+ "latitude": 30.2,
297
+ "longitude": 60.2,
298
+ },
299
+ "foundedIn": "2002-10-02T15:00:00Z",
300
+ },
301
+ },
302
+ vectorizerCalledWith: &models.Object{
303
+ Class: cls,
304
+ Properties: map[string]interface{}{
305
+ "name": "My little pony zoo with extra sparkles",
306
+ "area": 3.222,
307
+ "employees": int64(70),
308
+ "located": &models.GeoCoordinates{
309
+ Latitude: ptFloat32(30.2),
310
+ Longitude: ptFloat32(60.2),
311
+ },
312
+ "foundedIn": timeMustParse(time.RFC3339, "2002-10-02T15:00:00Z"),
313
+ },
314
+ },
315
+ expectedOutput: &MergeDocument{
316
+ UpdateTime: lastTime,
317
+ Class: cls,
318
+ ID: uuid,
319
+ Vector: []float32{1, 2, 3},
320
+ PrimitiveSchema: map[string]interface{}{
321
+ "name": "My little pony zoo with extra sparkles",
322
+ "area": 3.222,
323
+ "employees": float64(70),
324
+ "located": &models.GeoCoordinates{
325
+ Latitude: ptFloat32(30.2),
326
+ Longitude: ptFloat32(60.2),
327
+ },
328
+ "foundedIn": timeMustParse(time.RFC3339, "2002-10-02T15:00:00Z"),
329
+ },
330
+ Vectors: map[string]models.Vector{},
331
+ },
332
+ stage: stageCount,
333
+ },
334
+ {
335
+ name: "add primitive and ref properties",
336
+ previous: &models.Object{
337
+ Class: cls,
338
+ Properties: map[string]interface{}{},
339
+ },
340
+ updated: &models.Object{
341
+ Class: cls,
342
+ ID: uuid,
343
+ Properties: map[string]interface{}{
344
+ "name": "My little pony zoo with extra sparkles",
345
+ "hasAnimals": []interface{}{
346
+ map[string]interface{}{
347
+ "beacon": "weaviate://localhost/AnimalAction/a8ffc82c-9845-4014-876c-11369353c33c",
348
+ },
349
+ },
350
+ },
351
+ },
352
+ vectorizerCalledWith: &models.Object{
353
+ Class: cls,
354
+ Properties: map[string]interface{}{
355
+ "name": "My little pony zoo with extra sparkles",
356
+ },
357
+ },
358
+ expectedOutput: &MergeDocument{
359
+ UpdateTime: lastTime,
360
+ Class: cls,
361
+ ID: uuid,
362
+ PrimitiveSchema: map[string]interface{}{
363
+ "name": "My little pony zoo with extra sparkles",
364
+ },
365
+ Vector: []float32{1, 2, 3},
366
+ References: BatchReferences{
367
+ BatchReference{
368
+ From: crossrefMustParseSource("weaviate://localhost/ZooAction/dd59815b-142b-4c54-9b12-482434bd54ca/hasAnimals"),
369
+ To: crossrefMustParse("weaviate://localhost/AnimalAction/a8ffc82c-9845-4014-876c-11369353c33c"),
370
+ },
371
+ },
372
+ Vectors: map[string]models.Vector{},
373
+ },
374
+ stage: stageCount,
375
+ },
376
+ {
377
+ name: "update vector non-vectorized class",
378
+ previous: &models.Object{
379
+ Class: "NotVectorized",
380
+ Properties: map[string]interface{}{
381
+ "description": "this description was set initially",
382
+ },
383
+ Vector: []float32{0.7, 0.3},
384
+ },
385
+ updated: &models.Object{
386
+ Class: "NotVectorized",
387
+ ID: uuid,
388
+ Vector: []float32{0.66, 0.22},
389
+ },
390
+ vectorizerCalledWith: nil,
391
+ expectedOutput: &MergeDocument{
392
+ UpdateTime: lastTime,
393
+ Class: "NotVectorized",
394
+ ID: uuid,
395
+ Vector: []float32{0.66, 0.22},
396
+ PrimitiveSchema: map[string]interface{}{},
397
+ Vectors: map[string]models.Vector{},
398
+ },
399
+ stage: stageCount,
400
+ },
401
+ {
402
+ name: "do not update vector non-vectorized class",
403
+ previous: &models.Object{
404
+ Class: "NotVectorized",
405
+ Properties: map[string]interface{}{
406
+ "description": "this description was set initially",
407
+ },
408
+ Vector: []float32{0.7, 0.3},
409
+ },
410
+ updated: &models.Object{
411
+ Class: "NotVectorized",
412
+ ID: uuid,
413
+ Properties: map[string]interface{}{
414
+ "description": "this description was updated",
415
+ },
416
+ },
417
+ vectorizerCalledWith: nil,
418
+ expectedOutput: &MergeDocument{
419
+ UpdateTime: lastTime,
420
+ Class: "NotVectorized",
421
+ ID: uuid,
422
+ Vector: []float32{0.7, 0.3},
423
+ PrimitiveSchema: map[string]interface{}{
424
+ "description": "this description was updated",
425
+ },
426
+ Vectors: map[string]models.Vector{},
427
+ },
428
+ stage: stageCount,
429
+ },
430
+ }
431
+
432
+ for _, tc := range tests {
433
+ t.Run(tc.name, func(t *testing.T) {
434
+ m := newFakeGetManager(zooAnimalSchemaForTest())
435
+ m.timeSource = fakeTimeSource{}
436
+ cls := ""
437
+ if tc.updated != nil {
438
+ cls = tc.updated.Class
439
+ }
440
+ if tc.previous != nil {
441
+ m.repo.On("Object", cls, uuid, search.SelectProperties(nil), additional.Properties{}, "").
442
+ Return(&search.Result{
443
+ Schema: tc.previous.Properties,
444
+ ClassName: tc.previous.Class,
445
+ Vector: tc.previous.Vector,
446
+ }, nil)
447
+ } else if tc.stage >= stageAuthorization {
448
+ m.repo.On("Object", cls, uuid, search.SelectProperties(nil), additional.Properties{}, "").
449
+ Return((*search.Result)(nil), tc.errGetObject)
450
+ }
451
+
452
+ if tc.expectedOutput != nil {
453
+ m.repo.On("Merge", *tc.expectedOutput).Return(tc.errMerge)
454
+ }
455
+
456
+ if tc.vectorizerCalledWith != nil {
457
+ if tc.errUpdateObject != nil {
458
+ m.modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
459
+ Return(nil, tc.errUpdateObject)
460
+ } else {
461
+ m.modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
462
+ Return(tc.expectedOutput.Vector, nil)
463
+ }
464
+ }
465
+
466
+ if tc.expectedOutput != nil && tc.expectedOutput.Vector != nil {
467
+ m.modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
468
+ Return(tc.expectedOutput.Vector, tc.errUpdateObject)
469
+ }
470
+
471
+ // called during validation of cross-refs only.
472
+ m.repo.On("Exists", mock.Anything, mock.Anything).Maybe().Return(true, tc.errExists)
473
+
474
+ err := m.MergeObject(context.Background(), nil, tc.updated, nil)
475
+ code := 0
476
+ if err != nil {
477
+ code = err.Code
478
+ }
479
+ if tc.wantCode != code {
480
+ t.Fatalf("status code want: %v got: %v", tc.wantCode, code)
481
+ } else if code == 0 && err != nil {
482
+ t.Fatal(err)
483
+ }
484
+
485
+ m.repo.AssertExpectations(t)
486
+ m.modulesProvider.AssertExpectations(t)
487
+ })
488
+ }
489
+ }
490
+
491
+ func timeMustParse(layout, value string) time.Time {
492
+ t, err := time.Parse(layout, value)
493
+ if err != nil {
494
+ panic(err)
495
+ }
496
+ return t
497
+ }
498
+
499
+ func crossrefMustParse(in string) *crossref.Ref {
500
+ ref, err := crossref.Parse(in)
501
+ if err != nil {
502
+ panic(err)
503
+ }
504
+
505
+ return ref
506
+ }
507
+
508
+ func crossrefMustParseSource(in string) *crossref.RefSource {
509
+ ref, err := crossref.ParseSource(in)
510
+ if err != nil {
511
+ panic(err)
512
+ }
513
+
514
+ return ref
515
+ }
516
+
517
+ type fakeTimeSource struct{}
518
+
519
+ func (f fakeTimeSource) Now() int64 {
520
+ return 12345
521
+ }
522
+
523
+ func ptFloat32(in float32) *float32 {
524
+ return &in
525
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/metrics.go ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "time"
16
+
17
+ "github.com/prometheus/client_golang/prometheus"
18
+ "github.com/weaviate/weaviate/usecases/monitoring"
19
+ )
20
+
21
+ type Metrics struct {
22
+ queriesCount *prometheus.GaugeVec
23
+ batchTime *prometheus.HistogramVec
24
+ dimensions *prometheus.CounterVec
25
+ dimensionsCombined prometheus.Counter
26
+ groupClasses bool
27
+ batchTenants prometheus.Summary
28
+ batchObjects prometheus.Summary
29
+ }
30
+
31
+ func NewMetrics(prom *monitoring.PrometheusMetrics) *Metrics {
32
+ if prom == nil {
33
+ return nil
34
+ }
35
+
36
+ return &Metrics{
37
+ queriesCount: prom.QueriesCount,
38
+ batchTime: prom.BatchTime,
39
+ dimensions: prom.QueryDimensions,
40
+ dimensionsCombined: prom.QueryDimensionsCombined,
41
+ groupClasses: prom.Group,
42
+ batchTenants: prom.BatchSizeTenants,
43
+ batchObjects: prom.BatchSizeObjects,
44
+ }
45
+ }
46
+
47
+ func (m *Metrics) queriesInc(queryType string) {
48
+ if m == nil {
49
+ return
50
+ }
51
+
52
+ m.queriesCount.With(prometheus.Labels{
53
+ "class_name": "n/a",
54
+ "query_type": queryType,
55
+ }).Inc()
56
+ }
57
+
58
+ func (m *Metrics) queriesDec(queryType string) {
59
+ if m == nil {
60
+ return
61
+ }
62
+
63
+ m.queriesCount.With(prometheus.Labels{
64
+ "class_name": "n/a",
65
+ "query_type": queryType,
66
+ }).Dec()
67
+ }
68
+
69
+ func (m *Metrics) BatchInc() {
70
+ m.queriesInc("batch")
71
+ }
72
+
73
+ func (m *Metrics) BatchDec() {
74
+ m.queriesDec("batch")
75
+ }
76
+
77
+ func (m *Metrics) BatchRefInc() {
78
+ m.queriesInc("batch_references")
79
+ }
80
+
81
+ func (m *Metrics) BatchRefDec() {
82
+ m.queriesDec("batch_references")
83
+ }
84
+
85
+ func (m *Metrics) BatchDeleteInc() {
86
+ m.queriesInc("batch_delete")
87
+ }
88
+
89
+ func (m *Metrics) BatchDeleteDec() {
90
+ m.queriesDec("batch_delete")
91
+ }
92
+
93
+ func (m *Metrics) AddObjectInc() {
94
+ m.queriesInc("add_object")
95
+ }
96
+
97
+ func (m *Metrics) AddObjectDec() {
98
+ m.queriesDec("add_object")
99
+ }
100
+
101
+ func (m *Metrics) UpdateObjectInc() {
102
+ m.queriesInc("update_object")
103
+ }
104
+
105
+ func (m *Metrics) UpdateObjectDec() {
106
+ m.queriesDec("update_object")
107
+ }
108
+
109
+ func (m *Metrics) MergeObjectInc() {
110
+ m.queriesInc("merge_object")
111
+ }
112
+
113
+ func (m *Metrics) MergeObjectDec() {
114
+ m.queriesDec("merge_object")
115
+ }
116
+
117
+ func (m *Metrics) DeleteObjectInc() {
118
+ m.queriesInc("delete_object")
119
+ }
120
+
121
+ func (m *Metrics) DeleteObjectDec() {
122
+ m.queriesDec("delete_object")
123
+ }
124
+
125
+ func (m *Metrics) GetObjectInc() {
126
+ m.queriesInc("get_object")
127
+ }
128
+
129
+ func (m *Metrics) GetObjectDec() {
130
+ m.queriesDec("get_object")
131
+ }
132
+
133
+ func (m *Metrics) HeadObjectInc() {
134
+ m.queriesInc("head_object")
135
+ }
136
+
137
+ func (m *Metrics) HeadObjectDec() {
138
+ m.queriesDec("head_object")
139
+ }
140
+
141
+ func (m *Metrics) AddReferenceInc() {
142
+ m.queriesInc("add_reference")
143
+ }
144
+
145
+ func (m *Metrics) AddReferenceDec() {
146
+ m.queriesDec("add_reference")
147
+ }
148
+
149
+ func (m *Metrics) UpdateReferenceInc() {
150
+ m.queriesInc("update_reference")
151
+ }
152
+
153
+ func (m *Metrics) UpdateReferenceDec() {
154
+ m.queriesDec("update_reference")
155
+ }
156
+
157
+ func (m *Metrics) DeleteReferenceInc() {
158
+ m.queriesInc("delete_reference")
159
+ }
160
+
161
+ func (m *Metrics) DeleteReferenceDec() {
162
+ m.queriesDec("delete_reference")
163
+ }
164
+
165
+ func (m *Metrics) BatchOp(op string, startNs int64) {
166
+ if m == nil {
167
+ return
168
+ }
169
+
170
+ took := float64(time.Now().UnixNano()-startNs) / float64(time.Millisecond)
171
+
172
+ m.batchTime.With(prometheus.Labels{
173
+ "operation": op,
174
+ "class_name": "n/a",
175
+ "shard_name": "n/a",
176
+ }).Observe(float64(took))
177
+ }
178
+
179
+ func (m *Metrics) BatchTenants(tenants int) {
180
+ if m == nil {
181
+ return
182
+ }
183
+
184
+ m.batchTenants.Observe(float64(tenants))
185
+ }
186
+
187
+ func (m *Metrics) BatchObjects(objects int) {
188
+ if m == nil {
189
+ return
190
+ }
191
+
192
+ m.batchObjects.Observe(float64(objects))
193
+ }
194
+
195
+ func (m *Metrics) AddUsageDimensions(className, queryType, operation string, dims int) {
196
+ if m == nil {
197
+ return
198
+ }
199
+
200
+ if m.groupClasses {
201
+ className = "n/a"
202
+ }
203
+
204
+ m.dimensions.With(prometheus.Labels{
205
+ "class_name": className,
206
+ "operation": operation,
207
+ "query_type": queryType,
208
+ }).Add(float64(dims))
209
+ m.dimensionsCombined.Add(float64(dims))
210
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/models_for_test.go ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ type FeatureProjection struct {
15
+ Vector []float32 `json:"vector"`
16
+ }
17
+
18
+ type NearestNeighbors struct {
19
+ Neighbors []*NearestNeighbor `json:"neighbors"`
20
+ }
21
+
22
+ type NearestNeighbor struct {
23
+ Concept string `json:"concept,omitempty"`
24
+ Distance float32 `json:"distance,omitempty"`
25
+ Vector []float32 `json:"vector"`
26
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/query.go ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+
18
+ "github.com/weaviate/weaviate/entities/additional"
19
+ "github.com/weaviate/weaviate/entities/filters"
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization/filter"
23
+ )
24
+
25
+ type QueryInput struct {
26
+ Class string
27
+ Offset int
28
+ Limit int
29
+ Cursor *filters.Cursor
30
+ Filters *filters.LocalFilter
31
+ Sort []filters.Sort
32
+ Tenant string
33
+ Additional additional.Properties
34
+ }
35
+
36
+ type QueryParams struct {
37
+ Class string
38
+ Offset *int64
39
+ Limit *int64
40
+ After *string
41
+ Sort *string
42
+ Order *string
43
+ Tenant *string
44
+ Additional additional.Properties
45
+ }
46
+
47
+ func (q *QueryParams) inputs(m *Manager) (*QueryInput, error) {
48
+ smartOffset, smartLimit, err := m.localOffsetLimit(q.Offset, q.Limit)
49
+ if err != nil {
50
+ return nil, err
51
+ }
52
+ sort := m.getSort(q.Sort, q.Order)
53
+ cursor := m.getCursor(q.After, q.Limit)
54
+ tenant := ""
55
+ if q.Tenant != nil {
56
+ tenant = *q.Tenant
57
+ }
58
+ return &QueryInput{
59
+ Class: q.Class,
60
+ Offset: smartOffset,
61
+ Limit: smartLimit,
62
+ Sort: sort,
63
+ Cursor: cursor,
64
+ Tenant: tenant,
65
+ Additional: q.Additional,
66
+ }, nil
67
+ }
68
+
69
+ func (m *Manager) Query(ctx context.Context, principal *models.Principal, params *QueryParams,
70
+ ) ([]*models.Object, *Error) {
71
+ class := "*"
72
+
73
+ if params != nil && params.Class != "" {
74
+ params.Class, _ = m.resolveAlias(params.Class)
75
+ class = params.Class
76
+ }
77
+
78
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsData(class)...); err != nil {
79
+ return nil, &Error{err.Error(), StatusForbidden, err}
80
+ }
81
+
82
+ m.metrics.GetObjectInc()
83
+ defer m.metrics.GetObjectDec()
84
+
85
+ q, err := params.inputs(m)
86
+ if err != nil {
87
+ return nil, &Error{"offset or limit", StatusBadRequest, err}
88
+ }
89
+
90
+ filteredQuery := filter.New[*QueryInput](m.authorizer, m.config.Config.Authorization.Rbac).Filter(
91
+ ctx,
92
+ m.logger,
93
+ principal,
94
+ []*QueryInput{q},
95
+ authorization.READ,
96
+ func(qi *QueryInput) string {
97
+ return authorization.CollectionsData(qi.Class)[0]
98
+ },
99
+ )
100
+ if len(filteredQuery) == 0 {
101
+ err = fmt.Errorf("unauthorized to access collection %s", q.Class)
102
+ return nil, &Error{err.Error(), StatusForbidden, err}
103
+ }
104
+
105
+ res, rerr := m.vectorRepo.Query(ctx, filteredQuery[0])
106
+ if rerr != nil {
107
+ return nil, rerr
108
+ }
109
+
110
+ if m.modulesProvider != nil {
111
+ res, err = m.modulesProvider.ListObjectsAdditionalExtend(ctx, res, q.Additional.ModuleParams)
112
+ if err != nil {
113
+ return nil, &Error{"extend results", StatusInternalServerError, err}
114
+ }
115
+ }
116
+
117
+ if q.Additional.Vector {
118
+ m.trackUsageList(res)
119
+ }
120
+
121
+ return res.ObjectsWithVector(q.Additional.Vector), nil
122
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/query_test.go ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "testing"
18
+
19
+ "github.com/stretchr/testify/assert"
20
+
21
+ "github.com/weaviate/weaviate/entities/additional"
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/schema"
24
+ "github.com/weaviate/weaviate/entities/search"
25
+ )
26
+
27
+ func TestQuery(t *testing.T) {
28
+ t.Parallel()
29
+ var (
30
+ cls = "MyClass"
31
+ m = newFakeGetManager(schema.Schema{})
32
+ errAny = errors.New("any")
33
+ )
34
+ params := QueryParams{
35
+ Class: cls,
36
+ Limit: ptInt64(10),
37
+ }
38
+ inputs := QueryInput{
39
+ Class: cls,
40
+ Limit: 10,
41
+ }
42
+ tests := []struct {
43
+ class string
44
+ name string
45
+ param QueryParams
46
+ mockedErr *Error
47
+ authErr error
48
+ wantCode int
49
+ mockedDBResponse []search.Result
50
+ wantResponse []*models.Object
51
+ wantQueryInput QueryInput
52
+ wantUsageTracking bool
53
+ }{
54
+ {
55
+ name: "not found",
56
+ class: cls,
57
+ param: params,
58
+ mockedErr: &Error{Code: StatusNotFound},
59
+ wantCode: StatusNotFound,
60
+ wantQueryInput: inputs,
61
+ },
62
+ {
63
+ name: "forbidden",
64
+ class: cls,
65
+ param: params,
66
+ authErr: errAny,
67
+ wantCode: StatusForbidden,
68
+ wantQueryInput: inputs,
69
+ },
70
+ {
71
+ name: "happy path",
72
+ class: cls,
73
+ param: params,
74
+ mockedDBResponse: []search.Result{
75
+ {
76
+ ClassName: cls,
77
+ Schema: map[string]interface{}{
78
+ "foo": "bar",
79
+ },
80
+ Dims: 3,
81
+ Dist: 0,
82
+ },
83
+ },
84
+ wantResponse: []*models.Object{{
85
+ Class: cls,
86
+ VectorWeights: map[string]string(nil),
87
+ Properties: map[string]interface{}{
88
+ "foo": "bar",
89
+ },
90
+ }},
91
+ wantQueryInput: inputs,
92
+ },
93
+ {
94
+ name: "happy path with explicit vector requested",
95
+ class: cls,
96
+ param: QueryParams{
97
+ Class: cls,
98
+ Limit: ptInt64(10),
99
+ Additional: additional.Properties{Vector: true},
100
+ },
101
+ mockedDBResponse: []search.Result{
102
+ {
103
+ ClassName: cls,
104
+ Schema: map[string]interface{}{
105
+ "foo": "bar",
106
+ },
107
+ Dims: 3,
108
+ },
109
+ },
110
+ wantResponse: []*models.Object{{
111
+ Class: cls,
112
+ VectorWeights: map[string]string(nil),
113
+ Properties: map[string]interface{}{
114
+ "foo": "bar",
115
+ },
116
+ }},
117
+ wantQueryInput: QueryInput{
118
+ Class: cls,
119
+ Limit: 10,
120
+ Additional: additional.Properties{Vector: true},
121
+ },
122
+ wantUsageTracking: true,
123
+ },
124
+ {
125
+ name: "bad request",
126
+ class: cls,
127
+ param: QueryParams{Class: cls, Offset: ptInt64(1), Limit: &m.config.Config.QueryMaximumResults},
128
+ wantCode: StatusBadRequest,
129
+ wantQueryInput: inputs,
130
+ },
131
+ }
132
+ for i, tc := range tests {
133
+ t.Run(tc.name, func(t *testing.T) {
134
+ m.authorizer.SetErr(tc.authErr)
135
+ if tc.authErr == nil {
136
+ m.repo.On("Query", &tc.wantQueryInput).Return(tc.mockedDBResponse, tc.mockedErr).Once()
137
+ }
138
+ if tc.wantUsageTracking {
139
+ m.metrics.On("AddUsageDimensions", cls, "get_rest", "list_include_vector",
140
+ tc.mockedDBResponse[0].Dims)
141
+ }
142
+ res, err := m.Manager.Query(context.Background(), &models.Principal{
143
+ Username: "testuser",
144
+ }, &tc.param)
145
+ code := 0
146
+ if err != nil {
147
+ code = err.Code
148
+ }
149
+ if tc.wantCode != code {
150
+ t.Errorf("case %d expected:%v got:%v", i+1, tc.wantCode, code)
151
+ }
152
+
153
+ assert.Equal(t, tc.wantResponse, res)
154
+ })
155
+ }
156
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/references.go ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+
19
+ "github.com/weaviate/weaviate/entities/versioned"
20
+
21
+ "github.com/go-openapi/strfmt"
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/schema"
24
+ "github.com/weaviate/weaviate/entities/schema/crossref"
25
+ autherrs "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
26
+ )
27
+
28
+ func (m *Manager) autodetectToClass(class *models.Class, fromProperty string, beaconRef *crossref.Ref) (strfmt.URI, strfmt.URI, bool, *Error) {
29
+ // autodetect to class from schema if not part of reference
30
+ prop, err := schema.GetPropertyByName(class, schema.LowercaseFirstLetter(fromProperty))
31
+ if err != nil {
32
+ return "", "", false, &Error{"cannot get property", StatusInternalServerError, err}
33
+ }
34
+ if len(prop.DataType) > 1 {
35
+ return "", "", false, nil // can't autodetect for multi target
36
+ }
37
+
38
+ toClass := prop.DataType[0] // datatype is the name of the class that is referenced
39
+ toBeacon := crossref.NewLocalhost(toClass, beaconRef.TargetID).String()
40
+
41
+ return strfmt.URI(toClass), strfmt.URI(toBeacon), true, nil
42
+ }
43
+
44
+ func (m *Manager) getAuthorizedFromClass(ctx context.Context, principal *models.Principal, className string) (*models.Class, uint64, versioned.Classes, *Error) {
45
+ fetchedClass, err := m.schemaManager.GetCachedClass(ctx, principal, className)
46
+ if err != nil {
47
+ if errors.As(err, &autherrs.Forbidden{}) {
48
+ return nil, 0, nil, &Error{err.Error(), StatusForbidden, err}
49
+ }
50
+
51
+ return nil, 0, nil, &Error{err.Error(), StatusBadRequest, err}
52
+ }
53
+ if _, ok := fetchedClass[className]; !ok {
54
+ err := fmt.Errorf("collection %q not found in schema", className)
55
+ return nil, 0, nil, &Error{"collection not found", StatusBadRequest, err}
56
+ }
57
+
58
+ return fetchedClass[className].Class, fetchedClass[className].Version, fetchedClass, nil
59
+ }
60
+
61
+ // validateNames validates class and property names
62
+ func validateReferenceName(class, property string) error {
63
+ if _, err := schema.ValidateClassName(class); err != nil {
64
+ return err
65
+ }
66
+
67
+ if err := schema.ValidateReservedPropertyName(property); err != nil {
68
+ return err
69
+ }
70
+
71
+ if _, err := schema.ValidatePropertyName(property); err != nil {
72
+ return err
73
+ }
74
+
75
+ return nil
76
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/references_add.go ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+
19
+ autherrs "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
20
+
21
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
22
+
23
+ "github.com/go-openapi/strfmt"
24
+
25
+ "github.com/weaviate/weaviate/entities/additional"
26
+ "github.com/weaviate/weaviate/entities/classcache"
27
+ "github.com/weaviate/weaviate/entities/models"
28
+ "github.com/weaviate/weaviate/entities/schema"
29
+ "github.com/weaviate/weaviate/entities/schema/crossref"
30
+ "github.com/weaviate/weaviate/usecases/objects/validation"
31
+ )
32
+
33
+ // AddObjectReference to an existing object. If the class contains a network
34
+ // ref, it has a side-effect on the schema: The schema will be updated to
35
+ // include this particular network ref class.
36
+ func (m *Manager) AddObjectReference(ctx context.Context, principal *models.Principal,
37
+ input *AddReferenceInput, repl *additional.ReplicationProperties, tenant string,
38
+ ) *Error {
39
+ m.metrics.AddReferenceInc()
40
+ defer m.metrics.AddReferenceDec()
41
+
42
+ ctx = classcache.ContextWithClassCache(ctx)
43
+ input.Class = schema.UppercaseClassName(input.Class)
44
+ input.Class, _ = m.resolveAlias(input.Class)
45
+
46
+ if err := m.authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.ShardsData(input.Class, tenant)...); err != nil {
47
+ return &Error{err.Error(), StatusForbidden, err}
48
+ }
49
+
50
+ deprecatedEndpoint := input.Class == ""
51
+ if deprecatedEndpoint { // for backward compatibility only
52
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.Collections()...); err != nil {
53
+ return &Error{err.Error(), StatusForbidden, err}
54
+ }
55
+ objectRes, err := m.getObjectFromRepo(ctx, "", input.ID,
56
+ additional.Properties{}, nil, tenant)
57
+ if err != nil {
58
+ errnf := ErrNotFound{} // treated as StatusBadRequest for backward comp
59
+ if errors.As(err, &errnf) {
60
+ return &Error{"source object deprecated", StatusBadRequest, err}
61
+ } else if errors.As(err, &ErrMultiTenancy{}) {
62
+ return &Error{"source object deprecated", StatusUnprocessableEntity, err}
63
+ }
64
+ return &Error{"source object deprecated", StatusInternalServerError, err}
65
+ }
66
+ input.Class = objectRes.Object().Class
67
+ }
68
+
69
+ if err := validateReferenceName(input.Class, input.Property); err != nil {
70
+ return &Error{err.Error(), StatusBadRequest, err}
71
+ }
72
+
73
+ class, schemaVersion, fetchedClass, typedErr := m.getAuthorizedFromClass(ctx, principal, input.Class)
74
+ if typedErr != nil {
75
+ return typedErr
76
+ }
77
+
78
+ validator := validation.New(m.vectorRepo.Exists, m.config, repl)
79
+ targetRef, err := input.validate(validator, class)
80
+ if err != nil {
81
+ if errors.As(err, &ErrMultiTenancy{}) {
82
+ return &Error{"validate inputs", StatusUnprocessableEntity, err}
83
+ }
84
+ var forbidden autherrs.Forbidden
85
+ if errors.As(err, &forbidden) {
86
+ return &Error{"validate inputs", StatusForbidden, err}
87
+ }
88
+
89
+ return &Error{"validate inputs", StatusBadRequest, err}
90
+ }
91
+
92
+ if input.Class != "" && targetRef.Class == "" {
93
+ toClass, toBeacon, replace, err := m.autodetectToClass(class, input.Property, targetRef)
94
+ if err != nil {
95
+ return err
96
+ }
97
+ if replace {
98
+ input.Ref.Class = toClass
99
+ input.Ref.Beacon = toBeacon
100
+ targetRef.Class = string(toClass)
101
+ }
102
+ }
103
+
104
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.ShardsData(targetRef.Class, tenant)...); err != nil {
105
+ return &Error{err.Error(), StatusForbidden, err}
106
+ }
107
+ if err := input.validateExistence(ctx, validator, tenant, targetRef); err != nil {
108
+ return &Error{"validate existence", StatusBadRequest, err}
109
+ }
110
+
111
+ if !deprecatedEndpoint {
112
+ ok, err := m.vectorRepo.Exists(ctx, input.Class, input.ID, repl, tenant)
113
+ if err != nil {
114
+ switch {
115
+ case errors.As(err, &ErrMultiTenancy{}):
116
+ return &Error{"source object", StatusUnprocessableEntity, err}
117
+ default:
118
+ return &Error{"source object", StatusInternalServerError, err}
119
+ }
120
+ }
121
+ if !ok {
122
+ return &Error{"source object", StatusNotFound, err}
123
+ }
124
+ }
125
+
126
+ source := crossref.NewSource(schema.ClassName(input.Class),
127
+ schema.PropertyName(input.Property), input.ID)
128
+
129
+ target, err := crossref.ParseSingleRef(&input.Ref)
130
+ if err != nil {
131
+ return &Error{"parse target ref", StatusBadRequest, err}
132
+ }
133
+
134
+ if shouldValidateMultiTenantRef(tenant, source, target) {
135
+ _, err = validateReferenceMultiTenancy(ctx, principal,
136
+ m.schemaManager, m.vectorRepo, source, target, tenant, fetchedClass)
137
+ if err != nil {
138
+ switch {
139
+ case errors.As(err, &autherrs.Forbidden{}):
140
+ return &Error{"validation", StatusForbidden, err}
141
+ default:
142
+ return &Error{"multi-tenancy violation", StatusInternalServerError, err}
143
+ }
144
+ }
145
+ }
146
+
147
+ // Ensure that the local schema has caught up to the version we used to validate
148
+ if err := m.schemaManager.WaitForUpdate(ctx, schemaVersion); err != nil {
149
+ return &Error{
150
+ Msg: fmt.Sprintf("error waiting for local schema to catch up to version %d", schemaVersion),
151
+ Code: StatusInternalServerError,
152
+ Err: err,
153
+ }
154
+ }
155
+ if err := m.vectorRepo.AddReference(ctx, source, target, repl, tenant, schemaVersion); err != nil {
156
+ return &Error{"add reference to repo", StatusInternalServerError, err}
157
+ }
158
+
159
+ if err := m.updateRefVector(ctx, principal, input.Class, input.ID, tenant, class, schemaVersion); err != nil {
160
+ return &Error{"update ref vector", StatusInternalServerError, err}
161
+ }
162
+
163
+ return nil
164
+ }
165
+
166
+ func shouldValidateMultiTenantRef(tenant string, source *crossref.RefSource, target *crossref.Ref) bool {
167
+ return tenant != "" || (source != nil && target != nil && source.Class != "" && target.Class != "")
168
+ }
169
+
170
+ // AddReferenceInput represents required inputs to add a reference to an existing object.
171
+ type AddReferenceInput struct {
172
+ // Class name
173
+ Class string
174
+ // ID of an object
175
+ ID strfmt.UUID
176
+ // Property name
177
+ Property string
178
+ // Ref cross reference
179
+ Ref models.SingleRef
180
+ }
181
+
182
+ func (req *AddReferenceInput) validate(
183
+ v *validation.Validator,
184
+ class *models.Class,
185
+ ) (*crossref.Ref, error) {
186
+ ref, err := v.ValidateSingleRef(&req.Ref)
187
+ if err != nil {
188
+ return nil, err
189
+ }
190
+
191
+ return ref, validateReferenceSchema(class, req.Property)
192
+ }
193
+
194
+ func (req *AddReferenceInput) validateExistence(
195
+ ctx context.Context,
196
+ v *validation.Validator, tenant string, ref *crossref.Ref,
197
+ ) error {
198
+ return v.ValidateExistence(ctx, ref, "validate reference", tenant)
199
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/references_delete.go ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "slices"
19
+
20
+ "github.com/weaviate/weaviate/entities/schema"
21
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
22
+
23
+ "github.com/go-openapi/strfmt"
24
+ "github.com/weaviate/weaviate/entities/additional"
25
+ "github.com/weaviate/weaviate/entities/classcache"
26
+ "github.com/weaviate/weaviate/entities/dto"
27
+ "github.com/weaviate/weaviate/entities/models"
28
+ "github.com/weaviate/weaviate/entities/schema/crossref"
29
+ )
30
+
31
+ // DeleteReferenceInput represents required inputs to delete a reference from an existing object.
32
+ type DeleteReferenceInput struct {
33
+ // Class name
34
+ Class string
35
+ // ID of an object
36
+ ID strfmt.UUID
37
+ // Property name
38
+ Property string
39
+ // Reference cross reference
40
+ Reference models.SingleRef
41
+ }
42
+
43
+ func (m *Manager) DeleteObjectReference(ctx context.Context, principal *models.Principal,
44
+ input *DeleteReferenceInput, repl *additional.ReplicationProperties, tenant string,
45
+ ) *Error {
46
+ m.metrics.DeleteReferenceInc()
47
+ defer m.metrics.DeleteReferenceDec()
48
+
49
+ ctx = classcache.ContextWithClassCache(ctx)
50
+ input.Class = schema.UppercaseClassName(input.Class)
51
+ input.Class, _ = m.resolveAlias(input.Class)
52
+
53
+ // We are fetching the existing object and get to know if the UUID exists
54
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.ShardsData(input.Class, tenant)...); err != nil {
55
+ return &Error{err.Error(), StatusForbidden, err}
56
+ }
57
+ if err := m.authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.ShardsData(input.Class, tenant)...); err != nil {
58
+ return &Error{err.Error(), StatusForbidden, err}
59
+ }
60
+
61
+ deprecatedEndpoint := input.Class == ""
62
+ // we need to know which collection an object belongs to, so for the deprecated case we first need to fetch the
63
+ // object from any collection, to then know its collection to check for the correct permissions after wards
64
+ if deprecatedEndpoint {
65
+ if err := m.authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsData()...); err != nil {
66
+ return &Error{err.Error(), StatusForbidden, err}
67
+ }
68
+ res, err := m.getObjectFromRepo(ctx, input.Class, input.ID, additional.Properties{}, nil, tenant)
69
+ if err != nil {
70
+ errnf := ErrNotFound{}
71
+ if errors.As(err, &errnf) {
72
+ return &Error{"source object", StatusNotFound, err}
73
+ } else if errors.As(err, &ErrMultiTenancy{}) {
74
+ return &Error{"source object", StatusUnprocessableEntity, err}
75
+ }
76
+
77
+ return &Error{"source object", StatusInternalServerError, err}
78
+ }
79
+ input.Class = res.ClassName
80
+ }
81
+
82
+ if err := validateReferenceName(input.Class, input.Property); err != nil {
83
+ return &Error{err.Error(), StatusBadRequest, err}
84
+ }
85
+
86
+ class, schemaVersion, _, typedErr := m.getAuthorizedFromClass(ctx, principal, input.Class)
87
+ if typedErr != nil {
88
+ return typedErr
89
+ }
90
+
91
+ res, err := m.getObjectFromRepo(ctx, input.Class, input.ID, additional.Properties{}, nil, tenant)
92
+ if err != nil {
93
+ errnf := ErrNotFound{}
94
+ if errors.As(err, &errnf) {
95
+ return &Error{"source object", StatusNotFound, err}
96
+ } else if errors.As(err, &ErrMultiTenancy{}) {
97
+ return &Error{"source object", StatusUnprocessableEntity, err}
98
+ }
99
+
100
+ return &Error{"source object", StatusInternalServerError, err}
101
+ }
102
+
103
+ beacon, err := crossref.Parse(input.Reference.Beacon.String())
104
+ if err != nil {
105
+ return &Error{"cannot parse beacon", StatusBadRequest, err}
106
+ }
107
+ if input.Class != "" && beacon.Class == "" {
108
+ toClass, toBeacon, replace, err := m.autodetectToClass(class, input.Property, beacon)
109
+ if err != nil {
110
+ return err
111
+ }
112
+ if replace {
113
+ input.Reference.Class = toClass
114
+ input.Reference.Beacon = toBeacon
115
+ }
116
+ }
117
+
118
+ if err := input.validateSchema(class); err != nil {
119
+ if deprecatedEndpoint { // for backward comp reasons
120
+ return &Error{"bad inputs deprecated", StatusNotFound, err}
121
+ }
122
+ if errors.As(err, &ErrMultiTenancy{}) {
123
+ return &Error{"bad inputs", StatusUnprocessableEntity, err}
124
+ }
125
+ return &Error{"bad inputs", StatusBadRequest, err}
126
+ }
127
+
128
+ obj := res.Object()
129
+ obj.Tenant = tenant
130
+ ok, errmsg := removeReference(obj, input.Property, &input.Reference)
131
+ if errmsg != "" {
132
+ return &Error{errmsg, StatusInternalServerError, nil}
133
+ }
134
+ if !ok {
135
+ return nil
136
+ }
137
+ obj.LastUpdateTimeUnix = m.timeSource.Now()
138
+
139
+ // Ensure that the local schema has caught up to the version we used to validate
140
+ if err := m.schemaManager.WaitForUpdate(ctx, schemaVersion); err != nil {
141
+ return &Error{
142
+ Msg: fmt.Sprintf("error waiting for local schema to catch up to version %d", schemaVersion),
143
+ Code: StatusInternalServerError,
144
+ Err: err,
145
+ }
146
+ }
147
+
148
+ vectors, multiVectors, err := dto.GetVectors(res.Vectors)
149
+ if err != nil {
150
+ return &Error{"repo.putobject", StatusInternalServerError, fmt.Errorf("cannot get vectors: %w", err)}
151
+ }
152
+ err = m.vectorRepo.PutObject(ctx, obj, res.Vector, vectors, multiVectors, repl, schemaVersion)
153
+ if err != nil {
154
+ return &Error{"repo.putobject", StatusInternalServerError, err}
155
+ }
156
+
157
+ if err := m.updateRefVector(ctx, principal, input.Class, input.ID, tenant, class, schemaVersion); err != nil {
158
+ return &Error{"update ref vector", StatusInternalServerError, err}
159
+ }
160
+
161
+ return nil
162
+ }
163
+
164
+ func (req *DeleteReferenceInput) validateSchema(class *models.Class) error {
165
+ return validateReferenceSchema(class, req.Property)
166
+ }
167
+
168
+ // removeReference removes ref from object obj with property prop.
169
+ // It returns ok (removal took place) and an error message
170
+ func removeReference(obj *models.Object, prop string, remove *models.SingleRef) (ok bool, errmsg string) {
171
+ properties := obj.Properties.(map[string]interface{})
172
+ if properties == nil || properties[prop] == nil {
173
+ return false, ""
174
+ }
175
+
176
+ refs, ok := properties[prop].(models.MultipleRef)
177
+ if !ok {
178
+ return false, fmt.Sprintf("property %s of type %T is not a valid cross-reference", prop, refs)
179
+ }
180
+
181
+ var removed bool
182
+ properties[prop] = slices.DeleteFunc(refs, func(ref *models.SingleRef) bool {
183
+ if ref.Beacon == remove.Beacon {
184
+ removed = removed || true
185
+ return true
186
+ }
187
+ return false
188
+ })
189
+ return removed, ""
190
+ }
platform/dbops/binaries/weaviate-src/usecases/objects/references_test.go ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package objects
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "testing"
18
+ "time"
19
+
20
+ "github.com/go-openapi/strfmt"
21
+ "github.com/stretchr/testify/assert"
22
+ "github.com/stretchr/testify/mock"
23
+ "github.com/stretchr/testify/require"
24
+ "github.com/weaviate/weaviate/entities/additional"
25
+ "github.com/weaviate/weaviate/entities/models"
26
+ "github.com/weaviate/weaviate/entities/schema"
27
+ "github.com/weaviate/weaviate/entities/schema/crossref"
28
+ "github.com/weaviate/weaviate/entities/search"
29
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
30
+ )
31
+
32
+ func Test_ReferencesAddDeprecated(t *testing.T) {
33
+ cls := "Zoo"
34
+ id := strfmt.UUID("my-id")
35
+ t.Run("without prior refs", func(t *testing.T) {
36
+ req := AddReferenceInput{
37
+ ID: id,
38
+ Property: "hasAnimals",
39
+ Ref: models.SingleRef{
40
+ Beacon: strfmt.URI("weaviate://localhost/d18c8e5e-a339-4c15-8af6-56b0cfe33ce7"),
41
+ },
42
+ }
43
+ m := newFakeGetManager(zooAnimalSchemaForTest())
44
+ m.repo.On("Exists", "Animal", mock.Anything).Return(true, nil)
45
+ m.repo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything).Return(&search.Result{
46
+ ClassName: cls,
47
+ Schema: map[string]interface{}{
48
+ "name": "MyZoo",
49
+ },
50
+ }, nil)
51
+ expectedRefProperty := "hasAnimals"
52
+ source := crossref.NewSource(schema.ClassName(cls), schema.PropertyName(expectedRefProperty), id)
53
+ target := crossref.New("localhost", "Animal", "d18c8e5e-a339-4c15-8af6-56b0cfe33ce7")
54
+ m.repo.On("AddReference", source, target).Return(nil)
55
+ m.modulesProvider.On("UsingRef2Vec", mock.Anything).Return(false)
56
+
57
+ err := m.AddObjectReference(context.Background(), nil, &req, nil, "")
58
+ require.Nil(t, err)
59
+ m.repo.AssertExpectations(t)
60
+ })
61
+ t.Run("source object missing", func(t *testing.T) {
62
+ req := AddReferenceInput{
63
+ ID: strfmt.UUID("my-id"),
64
+ Property: "hasAnimals",
65
+ Ref: models.SingleRef{
66
+ Beacon: strfmt.URI("weaviate://localhost/d18c8e5e-a339-4c15-8af6-56b0cfe33ce7"),
67
+ },
68
+ }
69
+ m := newFakeGetManager(zooAnimalSchemaForTest())
70
+ m.repo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
71
+ err := m.AddObjectReference(context.Background(), nil, &req, nil, "")
72
+ require.NotNil(t, err)
73
+ if !err.BadRequest() {
74
+ t.Errorf("error expected: not found error got: %v", err)
75
+ }
76
+ })
77
+ t.Run("source object missing", func(t *testing.T) {
78
+ req := AddReferenceInput{
79
+ ID: strfmt.UUID("my-id"),
80
+ Property: "hasAnimals",
81
+ Ref: models.SingleRef{
82
+ Beacon: strfmt.URI("weaviate://localhost/d18c8e5e-a339-4c15-8af6-56b0cfe33ce7"),
83
+ },
84
+ }
85
+ m := newFakeGetManager(zooAnimalSchemaForTest())
86
+ m.repo.On("ObjectByID", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("any"))
87
+ err := m.AddObjectReference(context.Background(), nil, &req, nil, "")
88
+ require.NotNil(t, err)
89
+ if err.Code != StatusInternalServerError {
90
+ t.Errorf("error expected: internal error, got: %v", err)
91
+ }
92
+ })
93
+ }
94
+
95
+ func Test_ReferenceAdd(t *testing.T) {
96
+ t.Parallel()
97
+ var (
98
+ cls = "Zoo"
99
+ prop = "hasAnimals"
100
+ id = strfmt.UUID("d18c8e5e-000-0000-0000-56b0cfe33ce7")
101
+ refID = strfmt.UUID("d18c8e5e-a339-4c15-8af6-56b0cfe33ce7")
102
+ uri = strfmt.URI("weaviate://localhost/d18c8e5e-a339-4c15-8af6-56b0cfe33ce7")
103
+ anyErr = errors.New("any")
104
+ ref = models.SingleRef{Beacon: uri}
105
+ req = AddReferenceInput{
106
+ Class: cls,
107
+ ID: id,
108
+ Property: prop,
109
+ Ref: ref,
110
+ }
111
+ source = crossref.NewSource(schema.ClassName(cls), schema.PropertyName(prop), id)
112
+ target = crossref.New("localhost", "Animal", refID)
113
+ )
114
+
115
+ tests := []struct {
116
+ Name string
117
+ // inputs
118
+ Req AddReferenceInput
119
+
120
+ // outputs
121
+ ExpectedRef models.SingleRef
122
+ WantCode int
123
+ WantErr error
124
+ SrcNotFound bool
125
+ // control errors
126
+ ErrAddRef error
127
+ ErrTargetExists error
128
+ ErrSrcExists error
129
+ ErrAuth error
130
+ ErrLock error
131
+ ErrSchema error
132
+ // Stage: 1 -> validation(), 2 -> target exists(), 3 -> source exists(), 4 -> AddReference()
133
+ Stage int
134
+ }{
135
+ {
136
+ Name: "authorization", Req: req, Stage: 0,
137
+ WantCode: StatusForbidden, WantErr: anyErr, ErrAuth: anyErr,
138
+ },
139
+ {
140
+ Name: "get schema",
141
+ Req: req, Stage: 1,
142
+ ErrSchema: anyErr,
143
+ WantCode: StatusBadRequest,
144
+ },
145
+ {
146
+ Name: "empty data type",
147
+ Req: AddReferenceInput{Class: cls, ID: id, Property: "emptyType", Ref: ref}, Stage: 1,
148
+ WantCode: StatusBadRequest,
149
+ },
150
+ {
151
+ Name: "primitive data type",
152
+ Req: AddReferenceInput{Class: cls, ID: id, Property: "name", Ref: ref}, Stage: 1,
153
+ WantCode: StatusBadRequest,
154
+ },
155
+ {
156
+ Name: "unknown property",
157
+ Req: AddReferenceInput{Class: cls, ID: id, Property: "unknown", Ref: ref}, Stage: 1,
158
+ WantCode: StatusBadRequest,
159
+ },
160
+ {
161
+ Name: "valid class name",
162
+ Req: AddReferenceInput{Class: "-", ID: id, Property: prop}, Stage: 1,
163
+ WantCode: StatusBadRequest,
164
+ },
165
+ {
166
+ Name: "reserved property name",
167
+ Req: AddReferenceInput{Class: cls, ID: id, Property: "_id"}, Stage: 1,
168
+ WantCode: StatusBadRequest,
169
+ },
170
+ {
171
+ Name: "valid property name",
172
+ Req: AddReferenceInput{Class: cls, ID: id, Property: "-"}, Stage: 1,
173
+ WantCode: StatusBadRequest,
174
+ },
175
+
176
+ {Name: "add valid reference", Req: req, Stage: 4},
177
+ {
178
+ Name: "referenced class not found", Req: req, Stage: 2,
179
+ WantCode: StatusBadRequest,
180
+ ErrTargetExists: anyErr,
181
+ WantErr: anyErr,
182
+ },
183
+ {
184
+ Name: "source object internal error", Req: req, Stage: 3,
185
+ WantCode: StatusInternalServerError,
186
+ ErrSrcExists: anyErr,
187
+ WantErr: anyErr,
188
+ },
189
+ {
190
+ Name: "source object missing", Req: req, Stage: 3,
191
+ WantCode: StatusNotFound,
192
+ SrcNotFound: true,
193
+ },
194
+ {
195
+ Name: "internal error", Req: req, Stage: 4,
196
+ WantCode: StatusInternalServerError,
197
+ ErrAddRef: anyErr,
198
+ WantErr: anyErr,
199
+ },
200
+ }
201
+
202
+ for _, tc := range tests {
203
+ t.Run(tc.Name, func(t *testing.T) {
204
+ m := newFakeGetManager(zooAnimalSchemaForTest())
205
+ m.authorizer.SetErr(tc.ErrAuth)
206
+ m.schemaManager.(*fakeSchemaManager).GetschemaErr = tc.ErrSchema
207
+ m.modulesProvider.On("UsingRef2Vec", mock.Anything).Return(false)
208
+ if tc.Stage >= 2 {
209
+ m.repo.On("Exists", "Animal", refID).Return(true, tc.ErrTargetExists).Once()
210
+ }
211
+ if tc.Stage >= 3 {
212
+ m.repo.On("Exists", tc.Req.Class, tc.Req.ID).Return(!tc.SrcNotFound, tc.ErrSrcExists).Once()
213
+ }
214
+ if tc.Stage >= 4 {
215
+ m.repo.On("AddReference", source, target).Return(tc.ErrAddRef).Once()
216
+ }
217
+
218
+ err := m.AddObjectReference(context.Background(), nil, &tc.Req, nil, "")
219
+ if tc.WantCode != 0 {
220
+ code := 0
221
+ if err != nil {
222
+ code = err.Code
223
+ }
224
+ if code != tc.WantCode {
225
+ t.Fatalf("code expected: %v, got %v", tc.WantCode, code)
226
+ }
227
+
228
+ if tc.WantErr != nil && !errors.Is(err, tc.WantErr) {
229
+ t.Errorf("wrapped error expected: %v, got %v", tc.WantErr, err.Err)
230
+ }
231
+
232
+ }
233
+ m.repo.AssertExpectations(t)
234
+ })
235
+ }
236
+ }
237
+
238
+ func Test_ReferenceUpdate(t *testing.T) {
239
+ t.Parallel()
240
+ var (
241
+ cls = "Zoo"
242
+ prop = "hasAnimals"
243
+ id = strfmt.UUID("d18c8e5e-000-0000-0000-56b0cfe33ce7")
244
+ refID = strfmt.UUID("d18c8e5e-a339-4c15-8af6-56b0cfe33ce7")
245
+ uri = strfmt.URI("weaviate://localhost/Animals/d18c8e5e-a339-4c15-8af6-56b0cfe33ce7")
246
+ anyErr = errors.New("any")
247
+ refs = models.MultipleRef{&models.SingleRef{Beacon: uri, Class: "Animals"}}
248
+ req = PutReferenceInput{
249
+ Class: cls,
250
+ ID: id,
251
+ Property: prop,
252
+ Refs: refs,
253
+ }
254
+ )
255
+
256
+ tests := []struct {
257
+ Name string
258
+ // inputs
259
+ Req PutReferenceInput
260
+
261
+ // outputs
262
+ ExpectedRef models.SingleRef
263
+ WantCode int
264
+ WantErr error
265
+ SrcNotFound bool
266
+ // control errors
267
+ ErrPutRefs error
268
+ ErrTargetExists error
269
+ ErrSrcExists error
270
+ ErrAuth error
271
+ ErrLock error
272
+ ErrSchema error
273
+ // Stage: 1 -> validation(), 2 -> target exists(), 3 -> PutObject()
274
+ Stage int
275
+ }{
276
+ {
277
+ Name: "source object internal error", Req: req,
278
+ WantCode: StatusInternalServerError,
279
+ ErrSrcExists: anyErr,
280
+ WantErr: NewErrInternal("repo: object by id: %v", anyErr),
281
+ Stage: 1,
282
+ },
283
+ {
284
+ Name: "source object missing", Req: req,
285
+ WantCode: StatusNotFound,
286
+ SrcNotFound: true,
287
+ Stage: 1,
288
+ },
289
+ {
290
+ Name: "authorization", Req: req,
291
+ WantCode: StatusForbidden, WantErr: anyErr, ErrAuth: anyErr,
292
+ Stage: 0,
293
+ },
294
+ {
295
+ Name: "get schema",
296
+ Req: req, Stage: 1,
297
+ ErrSchema: anyErr,
298
+ WantCode: StatusBadRequest,
299
+ },
300
+ {
301
+ Name: "empty data type",
302
+ Req: PutReferenceInput{Class: cls, ID: id, Property: "emptyType", Refs: refs}, Stage: 1,
303
+ WantCode: StatusBadRequest,
304
+ },
305
+ {
306
+ Name: "primitive data type",
307
+ Req: PutReferenceInput{Class: cls, ID: id, Property: "name", Refs: refs}, Stage: 1,
308
+ WantCode: StatusBadRequest,
309
+ },
310
+ {
311
+ Name: "unknown property",
312
+ Req: PutReferenceInput{Class: cls, ID: id, Property: "unknown", Refs: refs}, Stage: 1,
313
+ WantCode: StatusBadRequest,
314
+ },
315
+ {
316
+ Name: "reserved property name",
317
+ Req: PutReferenceInput{Class: cls, ID: id, Property: "_id", Refs: refs}, Stage: 1,
318
+ WantCode: StatusBadRequest,
319
+ },
320
+ {
321
+ Name: "valid property name",
322
+ Req: PutReferenceInput{Class: cls, ID: id, Property: "-", Refs: refs}, Stage: 1,
323
+ WantCode: StatusBadRequest,
324
+ },
325
+
326
+ {Name: "update valid reference", Req: req, Stage: 3},
327
+ {
328
+ Name: "referenced class not found", Req: req, Stage: 2,
329
+ WantCode: StatusBadRequest,
330
+ ErrTargetExists: anyErr,
331
+ WantErr: anyErr,
332
+ },
333
+ {
334
+ Name: "internal error", Req: req, Stage: 3,
335
+ WantCode: StatusInternalServerError,
336
+ ErrPutRefs: anyErr,
337
+ WantErr: anyErr,
338
+ },
339
+ }
340
+
341
+ for _, tc := range tests {
342
+ t.Run(tc.Name, func(t *testing.T) {
343
+ m := newFakeGetManager(zooAnimalSchemaForTest())
344
+ m.authorizer.SetErr(tc.ErrAuth)
345
+ m.schemaManager.(*fakeSchemaManager).GetschemaErr = tc.ErrSchema
346
+ srcObj := &search.Result{
347
+ ClassName: cls,
348
+ Schema: map[string]interface{}{
349
+ "name": "MyZoo",
350
+ },
351
+ }
352
+ if tc.SrcNotFound {
353
+ srcObj = nil
354
+ }
355
+ if tc.Stage >= 1 {
356
+ m.repo.On("Object", cls, id, mock.Anything, mock.Anything, "").Return(srcObj, tc.ErrSrcExists)
357
+ }
358
+
359
+ if tc.Stage >= 2 {
360
+ m.repo.On("Exists", "Animals", refID).Return(true, tc.ErrTargetExists).Once()
361
+ }
362
+
363
+ if tc.Stage >= 3 {
364
+ m.repo.On("PutObject", mock.Anything, mock.Anything).Return(tc.ErrPutRefs).Once()
365
+ }
366
+
367
+ err := m.UpdateObjectReferences(context.Background(), nil, &tc.Req, nil, "")
368
+ if tc.WantCode != 0 {
369
+ code := 0
370
+ if err != nil {
371
+ code = err.Code
372
+ }
373
+ if code != tc.WantCode {
374
+ t.Fatalf("code expected: %v, got %v", tc.WantCode, code)
375
+ }
376
+
377
+ if tc.WantErr != nil && !errors.Is(err, tc.WantErr) {
378
+ t.Errorf("wrapped error expected: %v, got %v", tc.WantErr, err.Err)
379
+ }
380
+
381
+ }
382
+ m.repo.AssertExpectations(t)
383
+ })
384
+ }
385
+ }
386
+
387
+ func Test_ReferenceDelete(t *testing.T) {
388
+ t.Parallel()
389
+ var (
390
+ cls = "Zoo"
391
+ prop = "hasAnimals"
392
+ id = strfmt.UUID("d18c8e5e-000-0000-0000-56b0cfe33ce7")
393
+ uri = strfmt.URI("weaviate://localhost/Animal/d18c8e5e-a339-4c15-8af6-56b0cfe33ce7")
394
+ anyErr = errors.New("any")
395
+ ref = models.SingleRef{Beacon: uri}
396
+ ref2 = &models.SingleRef{Beacon: strfmt.URI("weaviate://localhost/d18c8e5e-a339-4c15-8af6-56b0cfe33ce5")}
397
+ ref3 = &models.SingleRef{Beacon: strfmt.URI("weaviate://localhost/d18c8e5e-a339-4c15-8af6-56b0cfe33ce6")}
398
+ req = DeleteReferenceInput{
399
+ Class: cls,
400
+ ID: id,
401
+ Property: prop,
402
+ Reference: ref,
403
+ }
404
+ )
405
+
406
+ fakeProperties := func(refs ...*models.SingleRef) map[string]interface{} {
407
+ mrefs := make(models.MultipleRef, len(refs))
408
+ copy(mrefs, refs)
409
+ return map[string]interface{}{
410
+ "name": "MyZoo",
411
+ prop: mrefs,
412
+ }
413
+ }
414
+
415
+ tests := []struct {
416
+ Name string
417
+ // inputs
418
+ Req DeleteReferenceInput
419
+ properties interface{}
420
+ NewSrcRefsLen int
421
+ // outputs
422
+ ExpectedRef models.SingleRef
423
+ WantCode int
424
+ WantErr error
425
+ SrcNotFound bool
426
+ // control errors
427
+ ErrPutRefs error
428
+ ErrTargetExists error
429
+ ErrSrcExists error
430
+ ErrAuth error
431
+ ErrSchema error
432
+ // Stage: 1 -> validation(), 2 -> target exists(), 3 -> PutObject()
433
+ Stage int
434
+ }{
435
+ {
436
+ Name: "source object internal error", Req: req,
437
+ WantCode: StatusInternalServerError,
438
+ ErrSrcExists: anyErr,
439
+ WantErr: NewErrInternal("repo: object by id: %v", anyErr), Stage: 2,
440
+ },
441
+ {
442
+ Name: "source object missing", Req: req,
443
+ WantCode: StatusNotFound,
444
+ SrcNotFound: true, Stage: 2,
445
+ },
446
+ {
447
+ Name: "authorization", Req: req,
448
+ WantCode: StatusForbidden, WantErr: anyErr, ErrAuth: anyErr, Stage: 1,
449
+ },
450
+ {
451
+ Name: "get schema",
452
+ Req: req, Stage: 1,
453
+ ErrSchema: anyErr,
454
+ WantCode: StatusBadRequest,
455
+ },
456
+ {
457
+ Name: "empty data type",
458
+ Req: DeleteReferenceInput{Class: cls, ID: id, Property: "emptyType", Reference: ref}, Stage: 2,
459
+ WantCode: StatusBadRequest,
460
+ },
461
+ {
462
+ Name: "primitive data type",
463
+ Req: DeleteReferenceInput{Class: cls, ID: id, Property: "name", Reference: ref}, Stage: 2,
464
+ WantCode: StatusBadRequest,
465
+ },
466
+ {
467
+ Name: "unknown property",
468
+ Req: DeleteReferenceInput{Class: cls, ID: id, Property: "unknown", Reference: ref}, Stage: 2,
469
+ WantCode: StatusBadRequest,
470
+ },
471
+ {
472
+ Name: "reserved property name",
473
+ Req: DeleteReferenceInput{Class: cls, ID: id, Property: "_id"}, Stage: 1,
474
+ WantCode: StatusBadRequest,
475
+ },
476
+ {
477
+ Name: "valid property name",
478
+ Req: DeleteReferenceInput{Class: cls, ID: id, Property: "-"}, Stage: 1,
479
+ WantCode: StatusBadRequest,
480
+ },
481
+ {
482
+ Name: "delete one reference",
483
+ Req: req,
484
+ properties: fakeProperties(ref2, &ref, ref3), NewSrcRefsLen: 2,
485
+ Stage: 3,
486
+ },
487
+ {
488
+ Name: "delete two references",
489
+ Req: req,
490
+ properties: fakeProperties(&ref, ref2, &ref), NewSrcRefsLen: 1,
491
+ Stage: 3,
492
+ },
493
+ {
494
+ Name: "delete all references",
495
+ Req: req,
496
+ properties: fakeProperties(&ref, &ref), NewSrcRefsLen: 0,
497
+ Stage: 3,
498
+ },
499
+ {
500
+ Name: "reference not found",
501
+ Req: req,
502
+ properties: fakeProperties(ref2, ref3), NewSrcRefsLen: 2,
503
+ Stage: 2,
504
+ },
505
+ {
506
+ Name: "wrong reference type",
507
+ Req: req,
508
+ properties: map[string]interface{}{prop: "wrong reference type"}, NewSrcRefsLen: 0,
509
+ Stage: 2,
510
+ },
511
+ {
512
+ Name: "empty properties list",
513
+ Req: req,
514
+ properties: nil, NewSrcRefsLen: 0,
515
+ Stage: 2,
516
+ },
517
+ {
518
+ Name: "internal error",
519
+ Req: req,
520
+ properties: fakeProperties(ref2, &ref, ref3), NewSrcRefsLen: 3,
521
+ Stage: 3,
522
+ WantCode: StatusInternalServerError,
523
+ ErrPutRefs: anyErr,
524
+ WantErr: anyErr,
525
+ },
526
+ }
527
+
528
+ for _, tc := range tests {
529
+ t.Run(tc.Name, func(t *testing.T) {
530
+ m := newFakeGetManager(zooAnimalSchemaForTest())
531
+ m.authorizer.SetErr(tc.ErrAuth)
532
+ m.schemaManager.(*fakeSchemaManager).GetschemaErr = tc.ErrSchema
533
+ srcObj := &search.Result{
534
+ ClassName: cls,
535
+ Schema: tc.properties,
536
+ }
537
+ if tc.SrcNotFound {
538
+ srcObj = nil
539
+ }
540
+ if tc.Stage >= 2 {
541
+ m.repo.On("Object", cls, id, mock.Anything, mock.Anything, "").Return(srcObj, tc.ErrSrcExists)
542
+ m.modulesProvider.On("UsingRef2Vec", mock.Anything).Return(false)
543
+ }
544
+
545
+ if tc.Stage >= 3 {
546
+ m.repo.On("PutObject", mock.Anything, mock.Anything).Return(tc.ErrPutRefs).Once()
547
+ }
548
+
549
+ err := m.DeleteObjectReference(context.Background(), nil, &tc.Req, nil, "")
550
+ if tc.WantCode != 0 {
551
+ code := 0
552
+ if err != nil {
553
+ code = err.Code
554
+ }
555
+ if code != tc.WantCode {
556
+ t.Fatalf("code expected: %v, got %v", tc.WantCode, code)
557
+ }
558
+
559
+ if tc.WantErr != nil && !errors.Is(err, tc.WantErr) {
560
+ t.Errorf("wrapped error expected: %v, got %v", tc.WantErr, err.Err)
561
+ }
562
+
563
+ } else if tc.properties != nil {
564
+ refs, ok := srcObj.Schema.(map[string]interface{})[prop].(models.MultipleRef)
565
+ if g, w := len(refs), tc.NewSrcRefsLen; ok && g != w {
566
+ t.Errorf("length of source reference after deletion got:%v, want:%v", g, w)
567
+ }
568
+
569
+ }
570
+
571
+ m.repo.AssertExpectations(t)
572
+ })
573
+ }
574
+ }
575
+
576
+ func Test_ReferenceAdd_Ref2Vec(t *testing.T) {
577
+ t.Parallel()
578
+
579
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
580
+ defer cancel()
581
+
582
+ m := newFakeGetManager(articleSchemaForTest())
583
+
584
+ req := AddReferenceInput{
585
+ Class: "Article",
586
+ ID: strfmt.UUID("e1a60252-c38c-496d-8e54-306e1cedc5c4"),
587
+ Property: "hasParagraphs",
588
+ Ref: models.SingleRef{
589
+ Beacon: strfmt.URI("weaviate://localhost/Paragraph/494a2fe5-3e4c-4e9a-a47e-afcd9814f5ea"),
590
+ },
591
+ }
592
+
593
+ source := crossref.NewSource(schema.ClassName(req.Class), schema.PropertyName(req.Property), req.ID)
594
+ target := crossref.New("localhost", "Paragraph", "494a2fe5-3e4c-4e9a-a47e-afcd9814f5ea")
595
+ tenant := "randomTenant"
596
+
597
+ parent := &search.Result{
598
+ ID: strfmt.UUID("e1a60252-c38c-496d-8e54-306e1cedc5c4"),
599
+ ClassName: "Article",
600
+ Schema: map[string]interface{}{},
601
+ }
602
+
603
+ ref1 := &search.Result{
604
+ ID: strfmt.UUID("494a2fe5-3e4c-4e9a-a47e-afcd9814f5ea"),
605
+ ClassName: "Paragraph",
606
+ Vector: []float32{2, 4, 6},
607
+ }
608
+
609
+ m.repo.On("Exists", "Article", parent.ID).Return(true, nil)
610
+ m.repo.On("Exists", "Paragraph", ref1.ID).Return(true, nil)
611
+ m.repo.On("Object", "Article", parent.ID, search.SelectProperties{}, additional.Properties{}, tenant).Return(parent, nil)
612
+ m.repo.On("Object", "Paragraph", ref1.ID, search.SelectProperties{}, additional.Properties{}, tenant).Return(ref1, nil)
613
+ m.repo.On("AddReference", source, target).Return(nil)
614
+ m.modulesProvider.On("UsingRef2Vec", mock.Anything).Return(true)
615
+ m.modulesProvider.On("UpdateVector", mock.Anything, mock.AnythingOfType(FindObjectFn)).
616
+ Return(ref1.Vector, nil)
617
+ m.repo.On("PutObject", mock.Anything, ref1.Vector).Return(nil)
618
+ err := m.Manager.AddObjectReference(ctx, nil, &req, nil, tenant)
619
+ assert.Nil(t, err)
620
+ }
621
+
622
+ func Test_ReferenceDelete_Ref2Vec(t *testing.T) {
623
+ t.Parallel()
624
+
625
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
626
+ defer cancel()
627
+
628
+ m := newFakeGetManager(articleSchemaForTest())
629
+
630
+ req := DeleteReferenceInput{
631
+ Class: "Article",
632
+ ID: strfmt.UUID("e1a60252-c38c-496d-8e54-306e1cedc5c4"),
633
+ Property: "hasParagraphs",
634
+ Reference: models.SingleRef{
635
+ Beacon: strfmt.URI("weaviate://localhost/Paragraph/494a2fe5-3e4c-4e9a-a47e-afcd9814f5ea"),
636
+ },
637
+ }
638
+
639
+ tenant := "randomTenant"
640
+
641
+ parent := &search.Result{
642
+ ID: strfmt.UUID("e1a60252-c38c-496d-8e54-306e1cedc5c4"),
643
+ ClassName: "Article",
644
+ Schema: map[string]interface{}{},
645
+ }
646
+
647
+ ref1 := &search.Result{
648
+ ID: strfmt.UUID("494a2fe5-3e4c-4e9a-a47e-afcd9814f5ea"),
649
+ ClassName: "Paragraph",
650
+ Vector: []float32{2, 4, 6},
651
+ }
652
+
653
+ m.repo.On("Exists", "Article", parent.ID).Return(true, nil)
654
+ m.repo.On("Exists", "Paragraph", ref1.ID).Return(true, nil)
655
+ m.repo.On("Object", req.Class, req.ID, search.SelectProperties{}, additional.Properties{}, tenant).Return(parent, nil)
656
+ m.repo.On("PutObject", parent.Object(), []float32(nil)).Return(nil)
657
+ m.modulesProvider.On("UsingRef2Vec", mock.Anything).Return(true)
658
+
659
+ err := m.Manager.DeleteObjectReference(ctx, nil, &req, nil, tenant)
660
+ assert.Nil(t, err)
661
+ }
662
+
663
+ func articleSchemaForTest() schema.Schema {
664
+ return schema.Schema{
665
+ Objects: &models.Schema{
666
+ Classes: []*models.Class{
667
+ {
668
+ Class: "Paragraph",
669
+ VectorIndexConfig: hnsw.UserConfig{},
670
+ Properties: []*models.Property{
671
+ {
672
+ Name: "contents",
673
+ DataType: []string{"text"},
674
+ },
675
+ },
676
+ },
677
+ {
678
+ Class: "Article",
679
+ VectorIndexConfig: hnsw.UserConfig{},
680
+ Properties: []*models.Property{
681
+ {
682
+ Name: "title",
683
+ DataType: schema.DataTypeText.PropString(),
684
+ Tokenization: models.PropertyTokenizationWhitespace,
685
+ },
686
+ {
687
+ Name: "hasParagraphs",
688
+ DataType: []string{"Paragraph"},
689
+ },
690
+ },
691
+ Vectorizer: "ref2vec-centroid",
692
+ ModuleConfig: map[string]interface{}{
693
+ "ref2vec-centroid": map[string]interface{}{
694
+ "referenceProperties": []string{"hasParagraphs"},
695
+ "method": "mean",
696
+ },
697
+ },
698
+ },
699
+ },
700
+ },
701
+ }
702
+ }
703
+
704
+ func zooAnimalSchemaForTest() schema.Schema {
705
+ return schema.Schema{
706
+ Objects: &models.Schema{
707
+ Classes: []*models.Class{
708
+ {
709
+ Class: "ZooAction",
710
+ VectorIndexConfig: hnsw.UserConfig{},
711
+ Properties: []*models.Property{
712
+ {
713
+ Name: "name",
714
+ DataType: schema.DataTypeText.PropString(),
715
+ Tokenization: models.PropertyTokenizationWhitespace,
716
+ },
717
+ {
718
+ Name: "area",
719
+ DataType: []string{"number"},
720
+ },
721
+ {
722
+ Name: "employees",
723
+ DataType: []string{"int"},
724
+ },
725
+ {
726
+ Name: "located",
727
+ DataType: []string{"geoCoordinates"},
728
+ },
729
+ {
730
+ Name: "foundedIn",
731
+ DataType: []string{"date"},
732
+ },
733
+ {
734
+ Name: "hasAnimals",
735
+ DataType: []string{"AnimalAction"},
736
+ },
737
+ },
738
+ },
739
+ {
740
+ Class: "AnimalAction",
741
+ VectorIndexConfig: hnsw.UserConfig{},
742
+ Properties: []*models.Property{
743
+ {
744
+ Name: "name",
745
+ DataType: schema.DataTypeText.PropString(),
746
+ Tokenization: models.PropertyTokenizationWhitespace,
747
+ },
748
+ },
749
+ },
750
+ {
751
+ Class: "Zoo",
752
+ VectorIndexConfig: hnsw.UserConfig{},
753
+ Properties: []*models.Property{
754
+ {
755
+ Name: "name",
756
+ DataType: schema.DataTypeText.PropString(),
757
+ Tokenization: models.PropertyTokenizationWhitespace,
758
+ },
759
+ {
760
+ Name: "area",
761
+ DataType: []string{"number"},
762
+ },
763
+ {
764
+ Name: "employees",
765
+ DataType: []string{"int"},
766
+ },
767
+ {
768
+ Name: "located",
769
+ DataType: []string{"geoCoordinates"},
770
+ },
771
+ {
772
+ Name: "foundedIn",
773
+ DataType: []string{"date"},
774
+ },
775
+ {
776
+ Name: "hasAnimals",
777
+ DataType: []string{"Animal"},
778
+ },
779
+ {
780
+ Name: "emptyType",
781
+ DataType: []string{""},
782
+ },
783
+ },
784
+ },
785
+ {
786
+ Class: "Animal",
787
+ VectorIndexConfig: hnsw.UserConfig{},
788
+ Properties: []*models.Property{
789
+ {
790
+ Name: "name",
791
+ DataType: schema.DataTypeText.PropString(),
792
+ Tokenization: models.PropertyTokenizationWhitespace,
793
+ },
794
+ },
795
+ },
796
+ {
797
+ Class: "NotVectorized",
798
+ VectorIndexConfig: hnsw.UserConfig{},
799
+ Properties: []*models.Property{
800
+ {
801
+ Name: "description",
802
+ DataType: []string{"text"},
803
+ },
804
+ },
805
+ Vectorizer: "none",
806
+ },
807
+ },
808
+ },
809
+ }
810
+ }