qql-edge 0.4.2

Embedded QQL executor backed by qdrant-edge and optional local FastEmbed inference
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
//! `QdrantOps` trait implementation for the in-process edge backend.
//!
//! Split out of `backend/mod.rs`; the parent module keeps the `EdgeQdrant`
//! type, shard opening, and inherent query/mutation helpers (all visible to
//! this child module).

use super::*;

#[async_trait]
impl QdrantOps for EdgeQdrant {
    async fn close(&self) -> Result<(), QqlError> {
        EdgeQdrant::close(self).await
    }

    async fn list_collections(&self) -> Result<Vec<String>, QqlError> {
        let path = self.base_path.clone();
        tokio::task::spawn_blocking(move || -> Result<Vec<String>, QqlError> {
            let mut cols = Vec::new();
            if !path.exists() {
                return Ok(cols);
            }
            let mut dir = std::fs::read_dir(&path).map_err(|e| {
                QqlError::execution(
                    "QQL-EDGE-READ-DIR",
                    format!("failed to read collections directory: {e}"),
                    None,
                )
            })?;
            while let Some(entry) = dir.next().transpose().map_err(|e| {
                QqlError::execution(
                    "QQL-EDGE-DIR-ENTRY",
                    format!("failed to read directory entry: {e}"),
                    None,
                )
            })? {
                if entry.file_type().map(|t| t.is_dir()).unwrap_or(false)
                    && entry.path().join("segments").is_dir()
                    && let Some(name) = entry.file_name().to_str()
                    && !name.starts_with('.')
                {
                    cols.push(name.to_string());
                }
            }
            cols.sort();
            Ok(cols)
        })
        .await
        .map_err(|e| spawn_error("list_collections", e))?
    }

    async fn collection_exists(&self, name: &str) -> Result<bool, QqlError> {
        Ok(self.collection_path(name).join("segments").exists())
    }

    async fn get_collection_info(&self, name: &str) -> Result<CollectionInfo, QqlError> {
        let shard = self.open_shard(name).await?;
        let info = shard
            .info()
            .map_err(|e| edge_err(EdgeOp::Info, Some(name), e))?;
        let cfg = shard.config();
        let dense_vectors = cfg
            .vectors
            .keys()
            .filter(|name| !name.is_empty())
            .cloned()
            .collect();
        // Collection name for fail-closed introspection errors below; the
        // vector closure shadows `name` with the vector name.
        let collection = name;
        let vectors = cfg
            .vectors
            .iter()
            .map(|(name, params)| -> Result<_, QqlError> {
                Ok(qql::backend::VectorSpec {
                name: (!name.is_empty()).then(|| name.clone()),
                size: params.size as u64,
                distance: match params.distance {
                    qdrant_edge::Distance::Cosine => "Cosine",
                    qdrant_edge::Distance::Dot => "Dot",
                    qdrant_edge::Distance::Euclid => "Euclid",
                    qdrant_edge::Distance::Manhattan => "Manhattan",
                }
                .to_string(),
                hnsw: params
                    .hnsw_config
                    .map(|hnsw| {
                        let value = serde_json::to_value(hnsw).map_err(|error| {
                            info_config_error(
                                collection,
                                format!(
                                    "failed to serialize HNSW config for collection info: {error}"
                                ),
                            )
                        })?;
                        value.as_object().cloned().ok_or_else(|| {
                            info_config_error(
                                collection,
                                "HNSW config serialized to a non-object for collection info",
                            )
                        })
                    })
                    .transpose()?,
                quantization: params
                    .quantization_config
                    .as_ref()
                    .map(|quant| {
                        serde_json::to_value(quant).map_err(|error| {
                            info_config_error(
                                collection,
                                format!(
                                    "failed to serialize quantization config for collection info: {error}"
                                ),
                            )
                        })
                    })
                    .transpose()?,
                multivector: params.multivector_config.as_ref().map(|mv| {
                    let mut map = serde_json::Map::new();
                    map.insert(
                        "comparator".into(),
                        serde_json::Value::String(match mv.comparator {
                            qdrant_edge::MultiVectorComparator::MaxSim => "max_sim".into(),
                        }),
                    );
                    map
                }),
                on_disk: params.on_disk,
                datatype: params.datatype.map(|dt| {
                    match dt {
                        qdrant_edge::VectorStorageDatatype::Float32 => "float32",
                        qdrant_edge::VectorStorageDatatype::Float16 => "float16",
                        qdrant_edge::VectorStorageDatatype::Uint8 => "uint8",
                        qdrant_edge::VectorStorageDatatype::Turbo4 => "turbo4",
                    }
                    .to_string()
                }),
                memory: None,
                })
            })
            .collect::<Result<Vec<_>, QqlError>>()?;
        let sparse_vectors = cfg
            .sparse_vectors
            .iter()
            .map(|(name, params)| {
                // Engine-boundary JSON, not an envelope: `SparseVectorSpec::index`
                // is typed as an optional JSON map, so this map feeds the typed
                // constructor directly.
                let mut index = serde_json::Map::new();
                if let Some(threshold) = params.full_scan_threshold {
                    index.insert(
                        "full_scan_threshold".into(),
                        serde_json::json!(threshold as u64),
                    );
                }
                if let Some(on_disk) = params.on_disk {
                    index.insert("on_disk".into(), serde_json::Value::Bool(on_disk));
                }
                if let Some(datatype) = params.datatype {
                    index.insert(
                        "datatype".into(),
                        serde_json::Value::String(
                            match datatype {
                                qdrant_edge::VectorStorageDatatype::Float32 => "float32",
                                qdrant_edge::VectorStorageDatatype::Float16 => "float16",
                                qdrant_edge::VectorStorageDatatype::Uint8 => "uint8",
                                qdrant_edge::VectorStorageDatatype::Turbo4 => "turbo4",
                            }
                            .into(),
                        ),
                    );
                }
                qql::backend::SparseVectorSpec {
                    name: name.clone(),
                    index: (!index.is_empty()).then_some(index),
                    modifier: params.modifier.map(|modifier| match modifier {
                        qdrant_edge::Modifier::Idf => "idf".into(),
                        qdrant_edge::Modifier::None => "none".into(),
                    }),
                }
            })
            .collect();

        Ok(CollectionInfo {
            status: "green".to_string(),
            points_count: info.points_count as u64,
            indexed_vectors_count: Some(info.indexed_vectors_count as u64),
            segments_count: info.segments_count as u64,
            schema: CollectionSchema {
                dense_vectors,
                sparse_vectors,
                vectors,
                hnsw: Some(edge_hnsw_spec(&cfg.hnsw_config())),
                optimizers: Some(edge_optimizers_spec(&cfg.optimizers())),
                quantization: cfg.quantization_config.as_ref().map(edge_quantization_spec),
                params: qql::backend::CollectionParamsSpec {
                    on_disk_payload: cfg.on_disk_payload,
                    ..Default::default()
                },
                ..Default::default()
            },
        })
    }

    async fn create_collection(
        &self,
        collection_name: &str,
        req: &CreateCollectionRequest,
    ) -> Result<(), QqlError> {
        self.open_shard_inner(collection_name, Some(req), OpenMode::CreateExclusive)
            .await?;
        Ok(())
    }

    /// Apply the `ALTER COLLECTION` fields qdrant-edge can persist.
    ///
    /// qdrant-edge exposes `set_hnsw_config`, `set_vector_hnsw_config`, and
    /// `set_optimizers_config` (all persist to `edge_config.json`); per-vector
    /// fields beyond HNSW, sparse diffs, collection params, and a collection
    /// quantization diff have no setter, so they are rejected per field — only
    /// when the request actually carries them. Validation runs before any
    /// setter, so a mixed request never half-applies.
    async fn update_collection(
        &self,
        collection_name: &str,
        req: &UpdateCollectionRequest,
    ) -> Result<(), QqlError> {
        if req.params.is_some() {
            return Err(EdgeUnsupported::AlterCollectionParams.error());
        }
        if req.quantization_config.is_some() {
            return Err(EdgeUnsupported::AlterCollectionQuantization.error());
        }
        if req.strict_mode_config.is_some() {
            return Err(EdgeUnsupported::StrictMode.error());
        }
        if req.metadata.is_some() {
            return Err(EdgeUnsupported::Metadata.error());
        }
        let vector_hnsw = vector_hnsw_diffs(req)?;
        let shard = self.open_shard(collection_name).await?;
        if let Some(hnsw) = req.hnsw_config.as_ref() {
            let hnsw = edge_hnsw_config_over(hnsw, &shard.config().hnsw_config())?;
            shard
                .set_hnsw_config(hnsw)
                .map_err(|e| edge_err(EdgeOp::AlterCollection, Some(collection_name), e))?;
        }
        if let Some(optimizers) = req.optimizers_config.as_ref() {
            let optimizers = overlay_optimizers(optimizers, &shard.config().optimizers())?;
            shard
                .set_optimizers_config(optimizers)
                .map_err(|e| edge_err(EdgeOp::AlterCollection, Some(collection_name), e))?;
        }
        for (name, diff) in &vector_hnsw {
            // `set_vector_hnsw_config` replaces the whole per-vector block, so
            // merge the diff over the vector's effective config (its own, else
            // the collection-wide default), mirroring the server's field-wise
            // diff semantics. The engine stores a full per-vector config or
            // none, so the merged block pins every field: a later collection-
            // wide HNSW change no longer reaches this vector.
            let base = {
                let config = shard.config();
                config
                    .vectors
                    .get(name.as_str())
                    .and_then(|params| params.hnsw_config)
                    .unwrap_or_else(|| config.hnsw_config())
            };
            let merged = edge_hnsw_config_over(diff, &base)?;
            shard
                .set_vector_hnsw_config(name, merged)
                .map_err(|e| edge_err(EdgeOp::AlterCollection, Some(collection_name), e))?;
        }
        Ok(())
    }

    async fn delete_collection(&self, name: &str) -> Result<(), QqlError> {
        let path = self.collection_path(name);
        let shard = {
            let mut shards = self.shards.write().await;
            shards.remove(name)
        };
        {
            let mut opening = self.opening.lock().await;
            opening.remove(name);
        }
        if let Some(shard) = shard {
            tokio::task::spawn_blocking(move || drop(shard))
                .await
                .map_err(|error| {
                    QqlError::execution(
                        "QQL-EDGE-DELETE-COLLECTION-CLOSE",
                        format!("failed to close collection '{name}' before delete: {error}"),
                        None,
                    )
                    .with_collection(name.to_string())
                })?;
        }
        tokio::task::spawn_blocking(move || {
            if path.exists() {
                std::fs::remove_dir_all(&path).map_err(|e| {
                    QqlError::execution(
                        "QQL-EDGE-DELETE-COLLECTION",
                        format!("failed to delete collection directory: {e}"),
                        None,
                    )
                })
            } else {
                Ok(())
            }
        })
        .await
        .map_err(|e| spawn_error("delete_collection", e))?
    }

    async fn create_field_index(
        &self,
        collection_name: &str,
        req: &CreateIndexRequest,
    ) -> Result<(), QqlError> {
        let shard = self.open_shard(collection_name).await?;

        let field_schema = Some(edge_payload_field_schema(req)?);
        let field_name: qdrant_edge::JsonPath = serde_json::from_value(serde_json::Value::String(
            req.field_name.clone(),
        ))
        .map_err(|e| {
            QqlError::execution(
                "QQL-EDGE-FIELD-NAME",
                format!("invalid field name: {e}"),
                None,
            )
            .with_collection(collection_name.to_string())
            .with_field_name(req.field_name.clone())
        })?;

        let create_index = CreateIndex {
            field_name,
            field_schema,
        };

        let op =
            UpdateOperation::FieldIndexOperation(FieldIndexOperations::CreateIndex(create_index));

        shard
            .update(op)
            .map_err(|e| edge_err(EdgeOp::CreateIndex, Some(collection_name), e))
    }

    async fn delete_field_index(
        &self,
        collection_name: &str,
        field_name: &str,
    ) -> Result<(), QqlError> {
        let shard = self.open_shard(collection_name).await?;
        let field_name_json: qdrant_edge::JsonPath = serde_json::from_value(
            serde_json::Value::String(field_name.to_string()),
        )
        .map_err(|e| {
            QqlError::execution(
                "QQL-EDGE-FIELD-NAME",
                format!("invalid field name: {e}"),
                None,
            )
            .with_collection(collection_name.to_string())
            .with_field_name(field_name.to_string())
        })?;
        let op = UpdateOperation::FieldIndexOperation(FieldIndexOperations::DeleteIndex(
            field_name_json,
        ));
        shard
            .update(op)
            .map_err(|e| edge_err(EdgeOp::DropIndex, Some(collection_name), e))
    }

    async fn execute_planned(
        &self,
        op: &qql_plan::PlannedOperation,
    ) -> Result<BackendResponse, QqlError> {
        reject_shard_key(op.shard_key())?;
        use qql_plan::PlannedOperation::*;
        let data = match op {
            // Reads: qdrant-edge values map straight to `ExecData`.
            Query {
                collection,
                request,
            } => ExecData::Hits(self.execute_edge_query(collection, request).await?),
            QueryGroups {
                collection,
                request,
            } => ExecData::Groups(self.execute_edge_query_groups(collection, request).await?),
            GetPoints {
                collection,
                request,
            } => ExecData::Hits(self.execute_edge_points(collection, request).await?),
            Scroll {
                collection,
                request,
            } => ExecData::Hits(self.execute_edge_scroll(collection, request).await?),
            Count {
                collection,
                request,
            } => ExecData::Count(self.execute_edge_count(collection, request).await?),
            Facet {
                collection,
                request,
            } => ExecData::Facet(self.execute_edge_facet(collection, request).await?),
            // Writes: status-only. The executor owns the upsert count/message.
            Upsert {
                collection,
                request,
                ..
            } => {
                self.execute_edge_upsert(collection, request).await?;
                ExecData::Mutation { affected: None }
            }
            Delete {
                collection,
                request,
                ..
            } => {
                self.execute_edge_delete(collection, request).await?;
                ExecData::Mutation { affected: None }
            }
            UpdatePayload {
                collection,
                request,
                ..
            } => {
                self.execute_edge_update_payload(collection, request)
                    .await?;
                ExecData::Mutation { affected: None }
            }
            OverwritePayload {
                collection,
                request,
                ..
            } => {
                self.execute_edge_overwrite_payload(collection, request)
                    .await?;
                ExecData::Mutation { affected: None }
            }
            ClearPayload {
                collection,
                request,
                ..
            } => {
                self.execute_edge_clear_payload(collection, request).await?;
                ExecData::Mutation { affected: None }
            }
            DeletePayload {
                collection,
                request,
                ..
            } => {
                self.execute_edge_delete_payload(collection, request)
                    .await?;
                ExecData::Mutation { affected: None }
            }
            UpdateVectors {
                collection,
                request,
                ..
            } => {
                self.execute_edge_update_vectors(collection, request)
                    .await?;
                ExecData::Mutation { affected: None }
            }
            DeleteVectors {
                collection,
                request,
                ..
            } => {
                self.execute_edge_delete_vectors(collection, request)
                    .await?;
                ExecData::Mutation { affected: None }
            }
            // DDL: status-only. Sharding stays fail-closed; create-time params
            // are narrowed to the keys the engine can persist.
            CreateCollection {
                collection,
                request,
            } => {
                reject_collection_sharding(
                    request.shard_number,
                    request.sharding_method,
                    request.shard_keys.as_deref(),
                )?;
                reject_collection_params(request.params.as_ref())?;
                self.create_collection(collection, request).await?;
                ExecData::Mutation { affected: None }
            }
            UpdateCollection {
                collection,
                request,
            } => {
                self.update_collection(collection, request).await?;
                ExecData::Mutation { affected: None }
            }
            DropCollection { collection } => {
                self.delete_collection(collection).await?;
                ExecData::Mutation { affected: None }
            }
            CreateIndex {
                collection,
                request,
                ..
            } => {
                self.create_field_index(collection, request).await?;
                ExecData::Mutation { affected: None }
            }
            DropIndex { collection, field } => {
                self.delete_field_index(collection, field).await?;
                ExecData::Mutation { affected: None }
            }
            CreateShardKey { .. } | DropShardKey { .. } | ListShardKeys { .. } => {
                return Err(EdgeUnsupported::ShardKeyDdl.error());
            }
            // Collection metadata maps straight onto the typed variants.
            ListCollections => ExecData::Collections(self.list_collections().await?),
            GetCollection { collection } => {
                ExecData::Collection(self.get_collection_info(collection).await?)
            }
            CrossRerank { .. } => {
                return Err(EdgeUnsupported::CrossRerank.error());
            }
            Batch { .. } => {
                return Err(EdgeUnsupported::Route {
                    path_hint: "BATCH (dispatched by the Executor through the batch methods)",
                }
                .error());
            }
            GetQuotas | SetQuotas { .. } => return Err(EdgeUnsupported::Quota.error()),
        };
        Ok(BackendResponse {
            data,
            telemetry: None,
        })
    }

    async fn optimize_collection(&self, collection: &str) -> Result<bool, QqlError> {
        let shard = self.open_shard(collection).await?;
        tokio::task::spawn_blocking(move || shard.optimize())
            .await
            .map_err(|e| spawn_error("optimize", e))?
            .map_err(|e| edge_err(EdgeOp::Optimize, Some(collection), e))
    }

    async fn execute_query_batch(
        &self,
        collection: &str,
        batch: &QueryBatchRequest,
        timeout: Option<u64>,
        consistency: Option<qql_plan::types::ReadConsistencyParam>,
    ) -> Result<Vec<BackendResponse>, QqlError> {
        // Fail closed like the single-query path (`reject_request_level`):
        // the local engine has no RPC deadline and no replica levels, so a
        // batch that sets either must not silently run without it.
        if timeout.is_some() {
            return Err(EdgeUnsupported::Timeout.error());
        }
        if consistency.is_some() {
            return Err(EdgeUnsupported::Consistency.error());
        }
        for request in &batch.searches {
            reject_shard_key(request.shard_key.as_ref())?;
        }
        let mut results = Vec::with_capacity(batch.searches.len());
        for req in &batch.searches {
            results.push(BackendResponse {
                data: ExecData::Hits(self.execute_edge_query(collection, req).await?),
                telemetry: None,
            });
        }
        Ok(results)
    }

    async fn execute_update_batch(
        &self,
        collection: &str,
        batch: &UpdateBatchRequest,
        wait: bool,
    ) -> Result<Vec<BackendResponse>, QqlError> {
        // In-process execution is synchronous: every op is applied before the
        // call returns, so `wait: true` is satisfied by construction. `false`
        // is only reachable via an explicit `WAIT false` (every producer
        // defaults to `true`), which asks for fire-and-forget acknowledgement
        // the engine has no path for — fail closed instead of silently
        // over-delivering durability semantics the caller opted out of.
        if !wait {
            return Err(EdgeUnsupported::Wait.error());
        }
        let mut results = Vec::with_capacity(batch.operations.len());
        for op in &batch.operations {
            match op {
                PlanUpdateOperation::Upsert { upsert } => {
                    self.execute_edge_upsert(collection, upsert).await?;
                }
                PlanUpdateOperation::Delete { delete } => {
                    self.execute_edge_delete(collection, delete).await?;
                }
                PlanUpdateOperation::SetPayload { set_payload } => {
                    self.execute_edge_update_payload(collection, set_payload)
                        .await?;
                }
                PlanUpdateOperation::Overwrite { overwrite_payload } => {
                    self.execute_edge_overwrite_payload(collection, overwrite_payload)
                        .await?;
                }
                PlanUpdateOperation::ClearPayload { clear_payload } => {
                    self.execute_edge_clear_payload(collection, clear_payload)
                        .await?;
                }
                PlanUpdateOperation::DeletePayload { delete_payload } => {
                    self.execute_edge_delete_payload(collection, delete_payload)
                        .await?;
                }
                PlanUpdateOperation::UpdateVectors { update_vectors } => {
                    self.execute_edge_update_vectors(collection, update_vectors)
                        .await?;
                }
                PlanUpdateOperation::DeleteVectors { delete_vectors } => {
                    self.execute_edge_delete_vectors(collection, delete_vectors)
                        .await?;
                }
            }
            results.push(BackendResponse {
                data: ExecData::Mutation { affected: None },
                telemetry: None,
            });
        }
        Ok(results)
    }
}

/// Fail-closed `QQL-EDGE-CONFIG` for collection-info introspection.
///
/// Engine config types always serialize in practice, but a serialization
/// failure must surface — never silently drop the HNSW/quantization block
/// (the old `.ok()` path reported `None`, i.e. "no HNSW configured").
fn info_config_error(collection: &str, detail: impl Into<String>) -> QqlError {
    QqlError::execution("QQL-EDGE-CONFIG", detail.into(), None)
        .with_collection(collection.to_string())
}