qql 0.5.0

QQL runtime and executor for Qdrant REST and gRPC
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
//! REST vs gRPC field parity for query, filter, hybrid, feedback.

use super::{openapi_or_skip, validate_ref};
use crate::grpc_route::test_api;
use crate::qdrant_grpc::qdrant;
use qql_core::parser::Parser;
use qql_plan::PlannedOperation;
use qql_plan::plan::{plan, to_rest_route};

#[test]
fn numeric_shard_key_stays_numeric_on_both_transports() {
    // The 1.7 mistargeting fix: SHARD 101 must reach the numeric
    // partition on REST (body number) and gRPC (Number selector) —
    // never the "101" keyword.
    let stmt = Parser::parse("DELETE FROM docs WHERE id = 1 SHARD 101;").unwrap();
    let op = plan(&stmt).unwrap();

    let route = to_rest_route(&op).expect("rest route");
    let body = route.body_json().unwrap();
    assert_eq!(body["shard_key"], serde_json::json!(101));
    assert!(
        route.query.iter().all(|(k, _)| k != "shard_key"),
        "routing rides the body field, not the query string: {:?}",
        route.query
    );

    let PlannedOperation::Delete {
        collection,
        request,
        ..
    } = &op
    else {
        panic!("expected Delete plan");
    };
    assert_eq!(collection, "docs");
    let selector = test_api::shard_key_selector(&request.shard_key);
    let keys = selector.unwrap().shard_keys;
    assert_eq!(keys.len(), 1);
    match keys[0].key.as_ref() {
        Some(qdrant::shard_key::Key::Number(n)) => assert_eq!(*n, 101),
        other => panic!("expected numeric shard, got {other:?}"),
    }
}

#[test]
fn rest_grpc_query_parity_timeout_consistency_shard_multi() {
    // MultiDense + timeout + consistency + shard_key
    let stmt = Parser::parse(
        "QUERY NEAREST VECTOR [[0.1, 0.2], [0.3, 0.4]] FROM docs \
             USING colbert SHARD 'acme' \
             PARAMS (timeout = 15, consistency = quorum) LIMIT 7;",
    )
    .unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Query {
        collection,
        request,
    } = &op
    else {
        panic!("expected Query plan");
    };
    assert_eq!(collection, "docs");

    // REST projection
    let route = to_rest_route(&op).expect("rest route");
    assert_eq!(route.path, "/collections/docs/points/query");
    assert!(route.query.iter().any(|(k, v)| k == "timeout" && v == "15"));
    assert!(
        route
            .query
            .iter()
            .any(|(k, v)| k == "consistency" && v == "quorum")
    );
    let body = route.body_json().unwrap();
    assert_eq!(body["limit"], 7);
    assert_eq!(body["using"], "colbert");
    assert_eq!(body["shard_key"], "acme");
    assert!(body["query"]["nearest"].is_array());
    assert!(body.get("timeout").is_none());
    assert!(body.get("consistency").is_none());

    // gRPC conversion (proto QueryPoints)
    let grpc = test_api::to_query_points(request, collection).expect("to_query_points");
    assert_eq!(grpc.collection_name, "docs");
    assert_eq!(grpc.using.as_deref(), Some("colbert"));
    assert_eq!(grpc.limit, Some(7));
    assert_eq!(grpc.timeout, Some(15));
    assert!(grpc.read_consistency.is_some());
    let rc = grpc.read_consistency.as_ref().unwrap();
    use qdrant::read_consistency::Value as RcVal;
    match rc.value.as_ref() {
        Some(RcVal::Type(t)) => {
            assert_eq!(*t, qdrant::ReadConsistencyType::Quorum as i32);
        }
        other => panic!("expected quorum type, got {other:?}"),
    }
    assert!(grpc.shard_key_selector.is_some());
    let sk = &grpc.shard_key_selector.as_ref().unwrap().shard_keys;
    assert_eq!(sk.len(), 1);
    match sk[0].key.as_ref() {
        Some(qdrant::shard_key::Key::Keyword(k)) => assert_eq!(k, "acme"),
        other => panic!("expected keyword shard, got {other:?}"),
    }

    // MultiDense variant on nearest
    let q = grpc.query.as_ref().expect("query");
    use qdrant::query::Variant as Qv;
    use qdrant::vector_input::Variant as Vi;
    match q.variant.as_ref() {
        Some(Qv::Nearest(vi)) => match vi.variant.as_ref() {
            Some(Vi::MultiDense(md)) => {
                assert_eq!(md.vectors.len(), 2);
                assert_eq!(md.vectors[0].data, vec![0.1, 0.2]);
                assert_eq!(md.vectors[1].data, vec![0.3, 0.4]);
            }
            other => panic!("expected MultiDense, got {other:?}"),
        },
        other => panic!("expected Nearest, got {other:?}"),
    }
}

/// REST `"payload": {}` survives as `Some({})`; the gRPC empty proto map must
/// read the same, not `None`. Needs both transports (REST-only strict parser
/// plus the gRPC converter).
#[cfg(feature = "rest")]
#[test]
fn rest_grpc_empty_payload_parity() {
    use std::collections::HashMap;

    // REST `"payload": {}` survives as `Some({})`; the gRPC empty proto map
    // must read the same, not `None`.
    let stmt = Parser::parse("SCROLL FROM docs LIMIT 1;").unwrap();
    let op = plan(&stmt).unwrap();
    let rest = crate::rest_response::parse_planned(
        &op,
        serde_json::json!({"result": {"points": [{"id": 1, "payload": {}}]}, "status": "ok"}),
    )
    .expect("REST empty payload parses");
    let rest_hit = &rest.data.hits().expect("hits")[0];
    assert_eq!(rest_hit.payload, Some(HashMap::new()));

    let grpc_hit = test_api::retrieved_point_to_hit(qdrant::RetrievedPoint {
        id: Some(qdrant::PointId {
            point_id_options: Some(qdrant::point_id::PointIdOptions::Num(1)),
        }),
        payload: Default::default(),
        vectors: None,
        shard_key: None,
        order_value: None,
    })
    .expect("gRPC empty payload converts");
    assert_eq!(grpc_hit.payload, rest_hit.payload);
}

#[test]
fn rest_grpc_geo_polygon_parity() {
    // The same polygon must be present in the REST body and the proto field
    // condition — a missing proto conversion silently matches different rows.
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'e5' FROM docs WHERE area GEO_POLYGON \
         {exterior: [{lat: -70.0, lon: -70.0}, {lat: 60.0, lon: -70.0}, {lat: 60.0, lon: 60.0}, {lat: -70.0, lon: 60.0}], \
          interiors: [[{lat: -50.0, lon: -50.0}, {lat: 50.0, lon: -50.0}, {lat: 50.0, lon: 50.0}, {lat: -50.0, lon: 50.0}]]};",
    )
    .unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Query {
        collection,
        request,
    } = &op
    else {
        panic!("expected Query");
    };

    let body = to_rest_route(&op).expect("rest route").body_json().unwrap();
    let rest_polygon = &body["filter"]["must"][0]["geo_polygon"];
    assert_eq!(
        rest_polygon["exterior"]["points"].as_array().map(Vec::len),
        Some(4)
    );
    assert_eq!(rest_polygon["interiors"].as_array().map(Vec::len), Some(1));
    assert_eq!(rest_polygon["exterior"]["points"][0]["lat"], -70.0);

    let grpc = test_api::to_query_points(request, collection).unwrap();
    let condition = grpc
        .filter
        .expect("gRPC filter converts")
        .must
        .swap_remove(0);
    let Some(qdrant::condition::ConditionOneOf::Field(field)) = condition.condition_one_of else {
        panic!("expected a field condition");
    };
    let proto_polygon = field.geo_polygon.expect("REST body has geo_polygon");
    let exterior = proto_polygon.exterior.expect("exterior ring");
    assert_eq!(exterior.points.len(), 4);
    assert_eq!(exterior.points[0].lat, -70.0);
    assert_eq!(proto_polygon.interiors.len(), 1);
}

#[test]
fn rest_grpc_scroll_order_by_parity() {
    let stmt = Parser::parse("SCROLL FROM docs ORDER BY ts DESC START FROM 7 LIMIT 5;").unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Scroll {
        collection,
        request,
    } = &op
    else {
        panic!("expected Scroll");
    };

    let body = to_rest_route(&op).expect("rest route").body_json().unwrap();
    assert_eq!(body["order_by"]["key"], "ts");
    assert_eq!(body["order_by"]["direction"], "desc");
    assert_eq!(body["order_by"]["start_from"], 7);

    let grpc = test_api::to_scroll_points(request, collection).unwrap();
    let order_by = grpc.order_by.expect("REST body has order_by");
    assert_eq!(order_by.key, "ts");
    assert_eq!(order_by.direction, Some(qdrant::Direction::Desc as i32));
    match order_by.start_from.and_then(|sf| sf.value) {
        Some(qdrant::start_from::Value::Integer(7)) => {}
        other => panic!("expected integer START FROM 7, got {other:?}"),
    }
}

#[test]
fn rest_grpc_count_exact_parity() {
    let stmt = Parser::parse("COUNT FROM docs WITH (exact = false);").unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Count {
        collection,
        request,
    } = &op
    else {
        panic!("expected Count");
    };
    let body = to_rest_route(&op).expect("rest route").body_json().unwrap();
    assert_eq!(body["exact"], false);
    assert_eq!(
        test_api::to_count_points(request, collection)
            .unwrap()
            .exact,
        Some(false)
    );
}

#[test]
fn rest_grpc_relevance_feedback_parity() {
    let stmt = Parser::parse(
            "QUERY RELEVANCE FEEDBACK TARGET POINT 42 FEEDBACK ((POINT 43, 0.5), (POINT 44, -0.2)) STRATEGY NAIVE (a = 1.0, b = 0.5, c = 0.5) FROM docs USING dense LIMIT 10;",
        )
        .unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Query {
        collection,
        request,
    } = &op
    else {
        panic!("expected Query");
    };

    // REST projection carries the typed feedback shape.
    let body = to_rest_route(&op).expect("rest route").body_json().unwrap();
    let rf = &body["query"]["relevance_feedback"];
    assert!(
        rf.is_object(),
        "REST relevance_feedback missing: {}",
        body["query"]
    );
    assert_eq!(rf["feedback"].as_array().map(Vec::len), Some(2));
    assert_eq!(rf["strategy"]["naive"]["a"], 1.0);

    // gRPC conversion carries target + both items + strategy.
    let grpc = test_api::to_query_points(request, collection).unwrap();
    use qdrant::query::Variant as Qv;
    let Some(Qv::RelevanceFeedback(fb)) = grpc.query.as_ref().and_then(|q| q.variant.as_ref())
    else {
        panic!("expected RelevanceFeedback, got {:?}", grpc.query);
    };
    assert!(fb.target.is_some(), "feedback target must convert");
    assert_eq!(fb.feedback.len(), 2, "both feedback items must convert");
    assert!(fb.strategy.is_some(), "naive strategy must convert");
}

#[test]
fn match_except_filter_contract_matches_openapi() {
    // `MATCH EXCEPT` is QQL surface syntax (`qql-core` parses it to
    // `FilterExpr::MatchExcept`), so it is covered both ways: first the
    // end-to-end lowered route body, then the typed plan shape directly.
    // The gRPC half is covered by
    // `grpc_exact_list_match_is_homogeneous_and_fallible`.
    let Some(openapi) = openapi_or_skip() else {
        return;
    };

    // 1. QQL surface: parse → route → OpenAPI Filter.
    let stmt =
        Parser::parse("QUERY TEXT 'x' MODEL 'e5' FROM docs WHERE tags MATCH EXCEPT ('a', 'b');")
            .expect("MATCH EXCEPT parses");
    let body = to_rest_route(&plan(&stmt).expect("MATCH EXCEPT plans"))
        .expect("MATCH EXCEPT routes")
        .body_json()
        .expect("MATCH EXCEPT has a body");
    let filter = body.get("filter").expect("route body carries a filter");
    let norm_filter = if filter.get("must").is_none()
        && filter.get("should").is_none()
        && filter.get("must_not").is_none()
    {
        serde_json::json!({ "must": [filter] })
    } else {
        filter.clone()
    };
    assert_eq!(
        norm_filter["must"][0]["match"]["except"],
        serde_json::json!(["a", "b"])
    );
    validate_ref(&openapi, "Filter", &norm_filter);
    use qql_plan::{FieldCondition, FilterClause, MatchValue};
    let clause = FilterClause::Field(Box::new(FieldCondition {
        key: "tag".into(),
        r#match: Some(MatchValue::Except {
            except: vec![
                qql_core::ast::Value::Str("a".into()),
                qql_core::ast::Value::Str("b".into()),
            ],
        }),
        ..Default::default()
    }));
    let filter = serde_json::json!({
        "must": [serde_json::to_value(&clause).expect("except clause serializes")],
    });
    validate_ref(&openapi, "Filter", &filter);
}

#[test]
fn grpc_range_rejects_non_numeric_bounds() {
    // The bundled proto's `Range` carries doubles only. Numeric bounds
    // convert; string and datetime bounds error (`QQL-GRPC-RANGE-TYPE`)
    // instead of lowering to a silent `None` — an empty range that matches
    // wrong rows. REST keeps carrying them as strings.
    let stmt =
        Parser::parse("QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE age >= 21 LIMIT 5;")
            .unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Query {
        collection,
        request,
    } = &op
    else {
        panic!("expected Query");
    };
    let qp = test_api::to_query_points(request, collection).unwrap();
    let range = qp
        .filter
        .expect("filter converts")
        .must
        .swap_remove(0)
        .condition_one_of
        .and_then(|c| match c {
            qdrant::condition::ConditionOneOf::Field(f) => f.range,
            _ => None,
        })
        .expect("numeric bound converts to a proto range");
    assert_eq!(range.gte, Some(21.0));

    for sql in [
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE created_at >= '2024-01-01T00:00:00Z' LIMIT 5;",
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE name > 'm' LIMIT 5;",
    ] {
        let stmt = Parser::parse(sql).unwrap();
        let op = plan(&stmt).unwrap();
        let body = to_rest_route(&op).expect("rest route").body_json().unwrap();
        assert!(
            body["filter"]["must"][0]["range"].is_object(),
            "REST keeps the string bound: {body}"
        );
        let PlannedOperation::Query {
            collection,
            request,
        } = &op
        else {
            panic!("expected Query");
        };
        let err = test_api::to_query_points(request, collection).unwrap_err();
        assert_eq!(err.code, "QQL-GRPC-RANGE-TYPE");
    }
}

#[test]
fn rest_grpc_hybrid_prefetch_parity() {
    let stmt = Parser::parse(
            "QUERY HYBRID TEXT 'search' MODEL 'bge' DENSE dense SPARSE sparse FUSION RRF FROM docs LIMIT 10;",
        )
        .unwrap();
    let op = plan(&stmt).unwrap();
    let PlannedOperation::Query {
        collection,
        request,
    } = &op
    else {
        panic!("expected Query");
    };

    let body = to_rest_route(&op).expect("rest route").body_json().unwrap();
    assert_eq!(body["query"]["fusion"], "rrf");
    assert_eq!(body["prefetch"].as_array().unwrap().len(), 2);
    assert_eq!(body["prefetch"][0]["using"], "dense");
    assert_eq!(body["prefetch"][1]["using"], "sparse");

    let grpc = test_api::to_query_points(request, collection).unwrap();
    assert_eq!(grpc.prefetch.len(), 2);
    assert_eq!(grpc.prefetch[0].using.as_deref(), Some("dense"));
    assert_eq!(grpc.prefetch[1].using.as_deref(), Some("sparse"));
    use qdrant::query::Variant as Qv;
    match grpc.query.as_ref().and_then(|q| q.variant.as_ref()) {
        Some(Qv::Fusion(f)) => {
            let _ = f;
        }
        other => panic!("expected Fusion query variant, got {other:?}"),
    }
}