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
//! Stable catalog of product features **not available offline** (qql-edge).
//!
//! Every entry has:
//! - a fixed error code `QQL-EDGE-UNSUPPORTED-*` (or a dedicated stable code)
//! - a short "why" naming exactly what the engine lacks
//! - a remediation line pointing users at remote Qdrant when applicable
//!
//! Operational/runtime errors (spawn, path extract, filter convert) stay
//! outside this catalog.

use qql_core::error::QqlError;

/// Offline-unsupported product surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeUnsupported {
    /// `GROUP BY … LOOKUP FROM <collection>` (group-hit hydration lookup).
    GroupLookup,
    /// `SHARD '…'` on query/mutation.
    ShardRouting,
    /// Collection create/custom sharding options.
    CollectionSharding,
    /// `CREATE`/`DROP SHARD KEY`.
    ShardKeyDdl,
    /// `ALTER COLLECTION … WITH PARAMS` (no edge params setter).
    AlterCollectionParams,
    /// `ALTER COLLECTION … QUANTIZATION` (no edge quantization setter).
    AlterCollectionQuantization,
    /// `ALTER COLLECTION … WITH VECTOR <name>` fields beyond per-vector HNSW.
    AlterVectorDiff,
    /// `ALTER COLLECTION … WITH SPARSE <name>` (no edge sparse config setter).
    AlterSparseVectorDiff,
    /// Collection `WITH PARAMS` (replication, etc.) at create time.
    CollectionParams,
    /// Optimizer keys qdrant-edge deliberately excludes.
    OptimizerKey,
    /// `PARAMS (timeout = …)`.
    Timeout,
    /// `PARAMS (consistency = …)`.
    Consistency,
    /// `WAIT false` on mutation batches (no async acknowledgement path).
    Wait,
    /// `QUERY CROSS RERANK` via direct backend execution.
    CrossRerank,
    /// `SHOW QUOTAS` / `SET QUOTA`.
    Quota,
    /// `RECOMMEND … STRATEGY average_vector`.
    RecommendAverageVector,
    /// `MAX` / `MIN` / `ACOSH` formula functions (new Qdrant Expression variants).
    FormulaNary,
    /// Nearest/recommend inputs that are only point IDs (need materialised vectors offline).
    PointReferenceQuery,
    /// Catch-all unknown REST route projection.
    Route { path_hint: &'static str },
    /// `WITH WAL` (no per-collection WAL API in qdrant-edge).
    Wal,
    /// `WITH STRICT_MODE` (no strict mode policy in qdrant-edge).
    StrictMode,
    /// `WITH METADATA` (no collection metadata in qdrant-edge).
    Metadata,
}

impl EdgeUnsupported {
    pub fn code(self) -> &'static str {
        match self {
            Self::GroupLookup => "QQL-EDGE-UNSUPPORTED-GROUP-LOOKUP",
            Self::ShardRouting | Self::CollectionSharding => "QQL-EDGE-UNSUPPORTED-SHARD",
            Self::ShardKeyDdl => "QQL-EDGE-UNSUPPORTED-SHARD-KEY",
            Self::AlterCollectionParams => "QQL-EDGE-UNSUPPORTED-ALTER-PARAMS",
            Self::AlterCollectionQuantization => "QQL-EDGE-UNSUPPORTED-ALTER-QUANTIZATION",
            Self::AlterVectorDiff => "QQL-EDGE-UNSUPPORTED-VECTOR-DIFF",
            Self::AlterSparseVectorDiff => "QQL-EDGE-UNSUPPORTED-SPARSE-DIFF",
            Self::CollectionParams => "QQL-EDGE-UNSUPPORTED-COLLECTION-PARAMS",
            Self::OptimizerKey => "QQL-EDGE-UNSUPPORTED-OPTIMIZER-KEY",
            Self::Timeout => "QQL-EDGE-UNSUPPORTED-TIMEOUT",
            Self::Consistency => "QQL-EDGE-UNSUPPORTED-CONSISTENCY",
            Self::Wait => "QQL-EDGE-UNSUPPORTED-WAIT",
            Self::CrossRerank => "QQL-EDGE-UNSUPPORTED-CROSS-RERANK",
            Self::Quota => "QQL-EDGE-UNSUPPORTED-QUOTA",
            Self::RecommendAverageVector => "QQL-EDGE-UNSUPPORTED-RECOMMEND-STRATEGY",
            Self::PointReferenceQuery => "QQL-EDGE-UNSUPPORTED-POINT-REF",
            Self::FormulaNary => "QQL-EDGE-UNSUPPORTED-FORMULA-FUNCTION",
            Self::Route { .. } => "QQL-EDGE-UNSUPPORTED-ROUTE",
            Self::Wal => "QQL-EDGE-UNSUPPORTED-WAL",
            Self::StrictMode => "QQL-EDGE-UNSUPPORTED-STRICT-MODE",
            Self::Metadata => "QQL-EDGE-UNSUPPORTED-METADATA",
        }
    }

    pub fn feature(self) -> &'static str {
        match self {
            Self::GroupLookup => "GROUP BY … LOOKUP FROM",
            Self::ShardRouting => "SHARD routing",
            Self::CollectionSharding => {
                "collection sharding (shard_number / sharding_method / shard_keys)"
            }
            Self::ShardKeyDdl => "CREATE/DROP SHARD KEY",
            Self::AlterCollectionParams => "ALTER COLLECTION … WITH PARAMS",
            Self::AlterCollectionQuantization => "ALTER COLLECTION … QUANTIZATION",
            Self::AlterVectorDiff => {
                "ALTER COLLECTION … WITH VECTOR (<name>) fields other than hnsw_config"
            }
            Self::AlterSparseVectorDiff => "ALTER COLLECTION … WITH SPARSE (<name>)",
            Self::CollectionParams => "collection WITH PARAMS (replication, etc.)",
            Self::OptimizerKey => {
                "OPTIMIZERS (memmap_threshold / flush_interval_sec / max_optimization_threads)"
            }
            Self::Timeout => "PARAMS (timeout = …)",
            Self::Consistency => "PARAMS (consistency = …)",
            Self::Wait => "WAIT false on mutation batches",
            Self::CrossRerank => "QUERY CROSS RERANK",
            Self::Quota => "SHOW QUOTAS / SET QUOTA",
            Self::RecommendAverageVector => {
                "RECOMMEND STRATEGY average_vector (QQL default when STRATEGY is omitted)"
            }
            Self::PointReferenceQuery => "point-id query inputs without embedded vectors",
            Self::FormulaNary => "MAX / MIN / ACOSH formula functions",
            Self::Route { path_hint } => path_hint,
            Self::Wal => "collection WITH WAL",
            Self::StrictMode => "collection WITH STRICT_MODE",
            Self::Metadata => "collection WITH METADATA",
        }
    }

    pub fn why(self) -> &'static str {
        match self {
            Self::GroupLookup => {
                "qdrant-edge groups the queried shard only and has no lookup collection to hydrate hits from"
            }
            Self::ShardRouting => {
                "a qql-edge collection is a single qdrant-edge shard, so there is no shard to route to"
            }
            Self::CollectionSharding => {
                "qdrant-edge creates exactly one shard per collection; it has no shard_number / sharding_method / shard_keys API"
            }
            Self::ShardKeyDdl => {
                "qdrant-edge has no custom shard keys; a collection is a single shard"
            }
            Self::AlterCollectionParams => {
                "qdrant-edge persists HNSW and optimizer config after create; it exposes no collection-params setter"
            }
            Self::AlterCollectionQuantization => {
                "qdrant-edge exposes no quantization setter after create"
            }
            Self::AlterVectorDiff => {
                "qdrant-edge exposes set_vector_hnsw_config only; it has no per-vector quantization, memory, or on_disk setter"
            }
            Self::AlterSparseVectorDiff => {
                "qdrant-edge has no sparse vector config setter after create"
            }
            Self::CollectionParams => {
                "qdrant-edge persists only on_disk_payload; replication, write-consistency, fan-out, and payload-memory params have no offline equivalent"
            }
            Self::OptimizerKey => {
                "qdrant-edge has no memmap threshold, no timer flush, and runs optimizations manually"
            }
            Self::Timeout => {
                "qdrant-edge QueryRequest has no timeout field; qql-edge executes in-process with no RPC deadline"
            }
            Self::Consistency => {
                "qdrant-edge is a single-node engine with no replica consistency levels"
            }
            Self::Wait => {
                "qql-edge applies every write synchronously before returning; it has no async acknowledgement path to return before apply"
            }
            Self::CrossRerank => {
                "reranking runs client-side in the executor over scored pairs; direct backend execution has no cross-encoder path"
            }
            Self::Quota => {
                "qdrant-edge has no quotas API; Qdrant serves quotas only from the cluster REST /quotas endpoint"
            }
            Self::RecommendAverageVector => {
                "qdrant-edge QueryEnum has RecommendBestScore and RecommendSumScores only"
            }
            Self::PointReferenceQuery => {
                "qdrant-edge has no lookup_from / point-vector resolution; inputs must carry a materialized TEXT or VECTOR"
            }
            Self::FormulaNary => "qdrant-edge 0.8 Expression has no ACOSH / MAX / MIN variants",
            Self::Route { .. } => "this route has no qql-edge implementation",
            Self::Wal => {
                "qdrant-edge manages WAL segments via LocalExecutorOptions and has no per-collection WAL API"
            }
            Self::StrictMode => {
                "qdrant-edge is an embedded local engine with no server strict-mode policy enforcement"
            }
            Self::Metadata => {
                "qdrant-edge collection configs do not store arbitrary collection metadata"
            }
        }
    }

    pub fn remote_hint(self) -> Option<&'static str> {
        match self {
            Self::CollectionParams | Self::PointReferenceQuery => None,
            Self::CrossRerank => {
                Some("Run CROSS RERANK through the Executor, which scores pairs client-side")
            }
            Self::RecommendAverageVector => Some(
                "Use STRATEGY best_score or sum_scores offline, or remote Qdrant for average_vector",
            ),
            Self::Wal => Some("Use remote Qdrant (REST or gRPC) for per-collection WAL settings"),
            Self::StrictMode => {
                Some("Use remote Qdrant (REST or gRPC) for strict mode enforcement")
            }
            Self::Metadata => Some("Use remote Qdrant (REST or gRPC) for collection metadata"),
            _ => Some("Use remote Qdrant (REST or gRPC) for this feature"),
        }
    }

    pub fn message(self) -> String {
        let mut msg = format!(
            "{} is not supported offline: {}.",
            self.feature(),
            self.why()
        );
        if let Some(hint) = self.remote_hint() {
            msg.push(' ');
            msg.push_str(hint);
            msg.push('.');
        }
        msg
    }

    pub fn error(self) -> QqlError {
        QqlError::execution(self.code(), self.message(), None)
    }
}

/// Convenience: reject optional shard key on DML.
pub fn reject_shard_key<T>(shard_key: Option<T>) -> Result<(), QqlError> {
    if shard_key.is_some() {
        Err(EdgeUnsupported::ShardRouting.error())
    } else {
        Ok(())
    }
}

/// Convenience: reject collection sharding options on create.
pub fn reject_collection_sharding(
    shard_number: Option<u64>,
    sharding_method: Option<qql_plan::ShardingMethod>,
    shard_keys: Option<&[qql_plan::semantic::PlanShardKey]>,
) -> Result<(), QqlError> {
    if shard_number.is_some() || sharding_method.is_some() || shard_keys.is_some() {
        Err(EdgeUnsupported::CollectionSharding.error())
    } else {
        Ok(())
    }
}

/// Convenience: reject the create-time `WITH PARAMS` keys qdrant-edge cannot
/// persist. `on_disk_payload` **is** honored (it maps onto `EdgeConfig`), so a
/// params block carrying only that key is accepted.
pub fn reject_collection_params(
    params: Option<&qql_plan::CollectionParams>,
) -> Result<(), QqlError> {
    let unsupported = params.is_some_and(|params| {
        params.replication_factor.is_some()
            || params.write_consistency_factor.is_some()
            || params.read_fan_out_factor.is_some()
            || params.read_fan_out_delay_ms.is_some()
            || params.payload.is_some()
    });
    if unsupported {
        Err(EdgeUnsupported::CollectionParams.error())
    } else {
        Ok(())
    }
}

/// Validate the `ALTER COLLECTION` per-vector diffs for the edge backend.
///
/// Returns the dense HNSW patches to apply (name → diff). Any other dense
/// field (`quantization_config`, `on_disk`, `memory`) and every sparse diff
/// field is rejected **only when present**, with the vector name and the
/// offending key attached. A request is rejected as a whole before anything is
/// applied, so a mixed diff never half-applies.
pub fn vector_hnsw_diffs(
    request: &qql_plan::UpdateCollectionRequest,
) -> Result<Vec<(String, qql_plan::HnswConfig)>, QqlError> {
    let mut patches = Vec::new();
    if let Some(vectors) = &request.vectors {
        for (name, diff) in vectors {
            for (key, present) in [
                ("quantization_config", diff.quantization_config.is_some()),
                ("on_disk", diff.on_disk.is_some()),
                ("memory", diff.memory.is_some()),
            ] {
                if present {
                    return Err(EdgeUnsupported::AlterVectorDiff
                        .error()
                        .with_vector_name(name.clone())
                        .with_field("config_key", key));
                }
            }
            if let Some(hnsw) = &diff.hnsw_config {
                patches.push((name.clone(), hnsw.clone()));
            }
        }
    }
    if let Some(sparse) = &request.sparse_vectors {
        for (name, diff) in sparse {
            for (key, present) in [
                ("index", diff.index.is_some()),
                ("modifier", diff.modifier.is_some()),
            ] {
                if present {
                    return Err(EdgeUnsupported::AlterSparseVectorDiff
                        .error()
                        .with_vector_name(name.clone())
                        .with_field("config_key", key));
                }
            }
        }
    }
    Ok(patches)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn catalog_codes_are_stable_and_unique_for_primary_features() {
        // Exhaustive: adding a variant without extending this list fails
        // compilation, so new codes always get the uniqueness assertion.
        let features = [
            EdgeUnsupported::GroupLookup,
            EdgeUnsupported::ShardRouting,
            EdgeUnsupported::CollectionSharding,
            EdgeUnsupported::ShardKeyDdl,
            EdgeUnsupported::AlterCollectionParams,
            EdgeUnsupported::AlterCollectionQuantization,
            EdgeUnsupported::AlterVectorDiff,
            EdgeUnsupported::AlterSparseVectorDiff,
            EdgeUnsupported::CollectionParams,
            EdgeUnsupported::OptimizerKey,
            EdgeUnsupported::Timeout,
            EdgeUnsupported::Consistency,
            EdgeUnsupported::Wait,
            EdgeUnsupported::CrossRerank,
            EdgeUnsupported::Quota,
            EdgeUnsupported::RecommendAverageVector,
            EdgeUnsupported::FormulaNary,
            EdgeUnsupported::PointReferenceQuery,
            EdgeUnsupported::Route { path_hint: "test" },
            EdgeUnsupported::Wal,
            EdgeUnsupported::StrictMode,
            EdgeUnsupported::Metadata,
        ];
        let mut codes = std::collections::BTreeSet::new();
        for f in features {
            assert!(
                f.code().starts_with("QQL-EDGE-UNSUPPORTED-"),
                "{}",
                f.code()
            );
            // Collection sharding shares SHARD code with routing (same product class).
            if matches!(f, EdgeUnsupported::CollectionSharding) {
                assert_eq!(f.code(), EdgeUnsupported::ShardRouting.code());
            } else {
                assert!(codes.insert(f.code()), "duplicate code {}", f.code());
            }
            let msg = f.message();
            assert!(!msg.is_empty());
            assert!(
                msg.contains("not supported offline") || msg.contains("not supported"),
                "{msg}"
            );
            if f.remote_hint().is_some() {
                // CrossRerank remediates through the client-side Executor,
                // not remote Qdrant, so its message names the Executor.
                if matches!(f, EdgeUnsupported::CrossRerank) {
                    assert!(
                        msg.to_ascii_lowercase().contains("executor"),
                        "expected executor remediation in: {msg}"
                    );
                } else {
                    assert!(
                        msg.to_ascii_lowercase().contains("remote")
                            || msg.to_ascii_lowercase().contains("best_score"),
                        "expected remediation in: {msg}"
                    );
                }
            }
        }
    }

    #[test]
    fn group_lookup_message_names_the_engine_gap() {
        let e = EdgeUnsupported::GroupLookup.error();
        assert_eq!(e.code, "QQL-EDGE-UNSUPPORTED-GROUP-LOOKUP");
        assert!(e.message.contains("LOOKUP FROM"));
        assert!(e.message.contains("no lookup collection"));
    }

    #[test]
    fn alter_field_rejections_are_precise() {
        let params = EdgeUnsupported::AlterCollectionParams.error();
        assert_eq!(params.code, "QQL-EDGE-UNSUPPORTED-ALTER-PARAMS");
        assert!(params.message.contains("no collection-params setter"));

        let quantization = EdgeUnsupported::AlterCollectionQuantization.error();
        assert_eq!(quantization.code, "QQL-EDGE-UNSUPPORTED-ALTER-QUANTIZATION");
        assert!(quantization.message.contains("no quantization setter"));

        let vector = EdgeUnsupported::AlterVectorDiff.error();
        assert_eq!(vector.code, "QQL-EDGE-UNSUPPORTED-VECTOR-DIFF");
        assert!(vector.message.contains("set_vector_hnsw_config"));

        let sparse = EdgeUnsupported::AlterSparseVectorDiff.error();
        assert_eq!(sparse.code, "QQL-EDGE-UNSUPPORTED-SPARSE-DIFF");
        assert!(sparse.message.contains("sparse vector config setter"));
    }

    /// `vector_hnsw_diffs` passes HNSW patches through and rejects every other
    /// present field, naming the vector and the key; sparse diffs always reject.
    #[test]
    fn vector_hnsw_diffs_pass_hnsw_and_reject_other_fields() {
        use qql_plan::{SparseModifier, SparseVectorParamsDiff, VectorParamsDiff};

        let hnsw = qql_plan::HnswConfig {
            m: Some(32),
            ef_construct: None,
            full_scan_threshold: None,
            max_indexing_threads: None,
            on_disk: None,
            payload_m: None,
            inline_storage: None,
            memory: None,
        };
        let mut request = qql_plan::UpdateCollectionRequest {
            vectors: Some(std::collections::BTreeMap::from([(
                "dense".to_string(),
                VectorParamsDiff {
                    hnsw_config: Some(hnsw),
                    ..Default::default()
                },
            )])),
            ..Default::default()
        };
        let patches = vector_hnsw_diffs(&request).expect("hnsw-only diff");
        assert_eq!(patches.len(), 1);
        assert_eq!(patches[0].0, "dense");
        assert_eq!(patches[0].1.m, Some(32));

        request
            .vectors
            .as_mut()
            .unwrap()
            .get_mut("dense")
            .unwrap()
            .memory = Some(qql_plan::MemoryPlacement::Cold);
        let error = vector_hnsw_diffs(&request).expect_err("memory has no edge setter");
        assert_eq!(error.code, "QQL-EDGE-UNSUPPORTED-VECTOR-DIFF");
        assert_eq!(error.field("vector_name"), Some("dense"));
        assert_eq!(error.field("config_key"), Some("memory"));

        request
            .vectors
            .as_mut()
            .unwrap()
            .get_mut("dense")
            .unwrap()
            .memory = None;
        request.sparse_vectors = Some(std::collections::BTreeMap::from([(
            "bm25".to_string(),
            SparseVectorParamsDiff {
                index: None,
                modifier: Some(SparseModifier::Idf),
            },
        )]));
        let error = vector_hnsw_diffs(&request).expect_err("sparse has no edge setter");
        assert_eq!(error.code, "QQL-EDGE-UNSUPPORTED-SPARSE-DIFF");
        assert_eq!(error.field("vector_name"), Some("bm25"));
        assert_eq!(error.field("config_key"), Some("modifier"));
    }

    #[test]
    fn create_params_accept_only_on_disk_payload() {
        assert!(reject_collection_params(None).is_ok());

        let on_disk_only = qql_plan::CollectionParams {
            on_disk_payload: Some(false),
            ..Default::default()
        };
        assert!(reject_collection_params(Some(&on_disk_only)).is_ok());

        let replicated = qql_plan::CollectionParams {
            replication_factor: Some(3),
            ..Default::default()
        };
        let error = reject_collection_params(Some(&replicated)).unwrap_err();
        assert_eq!(error.code, "QQL-EDGE-UNSUPPORTED-COLLECTION-PARAMS");
        assert!(error.message.contains("only on_disk_payload"));
    }
}