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
//! Migration operations — the verbs a migration can perform.
//!
//! Each [`Operation`] is an internally-tagged enum: a YAML list of steps where
//! each step names its operation via an `op:` field. This reads naturally and,
//! unlike serde's externally-tagged form, doesn't require YAML `!tag` syntax:
//!
//! ```yaml
//! up:
//! - op: create_collection
//! name: products
//! spec:
//! vectors:
//! "":
//! size: 768
//! distance: Cosine
//! - op: create_payload_index
//! collection: products
//! field_name: category
//! schema: keyword
//! ```
//!
//! This module holds the *data* and the *reversibility* logic. Execution
//! against a live Qdrant lives in [`crate::executor`] so the file format stays
//! independent of the client crate.
use serde::{Deserialize, Serialize};
use crate::error::Result;
use crate::spec::{
CollectionSpec, HnswConfigSpec, Memory, OptimizersConfigSpec, PayloadIndexParamsSpec,
PayloadSchemaType, PayloadStorageSpec, QuantizationSpec, SparseVectorSpec, VectorSpec,
};
use crate::version::VersionRequirement;
/// A single migration step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Operation {
/// Create a new collection from a full spec.
CreateCollection { name: String, spec: CollectionSpec },
/// Delete a collection entirely. **Irreversible** (data loss).
DeleteCollection { name: String },
/// Patch tunable collection-level config in place.
UpdateCollection(UpdateCollectionOp),
/// Add a new named dense vector to an existing collection (v1.18+).
CreateVector {
collection: String,
name: String,
spec: VectorSpec,
},
/// Add a new named sparse vector to an existing collection.
CreateSparseVector {
collection: String,
name: String,
spec: SparseVectorSpec,
},
/// Drop a named vector. **Irreversible** (vector data loss).
DeleteVector { collection: String, name: String },
/// Create a payload field index.
CreatePayloadIndex {
collection: String,
field_name: String,
schema: PayloadSchemaType,
/// Index tuning knobs. Omitted → server defaults.
#[serde(default, skip_serializing_if = "Option::is_none")]
params: Option<PayloadIndexParamsSpec>,
},
/// Delete a payload field index. Reversible only when `schema` is supplied
/// so the index can be recreated.
DeletePayloadIndex {
collection: String,
field_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
schema: Option<PayloadSchemaType>,
/// Params to recreate the index with when this op is auto-inverted.
#[serde(default, skip_serializing_if = "Option::is_none")]
params: Option<PayloadIndexParamsSpec>,
},
/// Create an alias pointing at a collection.
CreateAlias { collection: String, alias: String },
/// Delete an alias. **Irreversible** (target not recorded).
DeleteAlias { alias: String },
/// Atomically repoint an alias to a new collection (zero-downtime swap).
/// Auto-inversion is unavailable because the previous target is not known
/// without querying; supply an explicit `down` to reverse.
SwitchAlias {
alias: String,
to_collection: String,
},
/// Shell out to a user-provided command — the escape hatch for
/// re-embedding and other data steps the binary can't own.
Exec(ExecOp),
}
/// Patchable collection-level configuration. Only the set fields are sent to
/// `update_collection`; `None` fields are left untouched.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpdateCollectionOp {
pub collection: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hnsw_config: Option<HnswConfigSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quantization_config: Option<QuantizationSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub optimizers_config: Option<OptimizersConfigSpec>,
/// Patch parameters of existing named vectors (memory/on_disk, hnsw,
/// quantization).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vectors: Option<indexmap::IndexMap<String, VectorParamsDiff>>,
/// Move the payload storage between memory tiers (Qdrant 1.19+).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload: Option<PayloadStorageSpec>,
}
/// In-place tunables for an existing named vector (size/distance excluded —
/// those are immutable).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VectorParamsDiff {
/// 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 hnsw_config: Option<HnswConfigSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quantization_config: Option<QuantizationSpec>,
/// Move the vector storage between memory tiers (Qdrant 1.19+).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory: Option<Memory>,
}
/// A shell command run as a migration step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecOp {
/// Command line, executed via `sh -c`.
pub command: String,
/// Optional human-readable label for status output.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Working directory; defaults to the project root.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workdir: Option<String>,
}
/// The outcome of asking an operation for its automatic inverse.
#[derive(Debug, Clone)]
pub enum Reversibility {
/// The inverse operation could be derived automatically. Boxed because
/// `Operation` is large relative to the `Irreversible` variant.
Auto(Box<Operation>),
/// The operation cannot be safely auto-reversed; the string explains why.
Irreversible(String),
}
impl Operation {
/// A short, human-readable description for status/log output.
pub fn describe(&self) -> String {
match self {
Operation::CreateCollection { name, .. } => format!("create collection `{name}`"),
Operation::DeleteCollection { name } => format!("delete collection `{name}`"),
Operation::UpdateCollection(op) => {
format!("update config of collection `{}`", op.collection)
}
Operation::CreateVector {
collection, name, ..
} => format!("add vector `{name}` to `{collection}`"),
Operation::CreateSparseVector {
collection, name, ..
} => format!("add sparse vector `{name}` to `{collection}`"),
Operation::DeleteVector { collection, name } => {
format!("drop vector `{name}` from `{collection}`")
}
Operation::CreatePayloadIndex {
collection,
field_name,
..
} => format!("create index on `{collection}.{field_name}`"),
Operation::DeletePayloadIndex {
collection,
field_name,
..
} => format!("drop index on `{collection}.{field_name}`"),
Operation::CreateAlias { collection, alias } => {
format!("create alias `{alias}` -> `{collection}`")
}
Operation::DeleteAlias { alias } => format!("delete alias `{alias}`"),
Operation::SwitchAlias {
alias,
to_collection,
} => format!("switch alias `{alias}` -> `{to_collection}`"),
Operation::Exec(op) => {
format!(
"exec `{}`",
op.name.clone().unwrap_or_else(|| op.command.clone())
)
}
}
}
/// Check the operation is internally consistent, without touching Qdrant.
///
/// Called when a migration file is parsed so `revector validate` — and the
/// pre-flight of every other command — rejects a bad step before any server
/// is contacted.
pub fn validate(&self) -> Result<()> {
match self {
Operation::CreatePayloadIndex {
schema,
params: Some(params),
..
} => params.validate_for(*schema)?,
// Params on a delete only exist to recreate the index on downgrade,
// which needs the schema anyway — nothing to check without it.
Operation::DeletePayloadIndex {
schema: Some(schema),
params: Some(params),
..
} => params.validate_for(*schema)?,
_ => {}
}
Ok(())
}
/// The oldest Qdrant that understands everything this operation sends.
///
/// Only fields that actually reach the wire count. [`crate::executor`]
/// drops some declarations by design — Qdrant's add-vector API takes
/// neither tuning nor placement, and a payload-index delete carries
/// `params` solely to rebuild the index on the way back up — and a
/// requirement they raised would block migrations that run fine.
pub fn version_requirements(&self) -> Vec<VersionRequirement> {
let mut out = Vec::new();
match self {
Operation::CreateCollection { spec, .. } => spec.version_requirements(&mut out),
Operation::UpdateCollection(op) => {
if let Some(h) = &op.hnsw_config {
h.version_requirements("hnsw_config", &mut out);
}
if let Some(q) = &op.quantization_config {
q.version_requirements("quantization_config", &mut out);
}
if let Some(vectors) = &op.vectors {
for (name, d) in vectors {
let display = if name.is_empty() { "<default>" } else { name };
d.version_requirements(&format!("vectors.{display}"), &mut out);
}
}
if let Some(p) = &op.payload {
p.version_requirements("payload", &mut out);
}
}
Operation::CreateVector { spec, name, .. } => {
// Only the datatype survives the add-vector API; everything
// else in the spec is warned about and dropped.
if spec.datatype == Some(crate::spec::Datatype::Turbo4) {
out.push(VersionRequirement::new(
crate::version::TURBO4_DATATYPE,
format!("`datatype: turbo4` on vector `{name}`"),
));
}
}
Operation::CreatePayloadIndex {
field_name,
params: Some(params),
..
} => params.version_requirements(&format!("`{field_name}` index params"), &mut out),
// Sparse vectors are created with server defaults, and a delete
// sends neither schema nor params.
_ => {}
}
out
}
/// Derive the operation that undoes this one, when possible.
///
/// Operations that destroy data, or that would need previous state we never
/// captured, return [`Reversibility::Irreversible`]. A migration author can
/// always override by supplying an explicit `down` block.
pub fn auto_inverse(&self) -> Reversibility {
match self {
Operation::CreateCollection { name, .. } => {
Reversibility::Auto(Box::new(Operation::DeleteCollection { name: name.clone() }))
}
Operation::DeleteCollection { name } => Reversibility::Irreversible(format!(
"deleting collection `{name}` destroys all its data; provide an explicit `down` to recreate it"
)),
Operation::UpdateCollection(op) => Reversibility::Irreversible(format!(
"config updates to `{}` are not auto-reversible (previous values unknown); provide an explicit `down`",
op.collection
)),
Operation::CreateVector {
collection, name, ..
} => Reversibility::Auto(Box::new(Operation::DeleteVector {
collection: collection.clone(),
name: name.clone(),
})),
Operation::CreateSparseVector {
collection, name, ..
} => Reversibility::Auto(Box::new(Operation::DeleteVector {
collection: collection.clone(),
name: name.clone(),
})),
Operation::DeleteVector { collection, name } => Reversibility::Irreversible(format!(
"dropping vector `{name}` from `{collection}` destroys its vector data; provide an explicit `down`"
)),
Operation::CreatePayloadIndex {
collection,
field_name,
schema,
params,
} => Reversibility::Auto(Box::new(Operation::DeletePayloadIndex {
collection: collection.clone(),
field_name: field_name.clone(),
schema: Some(*schema),
params: params.clone(),
})),
Operation::DeletePayloadIndex {
collection,
field_name,
schema,
params,
} => match schema {
Some(schema) => Reversibility::Auto(Box::new(Operation::CreatePayloadIndex {
collection: collection.clone(),
field_name: field_name.clone(),
schema: *schema,
params: params.clone(),
})),
None => Reversibility::Irreversible(format!(
"cannot recreate index on `{collection}.{field_name}` without its `schema`; add `schema:` to the op or provide an explicit `down`"
)),
},
Operation::CreateAlias { collection: _, alias } => {
Reversibility::Auto(Box::new(Operation::DeleteAlias {
alias: alias.clone(),
}))
}
Operation::DeleteAlias { alias } => Reversibility::Irreversible(format!(
"alias `{alias}`'s previous target is unknown; provide an explicit `down`"
)),
Operation::SwitchAlias { alias, .. } => Reversibility::Irreversible(format!(
"alias `{alias}`'s previous target is unknown; provide an explicit `down`"
)),
Operation::Exec(op) => Reversibility::Irreversible(format!(
"exec step `{}` has no automatic inverse; provide an explicit `down`",
op.name.clone().unwrap_or_else(|| op.command.clone())
)),
}
}
}
impl VectorParamsDiff {
/// Requirements for an in-place vector patch. Unlike [`crate::spec::VectorSpec`]
/// this is sent whole, so every field counts.
pub fn version_requirements(&self, path: &str, out: &mut Vec<VersionRequirement>) {
if self.memory.is_some() {
out.push(VersionRequirement::new(
crate::version::MEMORY_PLACEMENT,
format!("`memory` on {path}"),
));
}
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);
}
}
}