Repository navigation
Expand file tree
/
Copy pathrequest.ts
More file actions
1354 lines (1282 loc) · 57.1 KB
/
Copy pathrequest.ts
File metadata and controls
1354 lines (1282 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { utf8ByteLength } from "@/lib/db/console/bounds";
import { RequestRefusal } from "@/lib/db/console/dialect";
import { ConsoleRefusal, type ConsoleRequest, consoleTokens, parseConsole } from "@/lib/db/console/parser";
import {
checkIntRange,
isTaggedFloat,
isTaggedInt,
type TaggedJson,
type TaggedObject,
taggedNumber,
toJsonText,
} from "@/lib/db/console/tagged-json";
import {
checkDenseElements,
checkMultiVector,
type VectorRefusal,
type VectorTarget,
vectorNumbers,
} from "@/lib/db/vector/dense";
import { sparseFromIndicesValues } from "@/lib/db/vector/sparse";
import type { VectorFieldInfo } from "@/lib/db/vector/types";
import type { QueryWarning } from "@/lib/types";
import type { QdrantOp } from "./client";
import {
QDRANT_BOUNDS,
QDRANT_CONSOLE,
QDRANT_ENUMS,
QDRANT_GATES,
QDRANT_KEYS,
QDRANT_LOCAL_MODELS,
QDRANT_QUERY_ALIAS,
QDRANT_ROUTES,
QDRANT_VECTOR_NAME_FORBIDDEN,
type QdrantGateId,
type QdrantObjectName,
type QdrantRoute,
refusedRouteSentence,
} from "./routes";
/**
* The Qdrant console's request rules: one console text to one typed request, in the phases every vector console
* validates in.
*
* Phase 0 reads the text alone and makes no call: the grammar (`parseQdrantRequest`), then every rule that needs
* no schema (`qdrantPhase0`): names, closed keys at every level, ids, the inference rule, enumerations, caps and
* budget arithmetic, and the engine's documented defaults written in. The version gates are phase 0 too, but only
* the server holds the version, so they are a call of their own (`qdrantVersionGates`), which the browser's
* verdict leaves out. Phase 1 (`qdrantPhase1`) checks every query vector against the collection described for
* this request and writes the body's text from the parser's tokens.
*
* Nothing here sends anything. The first two functions are what the browser runs before a statement leaves it.
*/
/** What a described collection tells a request and its result: written by the provider's schema module. */
export interface QdrantCollectionFacts {
/** Every vector of the collection, the unnamed one under the name "". */
readonly vectors: readonly VectorFieldInfo[];
/** Each vector's column type text, `Dense(384, float32, Cosine; stored normalised)` and the rest, by vector name. */
readonly typeTexts: ReadonlyMap<string, string>;
/** The names of the vectors the server answers as a reconstruction of what was stored (datatype turbo4). */
readonly reconstructed: ReadonlySet<string>;
/** Each indexed payload key and its index type. */
readonly payloadIndexTypes: ReadonlyMap<string, string>;
}
/** The form of a search's final stage, which decides what its score means. */
export type QdrantQueryForm =
| "none"
| "vector"
| "id"
| "nearest"
| "recommend"
| "discover"
| "context"
| "order_by"
| "fusion.rrf"
| "fusion.dbsf"
| "rrf"
| "formula"
| "sample"
| "relevance_feedback";
/** One search of a request: a query, each entry of a batch, or a grouped query. */
export interface QdrantSearch {
readonly form: QdrantQueryForm;
/** The vector its final stage searches, "" for the unnamed one. */
readonly using: string;
}
/** A query vector typed in the body, kept by identity so phase 1 can check it and write it back. */
interface VectorLiteral {
readonly where: string;
readonly using: string;
readonly node: TaggedJson;
readonly kind: "dense" | "multi" | "sparse" | "text";
}
/** A place that names a vector a collection must have. */
interface UsingUse {
readonly where: string;
readonly using: string;
/** False where the name was left out and the stage searches no vector, so nothing needs to exist. */
readonly needed: boolean;
/** The collection that must have it: the request's own, or the one a `lookup_from` names. */
readonly collection: string | null;
}
/** A request phase 0 accepted. */
export interface QdrantPhase0 {
readonly request: ConsoleRequest<QdrantOp>;
readonly route: QdrantRoute;
/** The body with the engine's defaults written in, or null where the route takes none. */
readonly body: TaggedObject | null;
/**
* The collections phase 1 describes, each once, in order: the request's own for every route that answers
* points, then each collection a `lookup_from` names. Empty for every other route.
*/
readonly collections: readonly string[];
readonly searches: readonly QdrantSearch[];
readonly gates: readonly QdrantGateId[];
readonly warnings: readonly QueryWarning[];
readonly literals: readonly VectorLiteral[];
readonly usings: readonly UsingUse[];
}
/** What a result needs to know about the request that asked for it. */
export interface QdrantResultShape {
readonly op: QdrantOp;
readonly facts: QdrantCollectionFacts | null;
readonly searches: readonly QdrantSearch[];
/** Whether a count, or a facet's counts, were asked for exactly. */
readonly exact: boolean;
readonly warnings: readonly QueryWarning[];
}
/** A request ready for the wire. `query` holds the user's keys; the runner sets `timeout`. */
export interface QdrantWire {
readonly op: QdrantOp;
readonly params: Readonly<Record<string, string>>;
readonly query: Readonly<Record<string, string>>;
readonly body?: string;
readonly shape: QdrantResultShape;
}
/** A UUID as the server reads one: 32 hex digits, or the hyphenated form; a form with only some hyphens is refused. */
const UUID = /^(?:[0-9a-fA-F]{32}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
const DIGITS = /^[0-9]+$/;
const SHOWN = 80;
const INFERENCE_RULE =
'Studio sends no inference input except a text for the local BM25 model: {"text": "...", "model": "qdrant/bm25"} ' +
'or "bm25", in lower case, with no options, aimed at a sparse vector.';
const INFERENCE_KEYS: readonly string[] = ["model", "text", "image", "object"];
const FILTER_CLAUSES: readonly string[] = ["must", "should", "must_not"];
const CONDITION_FORMS =
"a condition holds key (with match, range, geo_bounding_box, geo_radius, geo_polygon, values_count, is_empty or " +
"is_null), or is_empty, is_null, has_id, has_vector, slice or nested, or is itself a filter of must, should, " +
"must_not and min_should";
const QUERY_FORMS: readonly string[] = [
"nearest",
"recommend",
"discover",
"context",
"order_by",
"fusion",
"rrf",
"formula",
"sample",
"relevance_feedback",
];
const EXPRESSION_FORMS: Readonly<Record<string, QdrantObjectName>> = {
geo_distance: "GeoDistance",
datetime: "DatetimeExpression",
datetime_key: "DatetimeKeyExpression",
mult: "MultExpression",
sum: "SumExpression",
max: "MaxExpression",
min: "MinExpression",
neg: "NegExpression",
abs: "AbsExpression",
div: "DivExpression",
sqrt: "SqrtExpression",
pow: "PowExpression",
exp: "ExpExpression",
log10: "Log10Expression",
ln: "LnExpression",
acosh: "AcoshExpression",
lin_decay: "LinDecayExpression",
exp_decay: "ExpDecayExpression",
gauss_decay: "GaussDecayExpression",
};
const MATCH_FORMS: Readonly<Record<string, QdrantObjectName>> = {
value: "MatchValue",
text: "MatchText",
text_any: "MatchTextAny",
phrase: "MatchPhrase",
prefix: "MatchPrefix",
any: "MatchAny",
except: "MatchExcept",
};
/** The forms whose final stage searches a vector, so the vector they name must exist. */
const VECTOR_FORMS: ReadonlySet<QdrantQueryForm> = new Set([
"vector",
"id",
"nearest",
"recommend",
"discover",
"context",
"relevance_feedback",
]);
/** The routes that answer points, whose columns and scores are read from the described collection. */
const POINT_ROUTES: ReadonlySet<QdrantOp> = new Set([
"get_points",
"get_point",
"scroll_points",
"query_points",
"query_batch_points",
"query_points_groups",
]);
function refuse(message: string, key: string | null = null): never {
throw new RequestRefusal(message, 0, key);
}
function shown(text: string): string {
return JSON.stringify(text.length > SHOWN ? `${text.slice(0, SHOWN)}...` : text);
}
/** The JSON kind of a value, as a refusal names it, never the value itself. */
export function kindOf(value: TaggedJson | undefined): string {
if (value === undefined) return "nothing";
if (value === null) return "null";
if (Array.isArray(value)) return "a list";
if (isTaggedInt(value) || isTaggedFloat(value)) return "a number";
if (typeof value === "object") return "an object";
return typeof value === "boolean" ? "a boolean" : `a ${typeof value}`;
}
const isObject = (value: TaggedJson | undefined): value is TaggedObject =>
typeof value === "object" && value !== null && !Array.isArray(value) && !isTaggedInt(value) && !isTaggedFloat(value);
/** Whether the object holds the key with a value: a key written as null is a key left out. */
const has = (object: TaggedObject, key: string): boolean => Object.hasOwn(object, key) && object[key] !== null;
function objectAt(value: TaggedJson | undefined, where: string): TaggedObject {
if (!isObject(value)) return refuse(`${where} must be an object, found ${kindOf(value)}.`, where);
return value;
}
function listAt(value: TaggedJson | undefined, where: string): readonly TaggedJson[] {
if (!Array.isArray(value)) return refuse(`${where} must be a list, found ${kindOf(value)}.`, where);
return value;
}
function stringAt(value: TaggedJson | undefined, where: string): string {
if (typeof value !== "string") return refuse(`${where} must be a string, found ${kindOf(value)}.`, where);
return value;
}
/** The object's keys against the closed set of its schema: an unknown key and a missing required key by name. */
function closed(object: TaggedObject, name: QdrantObjectName, where: string): void {
const set = QDRANT_KEYS[name];
const keys: readonly string[] = set.keys;
for (const key of Object.keys(object)) {
if (!keys.includes(key)) {
refuse(`${where} takes no key ${shown(key)}: Qdrant reads ${keys.join(", ")} there and nothing else.`, key);
}
}
for (const key of set.required) {
if (!has(object, key)) refuse(`${where} needs the key ${key}.`, key);
}
}
/** A whole number written as an integer literal, from `min` to `max`. */
function integerAt(value: TaggedJson | undefined, where: string, min: number, max: number): number {
if (value === undefined || !isTaggedInt(value)) {
return refuse(`${where} must be an integer, found ${kindOf(value)}.`, where);
}
if (!checkIntRange(value, "safe") || Number(value.digits) < min || Number(value.digits) > max) {
return refuse(`${where} is ${value.digits}; it takes an integer from ${min} to ${max}.`, where);
}
return Number(value.digits);
}
function numberAt(value: TaggedJson | undefined, where: string): number {
if (value !== undefined && isTaggedFloat(value)) return Number(value.text);
if (value !== undefined && isTaggedInt(value)) return Number(value.digits);
return refuse(`${where} must be a number, found ${kindOf(value)}.`, where);
}
function wordAt(value: TaggedJson | undefined, where: string, words: readonly string[]): string {
if (typeof value !== "string" || !words.includes(value)) {
return refuse(
`${where} takes one of ${words.join(", ")}, not ${typeof value === "string" ? shown(value) : kindOf(value)}.`,
where,
);
}
return value;
}
/** A point id as a body takes it: an integer literal in the unsigned 64-bit range, or a UUID string. */
function pointIdAt(value: TaggedJson | undefined, where: string): void {
if (value !== undefined && isTaggedInt(value)) {
if (!checkIntRange(value, "uint64")) {
refuse(`${where} is ${value.digits}, outside the range of a point id, 0 to 18446744073709551615.`, where);
}
return;
}
if (typeof value === "string") {
if (UUID.test(value)) return;
if (DIGITS.test(value)) {
refuse(
`${where} is the string ${shown(value)}: write the id as a bare number, because Qdrant refuses a digit string.`,
where,
);
}
refuse(`${where} is ${shown(value)}, which is neither an unsigned integer nor a UUID.`, where);
}
refuse(`${where} must be a point id, an unsigned integer or a UUID string, found ${kindOf(value)}.`, where);
}
/**
* Why a collection or alias name cannot reach a path, or undefined: the server's own read-path rule. Every other
* character is the client's to percent-encode, so a name reaches the server as typed.
*/
export function qdrantCollectionNameRefusal(name: string): string | undefined {
if (name === "") return "A collection name cannot be empty.";
if (name === "." || name === "..") return `${shown(name)} is not a collection name: Qdrant serves no dot name.`;
if (name.includes("/") || name.includes("\u0000")) {
return `The collection name ${shown(name)} holds a character Qdrant refuses in a name: / or NUL.`;
}
const length = Array.from(name).length;
if (length > QDRANT_BOUNDS.maxCollectionNameLength) {
return `The collection name is ${length} characters long; Qdrant takes at most ${QDRANT_BOUNDS.maxCollectionNameLength}.`;
}
return undefined;
}
/** Why a vector name is not one Qdrant takes, or undefined. The unnamed vector's name, "", is refused here. */
export function qdrantVectorNameRefusal(name: string): string | undefined {
if (name === "") return "A vector name cannot be empty.";
if (name === "." || name === "..") return `${shown(name)} is not a vector name.`;
const forbidden = QDRANT_VECTOR_NAME_FORBIDDEN.find((character) => name.includes(character));
if (forbidden !== undefined) {
return `The vector name ${shown(name)} holds ${JSON.stringify(forbidden)}, a character Qdrant refuses in a vector name.`;
}
const bytes = utf8ByteLength(name);
if (bytes > QDRANT_BOUNDS.maxVectorNameBytes) {
return `The vector name is ${bytes} bytes long; Qdrant takes at most ${QDRANT_BOUNDS.maxVectorNameBytes}.`;
}
return undefined;
}
function collectionNameAt(value: TaggedJson | undefined, where: string): string {
const name = stringAt(value, where);
const refusal = qdrantCollectionNameRefusal(name);
return refusal === undefined ? name : refuse(`${where}: ${refusal}`, where);
}
function vectorNameAt(value: TaggedJson | undefined, where: string): string {
const name = stringAt(value, where);
const refusal = qdrantVectorNameRefusal(name);
return refusal === undefined ? name : refuse(`${where}: ${refusal}`, where);
}
/** What phase 0 gathers while it walks one request. */
class Walk {
readonly gates = new Set<QdrantGateId>();
readonly warnings: QueryWarning[] = [];
readonly literals: VectorLiteral[] = [];
readonly usings: UsingUse[] = [];
readonly searches: QdrantSearch[] = [];
filterBytes = 0;
prefetchNodes = 0;
candidates = 0;
rows = 0;
readonly lookups = new Set<string>();
private rangeWarned = false;
filter(value: TaggedJson, where: string): void {
this.filterBytes += utf8ByteLength(toJsonText(value));
if (this.filterBytes > QDRANT_BOUNDS.maxFilterBytes) {
refuse(
`The request's filters are ${this.filterBytes} bytes together, above the bound of ${QDRANT_BOUNDS.maxFilterBytes} bytes.`,
where,
);
}
readFilter(this, value, where, { conditions: 0 }, 0);
}
rangeBound(where: string): void {
if (this.rangeWarned) return;
this.rangeWarned = true;
this.warnings.push({
message: `${where} is an integer above 2^53: Qdrant compares range bounds as doubles, so a bound that large is rounded. A match on the value is exact.`,
});
}
candidate(count: number, where: string): void {
this.candidates += count;
if (this.candidates > QDRANT_BOUNDS.maxCandidates) {
refuse(
`The request asks its searches for ${this.candidates} candidates in all (each stage's offset plus limit, times its oversampling), above the bound of ${QDRANT_BOUNDS.maxCandidates}: lower a limit, an offset or an oversampling at or before ${where}.`,
where,
);
}
}
row(count: number, what: string): void {
this.rows += count;
if (this.rows > QDRANT_BOUNDS.maxRows) {
refuse(`The request asks for ${this.rows} rows (${what}), above the bound of ${QDRANT_BOUNDS.maxRows}.`, "limit");
}
}
}
interface FilterCount {
conditions: number;
}
function readFilter(walk: Walk, value: TaggedJson, where: string, count: FilterCount, nested: number): void {
const filter = objectAt(value, where);
closed(filter, "Filter", where);
for (const clause of FILTER_CLAUSES) {
if (!has(filter, clause)) continue;
const conditions = Array.isArray(filter[clause]) ? (filter[clause] as readonly TaggedJson[]) : [filter[clause]];
conditions.forEach((condition, index) => {
readCondition(walk, condition, `${where}.${clause}[${index}]`, count, nested);
});
}
if (has(filter, "min_should")) {
const minShould = objectAt(filter.min_should, `${where}.min_should`);
closed(minShould, "MinShould", `${where}.min_should`);
integerAt(minShould.min_count, `${where}.min_should.min_count`, 1, Number.MAX_SAFE_INTEGER);
listAt(minShould.conditions, `${where}.min_should.conditions`).forEach((condition, index) => {
readCondition(walk, condition, `${where}.min_should.conditions[${index}]`, count, nested);
});
}
}
function readCondition(walk: Walk, value: TaggedJson, where: string, count: FilterCount, nested: number): void {
const condition = objectAt(value, where);
const keys = Object.keys(condition);
const form = ["key", "is_empty", "is_null", "has_id", "has_vector", "slice", "nested"].find((key) =>
Object.hasOwn(condition, key),
);
if (form === undefined) {
const filterKeys: readonly string[] = QDRANT_KEYS.Filter.keys;
const stray = keys.find((key) => !filterKeys.includes(key));
if (stray !== undefined) refuse(`${where} takes no key ${shown(stray)}: ${CONDITION_FORMS}.`, stray);
readFilter(walk, condition, where, count, nested);
return;
}
count.conditions += 1;
if (count.conditions > QDRANT_BOUNDS.maxFilterConditions) {
refuse(`The filter holds more than ${QDRANT_BOUNDS.maxFilterConditions} conditions, the console's bound.`, where);
}
if (form === "key") {
readFieldCondition(walk, condition, where);
} else if (form === "is_empty" || form === "is_null") {
closed(condition, form === "is_empty" ? "IsEmptyCondition" : "IsNullCondition", where);
const field = objectAt(condition[form], `${where}.${form}`);
closed(field, "PayloadField", `${where}.${form}`);
stringAt(field.key, `${where}.${form}.key`);
} else if (form === "has_id") {
closed(condition, "HasIdCondition", where);
const ids = listAt(condition.has_id, `${where}.has_id`);
if (ids.length > QDRANT_BOUNDS.maxFilterListEntries) {
refuse(
`${where}.has_id holds ${ids.length} ids, above the bound of ${QDRANT_BOUNDS.maxFilterListEntries}.`,
"has_id",
);
}
ids.forEach((id, index) => {
pointIdAt(id, `${where}.has_id[${index}]`);
});
} else if (form === "has_vector") {
closed(condition, "HasVectorCondition", where);
const name = stringAt(condition.has_vector, `${where}.has_vector`);
// The unnamed vector is asked for by the empty name, the one place a request writes it.
if (name !== "") vectorNameAt(name, `${where}.has_vector`);
} else if (form === "slice") {
closed(condition, "SliceCondition", where);
const slice = objectAt(condition.slice, `${where}.slice`);
closed(slice, "Slice", `${where}.slice`);
const total = integerAt(slice.total, `${where}.slice.total`, 1, 4_294_967_295);
integerAt(slice.index, `${where}.slice.index`, 0, total - 1);
walk.gates.add("slice");
} else {
closed(condition, "NestedCondition", where);
const inner = objectAt(condition.nested, `${where}.nested`);
closed(inner, "Nested", `${where}.nested`);
stringAt(inner.key, `${where}.nested.key`);
if (nested + 1 > QDRANT_BOUNDS.maxNestedLevels) {
refuse(
`${where}.nested is more than ${QDRANT_BOUNDS.maxNestedLevels} nested conditions deep, the console's bound.`,
"nested",
);
}
readFilter(walk, inner.filter, `${where}.nested.filter`, count, nested + 1);
}
}
function readGeoPoint(value: TaggedJson | undefined, where: string): void {
const point = objectAt(value, where);
closed(point, "GeoPoint", where);
}
function readLineString(value: TaggedJson | undefined, where: string): void {
const line = objectAt(value, where);
closed(line, "GeoLineString", where);
listAt(line.points, `${where}.points`).forEach((point, index) => {
readGeoPoint(point, `${where}.points[${index}]`);
});
}
function readFieldCondition(walk: Walk, condition: TaggedObject, where: string): void {
closed(condition, "FieldCondition", where);
stringAt(condition.key, `${where}.key`);
if (has(condition, "match")) readMatch(walk, condition.match, `${where}.match`);
if (has(condition, "range")) {
const range = objectAt(condition.range, `${where}.range`);
closed(range, "Range", `${where}.range`);
for (const bound of Object.keys(range)) {
const value = range[bound];
if (value === null || typeof value === "string" || isTaggedFloat(value)) continue;
if (!isTaggedInt(value)) {
refuse(`${where}.range.${bound} must be a number or a date-time string, found ${kindOf(value)}.`, bound);
}
if (!checkIntRange(value, "safe")) walk.rangeBound(`${where}.range.${bound}`);
}
}
if (has(condition, "geo_bounding_box")) {
const box = objectAt(condition.geo_bounding_box, `${where}.geo_bounding_box`);
closed(box, "GeoBoundingBox", `${where}.geo_bounding_box`);
readGeoPoint(box.top_left, `${where}.geo_bounding_box.top_left`);
readGeoPoint(box.bottom_right, `${where}.geo_bounding_box.bottom_right`);
}
if (has(condition, "geo_radius")) {
const radius = objectAt(condition.geo_radius, `${where}.geo_radius`);
closed(radius, "GeoRadius", `${where}.geo_radius`);
readGeoPoint(radius.center, `${where}.geo_radius.center`);
}
if (has(condition, "geo_polygon")) {
const polygon = objectAt(condition.geo_polygon, `${where}.geo_polygon`);
closed(polygon, "GeoPolygon", `${where}.geo_polygon`);
readLineString(polygon.exterior, `${where}.geo_polygon.exterior`);
if (has(polygon, "interiors")) {
listAt(polygon.interiors, `${where}.geo_polygon.interiors`).forEach((line, index) => {
readLineString(line, `${where}.geo_polygon.interiors[${index}]`);
});
}
}
if (has(condition, "values_count")) {
closed(objectAt(condition.values_count, `${where}.values_count`), "ValuesCount", `${where}.values_count`);
}
}
/** An integer a match compares: Qdrant matches payload integers as signed 64-bit values. */
function matchInteger(value: TaggedJson, where: string): void {
if (isTaggedInt(value) && !checkIntRange(value, "int64")) {
refuse(`${where} is ${value.digits}, outside the signed 64-bit range a match compares.`, where);
}
}
function readMatch(walk: Walk, value: TaggedJson, where: string): void {
const match = objectAt(value, where);
const keys = Object.keys(match);
const form = keys.length === 1 ? MATCH_FORMS[keys[0]] : undefined;
if (form === undefined || !Object.hasOwn(MATCH_FORMS, keys[0])) {
refuse(
`${where} takes exactly one of ${Object.keys(MATCH_FORMS).join(", ")}; found ${keys.length === 0 ? "no key" : keys.map(shown).join(", ")}.`,
keys[0] ?? "match",
);
}
const key = keys[0];
if (key === "value") matchInteger(match.value, `${where}.value`);
else if (key === "any" || key === "except") {
const entries = listAt(match[key], `${where}.${key}`);
if (entries.length > QDRANT_BOUNDS.maxFilterListEntries) {
refuse(
`${where}.${key} holds ${entries.length} entries, above the bound of ${QDRANT_BOUNDS.maxFilterListEntries}.`,
key,
);
}
entries.forEach((entry, index) => {
matchInteger(entry, `${where}.${key}[${index}]`);
});
} else {
stringAt(match[key], `${where}.${key}`);
if (key === "prefix") walk.gates.add("matchPrefix");
}
}
interface FormulaCount {
nodes: number;
}
function readExpression(
walk: Walk,
value: TaggedJson | undefined,
where: string,
count: FormulaCount,
depth: number,
): void {
if (depth > QDRANT_BOUNDS.maxFormulaDepth) {
refuse(
`${where} is more than ${QDRANT_BOUNDS.maxFormulaDepth} expressions deep, the console's bound for a formula.`,
"formula",
);
}
count.nodes += 1;
if (count.nodes > QDRANT_BOUNDS.maxFormulaNodes) {
refuse(`The formula holds more than ${QDRANT_BOUNDS.maxFormulaNodes} expressions, the console's bound.`, "formula");
}
if (typeof value === "string" || (value !== undefined && (isTaggedInt(value) || isTaggedFloat(value)))) return;
const expression = objectAt(value, where);
const key = Object.keys(expression).find((name) => Object.hasOwn(EXPRESSION_FORMS, name));
if (key === undefined) {
readCondition(walk, expression, where, { conditions: 0 }, 0);
return;
}
closed(expression, EXPRESSION_FORMS[key], where);
const inner = `${where}.${key}`;
const operand = expression[key];
if (key === "mult" || key === "sum" || key === "max" || key === "min") {
if (key === "max") walk.gates.add("formulaMax");
if (key === "min") walk.gates.add("formulaMin");
listAt(operand, inner).forEach((entry, index) => {
readExpression(walk, entry, `${inner}[${index}]`, count, depth + 1);
});
} else if (key === "div") {
const div = objectAt(operand, inner);
closed(div, "DivParams", inner);
readExpression(walk, div.left, `${inner}.left`, count, depth + 1);
readExpression(walk, div.right, `${inner}.right`, count, depth + 1);
} else if (key === "pow") {
const pow = objectAt(operand, inner);
closed(pow, "PowParams", inner);
readExpression(walk, pow.base, `${inner}.base`, count, depth + 1);
readExpression(walk, pow.exponent, `${inner}.exponent`, count, depth + 1);
} else if (key === "geo_distance") {
const distance = objectAt(operand, inner);
closed(distance, "GeoDistanceParams", inner);
readGeoPoint(distance.origin, `${inner}.origin`);
stringAt(distance.to, `${inner}.to`);
} else if (key === "datetime" || key === "datetime_key") {
stringAt(operand, inner);
} else if (key === "lin_decay" || key === "exp_decay" || key === "gauss_decay") {
const decay = objectAt(operand, inner);
closed(decay, "DecayParamsExpression", inner);
readExpression(walk, decay.x, `${inner}.x`, count, depth + 1);
if (has(decay, "target")) readExpression(walk, decay.target, `${inner}.target`, count, depth + 1);
} else {
if (key === "acosh") walk.gates.add("formulaAcosh");
readExpression(walk, operand, inner, count, depth + 1);
}
}
/** A vector's numbers as phase 0 can check them with no schema: every element a number a float32 can hold. */
function checkLiteralNumbers(values: readonly TaggedJson[], where: string, using: string): void {
const target: VectorTarget = { name: using, kind: "dense", dtype: "float32", dimension: null };
const empty = values.indexOf(null);
if (empty !== -1) {
refuse(
`${where}: element ${empty} is null. Qdrant prints a float16 element that overflowed as null, and a vector with one cannot be sent back as a query.`,
where,
);
}
const numbers = vectorNumbers(target, values);
const refused = "sentence" in numbers ? numbers : checkDenseElements(target, numbers);
if (refused !== null) refuse(`${where}: ${(refused as VectorRefusal).sentence}`, where);
}
/**
* One vector input: a dense list, a list of lists, a point id, a sparse pair, or a text for the local model. Every
* other inference object is refused here, by name, before anything else about it is read.
*/
function readVectorInput(walk: Walk, value: TaggedJson | undefined, where: string, using: string): void {
if (Array.isArray(value)) {
if (value.length === 0) refuse(`${where} is an empty list: a query vector holds at least one number.`, where);
if (value.every((row) => Array.isArray(row))) {
(value as readonly (readonly TaggedJson[])[]).forEach((row, index) => {
if (row.length === 0)
refuse(`${where}[${index}] is an empty row: a multivector row holds at least one number.`, where);
checkLiteralNumbers(row, `${where}[${index}]`, using);
});
walk.literals.push({ where, using, node: value, kind: "multi" });
} else {
checkLiteralNumbers(value, where, using);
walk.literals.push({ where, using, node: value, kind: "dense" });
}
return;
}
if (!isObject(value)) {
pointIdAt(value, where);
return;
}
if (INFERENCE_KEYS.some((key) => Object.hasOwn(value, key))) {
const model = value.model;
if (typeof model !== "string" || !QDRANT_LOCAL_MODELS.includes(model)) {
const named =
typeof model === "string" ? `names the model ${shown(model)}` : "is an inference input with no model name";
refuse(`${where} ${named}, which this console does not send. ${INFERENCE_RULE}`, "model");
}
if (Object.hasOwn(value, "options")) refuse(`${where} holds options. ${INFERENCE_RULE}`, "options");
if (Object.hasOwn(value, "image") || Object.hasOwn(value, "object")) {
refuse(`${where} hands the local model an image or an object, and it reads a text. ${INFERENCE_RULE}`, "model");
}
closed(value, "Document", where);
stringAt(value.text, `${where}.text`);
walk.literals.push({ where, using, node: value, kind: "text" });
return;
}
closed(value, "SparseVector", where);
const sparse = sparseFromIndicesValues(
{ name: using, kind: "sparse", dtype: "float32", dimension: null },
listAt(value.indices, `${where}.indices`),
listAt(value.values, `${where}.values`),
QDRANT_BOUNDS.sparseIndexBoundExclusive,
);
if ("sentence" in sparse) refuse(`${where}: ${sparse.sentence}`, where);
walk.literals.push({ where, using, node: value, kind: "sparse" });
}
function readContext(walk: Walk, value: TaggedJson | undefined, where: string, using: string): void {
const pairs = Array.isArray(value) ? value : [value];
pairs.forEach((entry, index) => {
const at = Array.isArray(value) ? `${where}[${index}]` : where;
const pair = objectAt(entry, at);
closed(pair, "ContextPair", at);
readVectorInput(walk, pair.positive, `${at}.positive`, using);
readVectorInput(walk, pair.negative, `${at}.negative`, using);
});
}
function readOrderBy(value: TaggedJson | undefined, where: string): void {
if (typeof value === "string") return;
const order = objectAt(value, where);
closed(order, "OrderBy", where);
stringAt(order.key, `${where}.key`);
if (has(order, "direction")) wordAt(order.direction, `${where}.direction`, QDRANT_ENUMS.Direction);
const start = order.start_from;
if (start !== undefined && isTaggedInt(start) && !checkIntRange(start, "int64")) {
refuse(`${where}.start_from is ${start.digits}, outside the signed 64-bit range.`, "start_from");
}
}
interface QueryRead {
readonly form: QdrantQueryForm;
/** An MMR candidates_limit, which stands in for the stage's limit in the candidate sum. */
readonly mmrCandidates: number | null;
}
function readQuery(walk: Walk, value: TaggedJson | undefined, where: string, using: string): QueryRead {
if (value === undefined || value === null) return { form: "none", mmrCandidates: null };
if (!isObject(value)) {
readVectorInput(walk, value, where, using);
return { form: Array.isArray(value) ? "vector" : "id", mmrCandidates: null };
}
const forms = QUERY_FORMS.filter((key) => Object.hasOwn(value, key));
if (forms.length === 0) {
const vectorKeys: readonly string[] = [
...QDRANT_KEYS.SparseVector.keys,
...QDRANT_KEYS.Document.keys,
...QDRANT_KEYS.Image.keys,
...QDRANT_KEYS.InferenceObject.keys,
];
const stray = Object.keys(value).find((key) => !vectorKeys.includes(key));
if (stray !== undefined || Object.keys(value).length === 0) {
refuse(
`${where} is not a query Qdrant reads: a query is a vector, a point id, {"indices", "values"}, or one of ${QUERY_FORMS.join(", ")}${stray === undefined ? "" : `; found the key ${shown(stray)}`}.`,
stray ?? "query",
);
}
readVectorInput(walk, value, where, using);
return { form: "vector", mmrCandidates: null };
}
if (forms.length > 1) refuse(`${where} holds ${forms.join(" and ")}: a query takes one form.`, forms[1]);
const form = forms[0];
const inner = `${where}.${form}`;
let mmrCandidates: number | null = null;
if (form === "nearest") {
closed(value, "NearestQuery", where);
readVectorInput(walk, value.nearest, inner, using);
if (has(value, "mmr")) {
const mmr = objectAt(value.mmr, `${where}.mmr`);
closed(mmr, "Mmr", `${where}.mmr`);
if (has(mmr, "diversity")) numberAt(mmr.diversity, `${where}.mmr.diversity`);
if (has(mmr, "candidates_limit")) {
mmrCandidates = integerAt(
mmr.candidates_limit,
`${where}.mmr.candidates_limit`,
1,
QDRANT_BOUNDS.maxMmrCandidates,
);
}
}
return { form, mmrCandidates };
}
if (form === "recommend") {
closed(value, "RecommendQuery", where);
const recommend = objectAt(value.recommend, inner);
closed(recommend, "RecommendInput", inner);
for (const side of ["positive", "negative"]) {
if (!has(recommend, side)) continue;
listAt(recommend[side], `${inner}.${side}`).forEach((example, index) => {
readVectorInput(walk, example, `${inner}.${side}[${index}]`, using);
});
}
if (has(recommend, "strategy")) wordAt(recommend.strategy, `${inner}.strategy`, QDRANT_ENUMS.RecommendStrategy);
return { form, mmrCandidates };
}
if (form === "discover") {
closed(value, "DiscoverQuery", where);
const discover = objectAt(value.discover, inner);
closed(discover, "DiscoverInput", inner);
readVectorInput(walk, discover.target, `${inner}.target`, using);
readContext(walk, discover.context, `${inner}.context`, using);
return { form, mmrCandidates };
}
if (form === "context") {
closed(value, "ContextQuery", where);
readContext(walk, value.context, inner, using);
return { form, mmrCandidates };
}
if (form === "order_by") {
closed(value, "OrderByQuery", where);
readOrderBy(value.order_by, inner);
return { form, mmrCandidates };
}
if (form === "fusion") {
closed(value, "FusionQuery", where);
return {
form: wordAt(value.fusion, inner, QDRANT_ENUMS.Fusion) === "rrf" ? "fusion.rrf" : "fusion.dbsf",
mmrCandidates,
};
}
if (form === "rrf") {
closed(value, "RrfQuery", where);
const rrf = objectAt(value.rrf, inner);
closed(rrf, "Rrf", inner);
if (has(rrf, "k")) integerAt(rrf.k, `${inner}.k`, 1, Number.MAX_SAFE_INTEGER);
if (has(rrf, "weights")) {
listAt(rrf.weights, `${inner}.weights`).forEach((weight, index) => {
numberAt(weight, `${inner}.weights[${index}]`);
});
walk.gates.add("rrfWeights");
}
return { form, mmrCandidates };
}
if (form === "formula") {
closed(value, "FormulaQuery", where);
readExpression(walk, value.formula, inner, { nodes: 0 }, 1);
if (has(value, "defaults")) objectAt(value.defaults, `${where}.defaults`);
return { form, mmrCandidates };
}
if (form === "sample") {
closed(value, "SampleQuery", where);
wordAt(value.sample, inner, QDRANT_ENUMS.Sample);
return { form, mmrCandidates };
}
closed(value, "RelevanceFeedbackQuery", where);
walk.gates.add("relevanceFeedback");
const feedback = objectAt(value.relevance_feedback, inner);
closed(feedback, "RelevanceFeedbackInput", inner);
readVectorInput(walk, feedback.target, `${inner}.target`, using);
listAt(feedback.feedback, `${inner}.feedback`).forEach((entry, index) => {
const item = objectAt(entry, `${inner}.feedback[${index}]`);
closed(item, "FeedbackItem", `${inner}.feedback[${index}]`);
readVectorInput(walk, item.example, `${inner}.feedback[${index}].example`, using);
numberAt(item.score, `${inner}.feedback[${index}].score`);
});
const strategy = objectAt(feedback.strategy, `${inner}.strategy`);
closed(strategy, "NaiveFeedbackStrategy", `${inner}.strategy`);
closed(objectAt(strategy.naive, `${inner}.strategy.naive`), "NaiveFeedbackStrategyParams", `${inner}.strategy.naive`);
return { form: "relevance_feedback", mmrCandidates };
}
function readShardKey(value: TaggedJson, where: string): void {
const one = (key: TaggedJson | undefined, at: string): void => {
if (typeof key === "string") return;
if (key === undefined || !isTaggedInt(key) || !checkIntRange(key, "uint64")) {
refuse(`${at} must be a shard key, a string or an unsigned integer, found ${kindOf(key)}.`, "shard_key");
}
};
if (Array.isArray(value)) {
value.forEach((key, index) => {
one(key, `${where}[${index}]`);
});
} else if (isObject(value)) {
closed(value, "ShardKeyWithFallback", where);
one(value.target, `${where}.target`);
one(value.fallback, `${where}.fallback`);
} else one(value, where);
}
function readWithPayload(value: TaggedJson, where: string): void {
if (typeof value === "boolean") return;
if (Array.isArray(value)) {
value.forEach((key, index) => {
stringAt(key, `${where}[${index}]`);
});
return;
}
const selector = objectAt(value, where);
const form = Object.hasOwn(selector, "exclude") ? "exclude" : "include";
closed(selector, form === "exclude" ? "PayloadSelectorExclude" : "PayloadSelectorInclude", where);
listAt(selector[form], `${where}.${form}`).forEach((key, index) => {
stringAt(key, `${where}.${form}[${index}]`);
});
}
function readWithVector(value: TaggedJson, where: string): void {
if (typeof value === "boolean") return;
listAt(value, where).forEach((name, index) => {
stringAt(name, `${where}[${index}]`);
});
}
/** The search parameters of one stage; the oversampling it asks for, 1 where it asks for none. */
function readParams(walk: Walk, value: TaggedJson, where: string): number {
const params = objectAt(value, where);
closed(params, "SearchParams", where);
if (has(params, "hnsw_ef")) integerAt(params.hnsw_ef, `${where}.hnsw_ef`, 1, QDRANT_BOUNDS.maxHnswEf);
if (has(params, "acorn")) closed(objectAt(params.acorn, `${where}.acorn`), "AcornSearchParams", `${where}.acorn`);
if (has(params, "idf")) {
walk.gates.add("paramsIdf");
if (isObject(params.idf)) {
closed(params.idf, "IdfCorpusParams", `${where}.idf`);
walk.filter(params.idf.corpus, `${where}.idf.corpus`);
} else wordAt(params.idf, `${where}.idf`, QDRANT_ENUMS.IdfScope);
}
if (!has(params, "quantization")) return 1;
const quantization = objectAt(params.quantization, `${where}.quantization`);
closed(quantization, "QuantizationSearchParams", `${where}.quantization`);
if (!has(quantization, "oversampling")) return 1;
const oversampling = numberAt(quantization.oversampling, `${where}.quantization.oversampling`);
if (!(oversampling >= 1 && oversampling <= QDRANT_BOUNDS.maxOversampling)) {
refuse(
`${where}.quantization.oversampling is ${oversampling}; it takes a number from 1 to ${QDRANT_BOUNDS.maxOversampling}.`,
"oversampling",
);
}
return oversampling;
}
/** The keys a query, a prefetch entry and a grouped query share; what the stage is and what it costs. */
function readStage(
walk: Walk,
stage: TaggedObject,
where: string,
depth: number,
rows: (limit: number | null) => { readonly limit: number; readonly offset: number },
): QdrantSearch {
const at = (key: string) => (where === "" ? key : `${where}.${key}`);
const using = has(stage, "using") ? vectorNameAt(stage.using, at("using")) : "";
if (has(stage, "filter")) walk.filter(stage.filter, at("filter"));
const oversampling = has(stage, "params") ? readParams(walk, stage.params, at("params")) : 1;
if (has(stage, "score_threshold")) numberAt(stage.score_threshold, at("score_threshold"));
if (has(stage, "lookup_from")) {
const lookup = objectAt(stage.lookup_from, at("lookup_from"));
closed(lookup, "LookupLocation", at("lookup_from"));
const collection = collectionNameAt(lookup.collection, at("lookup_from.collection"));
const vector = has(lookup, "vector") ? vectorNameAt(lookup.vector, at("lookup_from.vector")) : using;
if (has(lookup, "shard_key")) readShardKey(lookup.shard_key, at("lookup_from.shard_key"));
walk.lookups.add(collection);
walk.usings.push({ where: at("lookup_from.vector"), using: vector, needed: true, collection });
}
if (has(stage, "prefetch")) {
if (depth + 1 > QDRANT_BOUNDS.maxPrefetchDepth) {
refuse(
`${at("prefetch")} nests prefetch more than ${QDRANT_BOUNDS.maxPrefetchDepth} levels deep, the console's bound.`,
"prefetch",
);
}
const entries = Array.isArray(stage.prefetch) ? (stage.prefetch as readonly TaggedJson[]) : [stage.prefetch];
if (entries.length > QDRANT_BOUNDS.maxPrefetchPerList) {
refuse(
`${at("prefetch")} holds ${entries.length} entries, above the bound of ${QDRANT_BOUNDS.maxPrefetchPerList} in one list.`,
"prefetch",
);
}
entries.forEach((entry, index) => {
const inner = Array.isArray(stage.prefetch) ? `${at("prefetch")}[${index}]` : at("prefetch");
const prefetch = objectAt(entry, inner);
closed(prefetch, "Prefetch", inner);
walk.prefetchNodes += 1;
if (walk.prefetchNodes > QDRANT_BOUNDS.maxPrefetchNodes) {
refuse(
`The request holds more than ${QDRANT_BOUNDS.maxPrefetchNodes} prefetch entries in all, every search counted together, the console's bound.`,
"prefetch",
);
}
readStage(walk, prefetch, inner, depth + 1, (limit) => ({
limit: limit ?? QDRANT_BOUNDS.countedPrefetchLimit,
offset: 0,
}));
});