qql-core 0.4.1

Parser, typed AST, validation, and transformations for the Qdrant Query Language
Documentation
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
use super::ascii_equal;
use crate::ast::{CollectionConfig, OptimizationThreads, Value};
use crate::error::QqlError;
use alloc::string::String;

/// Looks up a config entry by key, comparing ASCII case-insensitively.
pub fn config_value<'a>(config: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
    for (k, v) in config {
        if ascii_equal(k, key) {
            return Some(v);
        }
    }
    None
}

/// Returns true when the config contains the given key (case-insensitive).
pub fn config_has_key(config: &[(String, Value)], key: &str) -> bool {
    config_value(config, key).is_some()
}

/// Reads a boolean config value, returning `None` when absent or not a bool.
pub fn config_bool(config: &[(String, Value)], key: &str) -> Option<bool> {
    match config_value(config, key)? {
        Value::Bool(b) => Some(*b),
        _ => None,
    }
}

use crate::error::Span;

fn validation_err(message: impl Into<alloc::borrow::Cow<'static, str>>, span: Span) -> QqlError {
    QqlError::validation("QQL-VALIDATION-CONFIG", message, Some(span))
}

/// Reads a positive integer config value; `None` when absent, error when invalid.
pub fn config_positive_u64(
    config: &[(String, Value)],
    key: &str,
    span: Span,
) -> Result<Option<u64>, QqlError> {
    match config_value(config, key) {
        None => Ok(None),
        Some(Value::Int(n)) if *n > 0 => Ok(Some(*n as u64)),
        Some(Value::Float(n)) if *n > 0.0 && *n == (*n as u64) as f64 => Ok(Some(*n as u64)),
        _ => Err(validation_err(
            alloc::format!("{} must be a positive integer", key),
            span,
        )),
    }
}

/// Reads a non-negative integer config value; `None` when absent, error when invalid.
pub fn config_non_negative_u64(
    config: &[(String, Value)],
    key: &str,
    span: Span,
) -> Result<Option<u64>, QqlError> {
    match config_value(config, key) {
        None => Ok(None),
        Some(Value::Int(n)) if *n >= 0 => Ok(Some(*n as u64)),
        Some(Value::Float(n)) if *n >= 0.0 && *n == (*n as u64) as f64 => Ok(Some(*n as u64)),
        _ => Err(validation_err(
            alloc::format!("{} must be a non-negative integer", key),
            span,
        )),
    }
}

/// Reads a numeric config value, or `None` when absent or outside `[min, max]`.
pub fn config_float_range(
    config: &[(String, Value)],
    key: &str,
    min: f64,
    max: f64,
) -> Option<f64> {
    match config_value(config, key)? {
        Value::Int(n) => {
            let f = *n as f64;
            if (min..=max).contains(&f) {
                Some(f)
            } else {
                None
            }
        }
        Value::Float(f) => {
            if (min..=max).contains(f) {
                Some(*f)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Reads a thread count as a positive integer or the string `auto`.
pub fn config_max_optimization_threads(
    config: &[(String, Value)],
    key: &str,
) -> Option<OptimizationThreads> {
    match config_value(config, key)? {
        Value::Int(n) if *n > 0 => Some(OptimizationThreads {
            auto_: false,
            value: *n as u64,
        }),
        Value::Str(s) if ascii_equal(s, "auto") => Some(OptimizationThreads {
            auto_: true,
            value: 0,
        }),
        _ => None,
    }
}

pub fn is_integer_val(value: &Value) -> bool {
    match value {
        Value::Int(_) => true,
        Value::Float(f) => *f >= 0.0 && *f == (*f as u64) as f64,
        _ => false,
    }
}

/// Type-checks one HNSW config option (`m`, `ef_construct`, `on_disk`, `memory`, …).
pub fn validate_hnsw_value(key: &str, value: &Value, span: Span) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "m" | "ef_construct" | "full_scan_threshold" | "max_indexing_threads" | "payload_m" => {
            if !is_integer_val(value) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    span,
                ));
            }
        }
        "on_disk" | "inline_storage" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                span,
            ));
        }
        "memory" => validate_memory_value(key, value, span, true)?,
        _ => {}
    }
    Ok(())
}

/// Type-checks one vectors config option (`on_disk`, `memory`, `datatype`).
pub fn validate_vectors_value(key: &str, value: &Value, span: Span) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "on_disk" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                span,
            ));
        }
        "memory" => validate_memory_value(key, value, span, true)?,
        "datatype" => match value {
            Value::Str(s) if crate::ast::VectorDatatype::parse(s).is_some() => {}
            Value::Str(_) => {
                return Err(validation_err(
                    alloc::format!("{key} must be float32, float16, uint8, or turbo4"),
                    span,
                ));
            }
            _ => {
                return Err(validation_err(
                    alloc::format!("{key} must be a string (float32, float16, uint8, or turbo4)"),
                    span,
                ));
            }
        },
        _ => {}
    }
    Ok(())
}

fn validate_memory_value(
    key: &str,
    value: &Value,
    span: Span,
    allow_pinned: bool,
) -> Result<(), QqlError> {
    match value {
        Value::Str(s) => match crate::ast::MemoryPlacement::parse(s) {
            Some(crate::ast::MemoryPlacement::Pinned) if !allow_pinned => Err(validation_err(
                alloc::format!("{key} does not support 'pinned'"),
                span,
            )),
            Some(_) => Ok(()),
            None => Err(validation_err(
                alloc::format!("{key} must be 'cold', 'cached', or 'pinned'"),
                span,
            )),
        },
        _ => Err(validation_err(
            alloc::format!("{key} must be a string ('cold', 'cached', or 'pinned')"),
            span,
        )),
    }
}

/// Type-checks one optimizers config option (`deleted_threshold`, `memmap_threshold`, …).
pub fn validate_optimizers_value(key: &str, value: &Value, span: Span) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "deleted_threshold" => {
            if !matches!(value, Value::Int(_) | Value::Float(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be a number", key),
                    span,
                ));
            }
        }
        "vacuum_min_vector_number"
        | "default_segment_number"
        | "max_segment_size"
        | "memmap_threshold"
        | "indexing_threshold"
        | "flush_interval_sec" => {
            if !is_integer_val(value) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    span,
                ));
            }
        }
        "max_optimization_threads" => {
            if !is_integer_val(value) && !matches!(value, Value::Str(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be a positive integer or 'auto'", key),
                    span,
                ));
            }
        }
        "prevent_unoptimized" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                span,
            ));
        }
        _ => {}
    }
    Ok(())
}

/// Type-checks one collection `PARAMS` option (replication, sharding, memory, …).
pub fn validate_params_value(key: &str, value: &Value, span: Span) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "replication_factor"
        | "write_consistency_factor"
        | "read_fan_out_factor"
        | "read_fan_out_delay_ms"
        | "shard_number" => {
            if !matches!(value, Value::Int(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    span,
                ));
            }
        }
        "on_disk_payload" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                span,
            ));
        }
        "payload_memory" => validate_memory_value(key, value, span, false)?,
        "sharding_method" => match value {
            Value::Str(s) if s.eq_ignore_ascii_case("auto") || s.eq_ignore_ascii_case("custom") => {
            }
            Value::Str(_) => {
                return Err(validation_err(
                    "sharding_method must be 'auto' or 'custom'",
                    span,
                ));
            }
            _ => {
                return Err(validation_err(
                    "sharding_method must be a string ('auto' or 'custom')",
                    span,
                ));
            }
        },
        "shard_keys" => match value {
            Value::List(items) if items.is_empty() => {
                return Err(validation_err(
                    "shard_keys must be a non-empty list of strings or non-negative integers",
                    span,
                ));
            }
            Value::List(items) => {
                for item in items {
                    let ok = match item {
                        Value::Str(_) => true,
                        Value::Int(n) => *n >= 0,
                        Value::Param(..) | Value::PositionalParam(..) => true,
                        _ => false,
                    };
                    if !ok {
                        return Err(validation_err(
                            "shard_keys entries must all be strings or non-negative integers",
                            span,
                        ));
                    }
                }
            }
            _ => {
                return Err(validation_err(
                    "shard_keys must be a list of strings or non-negative integers",
                    span,
                ));
            }
        },
        _ => {}
    }
    Ok(())
}

/// Merges new collection config clauses into `current`, erroring on duplicates.
pub fn merge_collection_config(
    current: &mut CollectionConfig,
    new: CollectionConfig,
    span: Span,
) -> Result<(), QqlError> {
    if new.vectors.is_some() {
        if current.vectors.is_some() {
            return Err(validation_err("VECTOR clause may only appear once", span));
        }
        current.vectors = new.vectors;
    }
    if new.hnsw.is_some() {
        if current.hnsw.is_some() {
            return Err(validation_err("HNSW clause may only appear once", span));
        }
        current.hnsw = new.hnsw;
    }
    if new.optimizers.is_some() {
        if current.optimizers.is_some() {
            return Err(validation_err(
                "OPTIMIZERS clause may only appear once",
                span,
            ));
        }
        current.optimizers = new.optimizers;
    }
    if new.params.is_some() {
        if current.params.is_some() {
            return Err(validation_err("PARAMS clause may only appear once", span));
        }
        current.params = new.params;
    }
    if new.quantization.is_some() {
        if current.quantization.is_some() {
            return Err(validation_err(
                "QUANTIZATION clause may only appear once",
                span,
            ));
        }
        current.quantization = new.quantization;
    }
    if new.quantization_update.is_some() {
        if current.quantization_update.is_some() {
            return Err(validation_err(
                "QUANTIZATION clause may only appear once",
                span,
            ));
        }
        current.quantization_update = new.quantization_update;
    }
    if new.wal.is_some() {
        if current.wal.is_some() {
            return Err(validation_err("WAL clause may only appear once", span));
        }
        current.wal = new.wal;
    }
    if new.strict_mode.is_some() {
        if current.strict_mode.is_some() {
            return Err(validation_err(
                "STRICT_MODE clause may only appear once",
                span,
            ));
        }
        current.strict_mode = new.strict_mode;
    }
    if new.metadata.is_some() {
        if current.metadata.is_some() {
            return Err(validation_err("METADATA clause may only appear once", span));
        }
        current.metadata = new.metadata;
    }
    for diff in new.vector_diffs {
        if current.vector_diffs.iter().any(|d| d.name == diff.name) {
            return Err(validation_err(
                alloc::format!("VECTOR diff '{}' may only appear once", diff.name),
                span,
            ));
        }
        current.vector_diffs.push(diff);
    }
    for diff in new.sparse_vector_diffs {
        if current
            .sparse_vector_diffs
            .iter()
            .any(|d| d.name == diff.name)
        {
            return Err(validation_err(
                alloc::format!("SPARSE vector diff '{}' may only appear once", diff.name),
                span,
            ));
        }
        current.sparse_vector_diffs.push(diff);
    }
    Ok(())
}

/// Checks that `deleted_threshold` is a number between 0.0 and 1.0.
pub fn check_deleted_threshold(value: &Value, span: Span) -> Result<(), QqlError> {
    match value {
        Value::Int(n) => {
            let f = *n as f64;
            if !(0.0..=1.0).contains(&f) {
                return Err(validation_err(
                    "deleted_threshold must be between 0.0 and 1.0",
                    span,
                ));
            }
        }
        Value::Float(f) if !(0.0..=1.0).contains(f) => {
            return Err(validation_err(
                "deleted_threshold must be between 0.0 and 1.0",
                span,
            ));
        }
        _ => {}
    }
    Ok(())
}

/// Type-checks CREATE INDEX options, erroring on unknown keys or bad value types.
pub fn validate_index_options(options: &[(String, Value)], span: Span) -> Result<(), QqlError> {
    for (k, v) in options {
        let lower = k.to_ascii_lowercase();
        match lower.as_str() {
            "is_tenant" | "on_disk" | "enable_hnsw" | "lowercase" | "ascii_folding"
            | "phrase_matching" | "lookup" | "range" | "is_principal" | "prefix" => {
                if !matches!(v, Value::Bool(_)) {
                    return Err(validation_err(
                        alloc::format!("{} must be true or false", k),
                        span,
                    ));
                }
            }
            "min_token_len" | "max_token_len" => {
                if !matches!(v, Value::Int(n) if *n >= 0) {
                    return Err(validation_err(
                        alloc::format!("{} must be a non-negative integer", k),
                        span,
                    ));
                }
            }
            "tokenizer" | "stemmer" => {
                if !matches!(v, Value::Str(_)) {
                    return Err(validation_err(
                        alloc::format!("{} must be a string", k),
                        span,
                    ));
                }
            }
            "memory" => validate_memory_value(k, v, span, true)?,
            "stopwords" => match v {
                Value::List(items) => {
                    for item in items {
                        if !matches!(item, Value::Str(_)) {
                            return Err(validation_err(
                                alloc::format!("{} must be a list of strings", k),
                                span,
                            ));
                        }
                    }
                }
                // A bare language name (`stopwords = 'english'`) selects the
                // predefined list; names are validated against the OpenAPI
                // `Language` enum at plan time.
                Value::Str(_) => {}
                // `stopwords = {languages: […], custom: […]}` mirrors the
                // OpenAPI `StopwordsSet` object.
                Value::Dict(entries) => {
                    for (entry_key, entry_value) in entries {
                        if entry_key.eq_ignore_ascii_case("languages") {
                            match entry_value {
                                Value::List(items) => {
                                    for item in items {
                                        if !matches!(item, Value::Str(_)) {
                                            return Err(validation_err(
                                                "stopwords languages must be a list of strings",
                                                span,
                                            ));
                                        }
                                    }
                                }
                                _ => {
                                    return Err(validation_err(
                                        "stopwords languages must be a list of strings",
                                        span,
                                    ));
                                }
                            }
                        } else if entry_key.eq_ignore_ascii_case("custom") {
                            match entry_value {
                                Value::List(items) => {
                                    for item in items {
                                        if !matches!(item, Value::Str(_)) {
                                            return Err(validation_err(
                                                "stopwords custom must be a list of strings",
                                                span,
                                            ));
                                        }
                                    }
                                }
                                _ => {
                                    return Err(validation_err(
                                        "stopwords custom must be a list of strings",
                                        span,
                                    ));
                                }
                            }
                        } else {
                            return Err(validation_err(
                                alloc::format!(
                                    "unknown stopwords set key '{entry_key}'. Expected: languages, custom"
                                ),
                                span,
                            ));
                        }
                    }
                }
                _ => {
                    return Err(validation_err(
                        alloc::format!(
                            "{} must be a list of strings, a language name, or {{languages: […], custom: […]}}",
                            k
                        ),
                        span,
                    ));
                }
            },
            _ => {
                return Err(validation_err(
                    alloc::format!("unknown index option: {}", k),
                    span,
                ));
            }
        }
    }
    Ok(())
}

/// Closed key set of `WITH STRICT_MODE (…)` (OpenAPI `StrictModeConfig`).
pub const STRICT_MODE_KEYS: &[&str] = &[
    "enabled",
    "max_query_limit",
    "max_timeout",
    "unindexed_filtering_retrieve",
    "unindexed_filtering_update",
    "search_max_hnsw_ef",
    "search_allow_exact",
    "search_max_oversampling",
    "upsert_max_batchsize",
    "search_max_batchsize",
    "max_collection_vector_size_bytes",
    "read_rate_limit",
    "write_rate_limit",
    "max_collection_payload_size_bytes",
    "max_points_count",
    "filter_max_conditions",
    "condition_max_size",
    "multivector_config",
    "sparse_config",
    "max_payload_index_count",
    "max_resident_memory_percent",
];

/// True when `key` names a `STRICT_MODE` option (case-insensitive).
pub fn is_strict_mode_key(key: &str) -> bool {
    STRICT_MODE_KEYS.iter().any(|known| ascii_equal(known, key))
}

/// Type-checks one WAL config option (`wal_capacity_mb`, …).
pub fn validate_wal_value(key: &str, value: &Value, span: Span) -> Result<(), QqlError> {
    if !matches!(value, Value::Int(_)) {
        return Err(validation_err(
            alloc::format!("{} must be an integer", key),
            span,
        ));
    }
    Ok(())
}

/// Type-checks one strict-mode config option by shape (ranges are enforced at
/// plan time so hand-built ASTs fail closed there too).
pub fn validate_strict_mode_value(key: &str, value: &Value, span: Span) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "enabled"
        | "unindexed_filtering_retrieve"
        | "unindexed_filtering_update"
        | "search_allow_exact" => {
            if !matches!(value, Value::Bool(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be true or false", key),
                    span,
                ));
            }
        }
        "search_max_oversampling" => {
            if !matches!(value, Value::Int(_) | Value::Float(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be a number", key),
                    span,
                ));
            }
        }
        "multivector_config" | "sparse_config" => {
            if !matches!(value, Value::Dict(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be an object", key),
                    span,
                ));
            }
        }
        _ => {
            if !matches!(value, Value::Int(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    span,
                ));
            }
        }
    }
    Ok(())
}