revector 0.6.0

Declarative, versioned schema & config migrations for Qdrant — Alembic for vector collections.
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
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
//! Declarative spec types — the on-disk vocabulary for describing Qdrant
//! schema and config.
//!
//! These types are deliberately decoupled from `qdrant-client`: they are the
//! stable, serde-friendly surface that users author in YAML. The executor
//! ([`crate::ops`]) translates them into client calls. Keeping the file format
//! independent of the client crate means a `qdrant-client` upgrade can't
//! silently change the meaning of a committed migration.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::version::{self, require, VersionRequirement};

/// Distance metric for a vector field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum Distance {
    Cosine,
    Euclid,
    Dot,
    Manhattan,
}

/// Storage datatype for vector elements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Datatype {
    Float32,
    Uint8,
    Float16,
    /// TurboQuant 4-bit storage (Qdrant 1.18.2+).
    Turbo4,
    /// TurboQuant 8-bit storage (Qdrant 1.20+).
    Turbo8,
    /// TurboQuant 16-bit storage (Qdrant 1.20+).
    Turbo16,
}

/// Where a component's data is held in RAM (Qdrant 1.19+).
///
/// Data is always persisted on disk regardless of this setting; `memory` only
/// controls caching behaviour. It supersedes the older `on_disk` /
/// `always_ram` booleans, which Qdrant still accepts but now marks deprecated —
/// when both are set, `memory` wins. revector keeps emitting whichever of the
/// two a migration declared, so a file committed against 1.18 keeps its exact
/// meaning.
///
/// Qdrant rejects `pinned` for dense vector storage and for the payload store.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Memory {
    /// Not pre-loaded; cached lazily as it is used.
    Cold,
    /// Pre-loaded into the disk cache on start, evictable under pressure.
    Cached,
    /// Held in RAM and never evicted.
    Pinned,
}

impl Memory {
    /// The name used in YAML, for diff and error output.
    pub fn as_str(&self) -> &'static str {
        match self {
            Memory::Cold => "cold",
            Memory::Cached => "cached",
            Memory::Pinned => "pinned",
        }
    }
}

/// Configuration for a single (dense) named vector.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VectorSpec {
    /// Dimensionality. Immutable once created — changing it requires the
    /// add-vector → re-embed → drop-old dance.
    pub size: u64,
    /// Distance metric. Also immutable in place.
    pub distance: Distance,
    /// Store vectors on disk rather than in RAM. Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_disk: Option<bool>,
    /// Memory placement of the vector storage (Qdrant 1.19+). `pinned` is not
    /// supported for dense vectors.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
    /// Per-vector HNSW overrides.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hnsw_config: Option<HnswConfigSpec>,
    /// Per-vector quantization overrides.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quantization_config: Option<QuantizationSpec>,
    /// Element storage type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub datatype: Option<Datatype>,
}

/// How sparse vector indexes are stored.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SparseVectorSpec {
    /// Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_disk: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub full_scan_threshold: Option<u64>,
    /// Memory placement of the inverted index (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

/// HNSW index parameters. All fields optional — only the ones set are sent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HnswConfigSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub m: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ef_construct: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub full_scan_threshold: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_indexing_threads: Option<u64>,
    /// Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_disk: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload_m: Option<u64>,
    /// Memory placement of the HNSW graph (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

/// Quantization configuration. Exactly one variant should be set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QuantizationSpec {
    Scalar(ScalarQuantizationSpec),
    Product(ProductQuantizationSpec),
    Binary(BinaryQuantizationSpec),
    Turboquant(TurboquantQuantizationSpec),
    /// Explicitly disable quantization (used by `update_collection`).
    Disabled,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScalarQuantizationSpec {
    /// Quantization type. Only `int8` exists today.
    #[serde(default = "default_int8")]
    pub r#type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quantile: Option<f32>,
    /// Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub always_ram: Option<bool>,
    /// Memory placement of the quantized vectors (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

fn default_int8() -> String {
    "int8".to_string()
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProductQuantizationSpec {
    /// Compression ratio: `x4`, `x8`, `x16`, `x32`, `x64`.
    pub compression: String,
    /// Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub always_ram: Option<bool>,
    /// Memory placement of the quantized vectors (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BinaryQuantizationSpec {
    /// Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub always_ram: Option<bool>,
    /// Memory placement of the quantized vectors (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TurboquantQuantizationSpec {
    /// Bits per component: `1`, `1.5`, `2`, `4`, or `8`. Omitted → server default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bits: Option<String>,
    /// Superseded by `memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub always_ram: Option<bool>,
    /// Memory placement of the quantized vectors (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

/// Optimizer thresholds and behaviour.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OptimizersConfigSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted_threshold: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vacuum_min_vector_number: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_segment_number: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_segment_size: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memmap_threshold: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub indexing_threshold: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flush_interval_sec: Option<u64>,
}

/// Memory placement of the point ID mapping in indexed segments (Qdrant 1.20+).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IdTrackerSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

/// Ranking configuration for a full-text index (Qdrant 1.20+).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum TextScoringSpec {
    Bm25 {},
}

/// Field types for payload indexes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PayloadSchemaType {
    Keyword,
    Integer,
    Float,
    Geo,
    Text,
    Bool,
    Datetime,
    Uuid,
}

impl PayloadSchemaType {
    /// The name used in YAML, for error messages that quote the file.
    pub fn as_str(&self) -> &'static str {
        match self {
            PayloadSchemaType::Keyword => "keyword",
            PayloadSchemaType::Integer => "integer",
            PayloadSchemaType::Float => "float",
            PayloadSchemaType::Geo => "geo",
            PayloadSchemaType::Text => "text",
            PayloadSchemaType::Bool => "bool",
            PayloadSchemaType::Datetime => "datetime",
            PayloadSchemaType::Uuid => "uuid",
        }
    }
}

/// Payload storage configuration (Qdrant 1.19+) — the successor to the
/// collection-level `on_disk_payload` flag.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadStorageSpec {
    /// Memory placement of the payload store. `pinned` is not supported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

/// Tokenizer used by a `text` payload index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tokenizer {
    Prefix,
    Whitespace,
    Word,
    Multilingual,
    /// Split code identifiers on underscores and case changes (Qdrant 1.20+).
    Code,
}

/// Stopword configuration for a `text` payload index.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StopwordsSpec {
    /// Built-in stopword lists to apply, by language name.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub languages: Vec<String>,
    /// Extra stopwords to apply on top of the built-in lists.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom: Vec<String>,
}

/// Stemming algorithm for a `text` payload index.
///
/// ```yaml
/// stemmer: { snowball: english }   # Snowball stemmer for a language
/// stemmer: disabled                # opt out of the language default (1.19+)
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StemmerSpec {
    /// Snowball stemmer for the named language.
    Snowball(String),
    /// Explicitly disable stemming, overriding the language default (Qdrant 1.19+).
    Disabled,
}

/// Tuning knobs for a payload index.
///
/// Qdrant models these as a per-field-type union, but the field type is already
/// named by the operation's `schema:`, so revector keeps the YAML flat and
/// checks applicability instead: setting a field that the chosen type doesn't
/// accept is a validation error rather than a silently dropped setting.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadIndexParamsSpec {
    /// Array path whose elements are indexed separately, e.g. `offers`
    /// for `offers[].price` (Qdrant 1.20+). All types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nested: Option<String>,
    /// Enable full-text ranking (Qdrant 1.20+). `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scoring: Option<TextScoringSpec>,
    /// Store the index on disk. Superseded by `memory`. All types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_disk: Option<bool>,
    /// Memory placement of the index (Qdrant 1.19+). All types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
    /// Build payload-aware HNSW links for this field (needs `payload_m > 0`).
    /// All types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enable_hnsw: Option<bool>,
    /// Optimize storage for multitenancy on this field. `keyword`, `uuid`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_tenant: Option<bool>,
    /// Organize collection storage by this field. `integer`, `float`, `datetime`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_principal: Option<bool>,
    /// Enable `match: { prefix: … }` filtering (Qdrant 1.19+). `keyword` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<bool>,
    /// Support direct lookups. `integer` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lookup: Option<bool>,
    /// Support range filters. `integer` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub range: Option<bool>,
    /// Tokenizer. `text` only — required when a `text` index declares params.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tokenizer: Option<Tokenizer>,
    /// Lowercase all tokens. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lowercase: Option<bool>,
    /// Minimum token length. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_token_len: Option<u64>,
    /// Maximum token length. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_token_len: Option<u64>,
    /// Support phrase matching. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phrase_matching: Option<bool>,
    /// Fold accented characters to ASCII. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ascii_folding: Option<bool>,
    /// Stopwords to drop when tokenizing. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stopwords: Option<StopwordsSpec>,
    /// Stemming algorithm. `text` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stemmer: Option<StemmerSpec>,
}

/// Params every payload index type accepts.
const COMMON_INDEX_PARAMS: &[&str] = &["on_disk", "memory", "enable_hnsw", "nested"];

impl PayloadIndexParamsSpec {
    /// The params this spec actually sets, by YAML field name.
    fn set_fields(&self) -> Vec<&'static str> {
        let mut set = Vec::new();
        let mut push = |name, is_set| {
            if is_set {
                set.push(name);
            }
        };
        push("nested", self.nested.is_some());
        push("scoring", self.scoring.is_some());
        push("on_disk", self.on_disk.is_some());
        push("memory", self.memory.is_some());
        push("enable_hnsw", self.enable_hnsw.is_some());
        push("is_tenant", self.is_tenant.is_some());
        push("is_principal", self.is_principal.is_some());
        push("prefix", self.prefix.is_some());
        push("lookup", self.lookup.is_some());
        push("range", self.range.is_some());
        push("tokenizer", self.tokenizer.is_some());
        push("lowercase", self.lowercase.is_some());
        push("min_token_len", self.min_token_len.is_some());
        push("max_token_len", self.max_token_len.is_some());
        push("phrase_matching", self.phrase_matching.is_some());
        push("ascii_folding", self.ascii_folding.is_some());
        push("stopwords", self.stopwords.is_some());
        push("stemmer", self.stemmer.is_some());
        set
    }

    /// The params accepted on top of [`COMMON_INDEX_PARAMS`] for a field type.
    fn extra_fields(schema: PayloadSchemaType) -> &'static [&'static str] {
        match schema {
            PayloadSchemaType::Keyword => &["is_tenant", "prefix"],
            PayloadSchemaType::Uuid => &["is_tenant"],
            PayloadSchemaType::Integer => &["is_principal", "lookup", "range"],
            PayloadSchemaType::Float | PayloadSchemaType::Datetime => &["is_principal"],
            PayloadSchemaType::Geo | PayloadSchemaType::Bool => &[],
            PayloadSchemaType::Text => &[
                "scoring",
                "tokenizer",
                "lowercase",
                "min_token_len",
                "max_token_len",
                "phrase_matching",
                "ascii_folding",
                "stopwords",
                "stemmer",
            ],
        }
    }

    /// Reject params the chosen field type doesn't accept.
    ///
    /// Run at parse time so a typo fails `revector validate` offline instead of
    /// halfway through an `up` against a live server.
    pub fn validate_for(&self, schema: PayloadSchemaType) -> Result<()> {
        let extra = Self::extra_fields(schema);
        let rejected: Vec<&str> = self
            .set_fields()
            .into_iter()
            .filter(|f| !COMMON_INDEX_PARAMS.contains(f) && !extra.contains(f))
            .collect();
        if !rejected.is_empty() {
            let mut accepted = COMMON_INDEX_PARAMS.to_vec();
            accepted.extend_from_slice(extra);
            return Err(Error::InvalidOperation(format!(
                "payload index params {rejected:?} do not apply to a `{}` field \
                 (accepted: {accepted:?})",
                schema.as_str()
            )));
        }
        // Qdrant's text index params carry the tokenizer as a required field, so
        // there is no "leave it to the server" value we could send.
        if schema == PayloadSchemaType::Text && self.tokenizer.is_none() {
            return Err(Error::InvalidOperation(
                "a `text` payload index with `params` must set `tokenizer` \
                 (prefix | whitespace | word | multilingual | code)"
                    .to_string(),
            ));
        }
        Ok(())
    }
}

/// A full collection specification, used both for `create_collection` ops and
/// as the declared desired state for `diff`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CollectionSpec {
    /// Named dense vectors. A single-vector collection uses one entry, by
    /// convention keyed `""` or any chosen name.
    #[serde(default)]
    pub vectors: IndexMap<String, VectorSpec>,
    /// Named sparse vectors.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub sparse_vectors: IndexMap<String, SparseVectorSpec>,
    /// Collection-level HNSW defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hnsw_config: Option<HnswConfigSpec>,
    /// Collection-level quantization defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quantization_config: Option<QuantizationSpec>,
    /// Optimizer configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub optimizers_config: Option<OptimizersConfigSpec>,
    /// Number of shards (immutable after create on single-node).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shard_number: Option<u32>,
    /// Replication factor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replication_factor: Option<u32>,
    /// Write consistency factor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_consistency_factor: Option<u32>,
    /// Store the whole collection payload on disk. Superseded by
    /// `payload.memory`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_disk_payload: Option<bool>,
    /// Payload storage configuration (Qdrant 1.19+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload: Option<PayloadStorageSpec>,
    /// Memory placement of the point ID mapping (Qdrant 1.20+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id_tracker: Option<IdTrackerSpec>,
}

// --- Minimum server version -------------------------------------------------
//
// Each spec reports the oldest Qdrant that understands the fields it sets, so
// the runner can refuse before a newer-than-the-server setting is silently
// dropped on the wire. See [`crate::version`] for why this matters.

impl Datatype {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        let (version, name) = match self {
            Datatype::Turbo4 => (version::TURBO4_DATATYPE, "turbo4"),
            Datatype::Turbo8 => (version::QDRANT_1_20, "turbo8"),
            Datatype::Turbo16 => (version::QDRANT_1_20, "turbo16"),
            _ => return,
        };
        require(out, version, format!("`datatype: {name}` on {path}"));
    }
}

impl IdTrackerSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        require(out, version::QDRANT_1_20, format!("`{path}` block"));
    }
}

impl VectorSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        if self.memory.is_some() {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`memory` on {path}"),
            );
        }
        if let Some(datatype) = self.datatype {
            datatype.version_requirements(path, out);
        }
        if let Some(h) = &self.hnsw_config {
            h.version_requirements(&format!("{path}.hnsw_config"), out);
        }
        if let Some(q) = &self.quantization_config {
            q.version_requirements(&format!("{path}.quantization_config"), out);
        }
    }
}

impl HnswConfigSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        if self.memory.is_some() {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`memory` on {path}"),
            );
        }
    }
}

impl SparseVectorSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        if self.memory.is_some() {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`memory` on {path}"),
            );
        }
    }
}

impl QuantizationSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        if let QuantizationSpec::Turboquant(t) = self {
            if t.bits.as_deref() == Some("8") {
                require(out, version::QDRANT_1_20, format!("`bits: 8` on {path}"));
            }
        }
        let memory = match self {
            QuantizationSpec::Scalar(s) => s.memory,
            QuantizationSpec::Product(p) => p.memory,
            QuantizationSpec::Binary(b) => b.memory,
            QuantizationSpec::Turboquant(t) => t.memory,
            QuantizationSpec::Disabled => None,
        };
        if memory.is_some() {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`memory` on {path}"),
            );
        }
    }
}

impl PayloadStorageSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        // The block itself is 1.19-only, so its mere presence is the requirement.
        require(out, version::MEMORY_PLACEMENT, format!("`{path}` block"));
    }
}

impl PayloadIndexParamsSpec {
    pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
        if self.nested.is_some() {
            require(out, version::QDRANT_1_20, format!("`nested` on {path}"));
        }
        if self.scoring.is_some() {
            require(out, version::QDRANT_1_20, format!("`scoring` on {path}"));
        }
        if self.tokenizer == Some(Tokenizer::Code) {
            require(
                out,
                version::QDRANT_1_20,
                format!("`tokenizer: code` on {path}"),
            );
        }
        if self.memory.is_some() {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`memory` on {path}"),
            );
        }
        if self.prefix == Some(true) {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`prefix` on {path}"),
            );
        }
        if self.stemmer == Some(StemmerSpec::Disabled) {
            require(
                out,
                version::MEMORY_PLACEMENT,
                format!("`stemmer: disabled` on {path}"),
            );
        }
    }
}

impl CollectionSpec {
    pub fn version_requirements(&self, out: &mut Vec<VersionRequirement>) {
        for (name, v) in &self.vectors {
            let display = if name.is_empty() { "<default>" } else { name };
            v.version_requirements(&format!("vectors.{display}"), out);
        }
        for (name, s) in &self.sparse_vectors {
            s.version_requirements(&format!("sparse_vectors.{name}"), out);
        }
        if let Some(h) = &self.hnsw_config {
            h.version_requirements("hnsw_config", out);
        }
        if let Some(q) = &self.quantization_config {
            q.version_requirements("quantization_config", out);
        }
        if let Some(p) = &self.payload {
            p.version_requirements("payload", out);
        }
        if let Some(id) = &self.id_tracker {
            id.version_requirements("id_tracker", out);
        }
    }
}