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
422
423
424
425
426
427
428
429
430
//! `FilterExpression` → proto [`qdrant::Filter`] converters.
//!
//! `IN`/`NOT IN` lists must be homogeneous and int64-representable (the pinned
//! proto carries repeated string or int64 lists only); anything else is a
//! structured validation error, never a silent drop.

use qql_core::error::QqlError;
use qql_plan::types::{
    FilterClause, FilterCompound, FilterExpression, GeoLineString, GeoPolygon, MatchValue,
    PlanRangeBound,
};

use crate::qdrant_grpc::qdrant;

use super::common::to_point_id;

pub(crate) fn to_filter(fe: &FilterExpression) -> Result<qdrant::Filter, QqlError> {
    match fe {
        FilterExpression::Compound(fc) => compound_to_filter(fc),
        FilterExpression::Single(fc) => Ok(qdrant::Filter {
            must: vec![to_condition(fc)?],
            ..Default::default()
        }),
    }
}

pub(crate) fn to_filter_opt(
    fe: Option<&FilterExpression>,
) -> Result<Option<qdrant::Filter>, QqlError> {
    fe.map(to_filter).transpose()
}

pub(crate) fn compound_to_filter(fc: &FilterCompound) -> Result<qdrant::Filter, QqlError> {
    let must = fc
        .must
        .iter()
        .map(to_condition)
        .collect::<Result<Vec<_>, _>>()?;
    let must_not = fc
        .must_not
        .iter()
        .map(to_condition)
        .collect::<Result<Vec<_>, _>>()?;
    let should = fc
        .should
        .iter()
        .map(to_condition)
        .collect::<Result<Vec<_>, _>>()?;
    let min_should = fc
        .min_should
        .as_ref()
        .map(|min_should| {
            min_should
                .conditions
                .iter()
                .map(to_condition)
                .collect::<Result<Vec<_>, _>>()
                .map(|conditions| qdrant::MinShould {
                    conditions,
                    min_count: min_should.min_count,
                })
        })
        .transpose()?;
    Ok(qdrant::Filter {
        must,
        must_not,
        should,
        min_should,
    })
}

pub(crate) fn to_condition(clause: &FilterClause) -> Result<qdrant::Condition, QqlError> {
    use qdrant::condition::ConditionOneOf;
    let condition_one_of = match clause {
        FilterClause::Field(fc) => {
            let mut field = qdrant::FieldCondition {
                key: fc.key.clone(),
                ..Default::default()
            };
            if let Some(mv) = &fc.r#match {
                field.r#match = Some(to_match(mv)?);
            }
            if let Some(r) = &fc.range {
                field.range = Some(qdrant::Range {
                    gt: range_double(r.gt.as_ref())?,
                    gte: range_double(r.gte.as_ref())?,
                    lt: range_double(r.lt.as_ref())?,
                    lte: range_double(r.lte.as_ref())?,
                });
            }
            if let Some(b) = &fc.geo_bounding_box {
                field.geo_bounding_box = Some(qdrant::GeoBoundingBox {
                    top_left: Some(qdrant::GeoPoint {
                        lat: b.top_left.lat,
                        lon: b.top_left.lon,
                    }),
                    bottom_right: Some(qdrant::GeoPoint {
                        lat: b.bottom_right.lat,
                        lon: b.bottom_right.lon,
                    }),
                });
            }
            if let Some(r) = &fc.geo_radius {
                field.geo_radius = Some(qdrant::GeoRadius {
                    center: Some(qdrant::GeoPoint {
                        lat: r.center.lat,
                        lon: r.center.lon,
                    }),
                    radius: r.radius as f32,
                });
            }
            if let Some(p) = &fc.geo_polygon {
                field.geo_polygon = Some(to_geo_polygon(p)?);
            }
            if let Some(vc) = &fc.values_count {
                field.values_count = Some(qdrant::ValuesCount {
                    gt: vc.gt,
                    gte: vc.gte,
                    lt: vc.lt,
                    lte: vc.lte,
                });
            }
            ConditionOneOf::Field(field)
        }
        FilterClause::IsNull(n) => ConditionOneOf::IsNull(qdrant::IsNullCondition {
            key: n.is_null.key.clone(),
        }),
        FilterClause::IsEmpty(e) => ConditionOneOf::IsEmpty(qdrant::IsEmptyCondition {
            key: e.is_empty.key.clone(),
        }),
        FilterClause::HasId(h) => ConditionOneOf::HasId(qdrant::HasIdCondition {
            has_id: h.has_id.iter().map(to_point_id).collect(),
        }),
        FilterClause::HasVector(v) => ConditionOneOf::HasVector(qdrant::HasVectorCondition {
            has_vector: v.has_vector.clone(),
        }),
        FilterClause::Nested(n) => ConditionOneOf::Nested(qdrant::NestedCondition {
            key: n.nested.key.clone(),
            filter: Some(to_filter(&n.nested.filter)?),
        }),
        FilterClause::Filter(f) => ConditionOneOf::Filter(compound_to_filter(f)?),
        FilterClause::Slice(s) => ConditionOneOf::Slice(qdrant::SliceCondition {
            total: s.slice.total as u32,
            index: s.slice.index as u32,
        }),
    };
    Ok(qdrant::Condition {
        condition_one_of: Some(condition_one_of),
    })
}

/// Convert a plan geo ring to the proto `GeoLineString`.
///
/// A ring with fewer than three vertices cannot bound a surface: sending it
/// would either error server-side or silently match nothing, so it fails
/// closed instead of reaching the wire.
fn to_geo_line_string(
    ring: &GeoLineString,
    which: &str,
) -> Result<qdrant::GeoLineString, QqlError> {
    if ring.points.len() < 3 {
        return Err(QqlError::validation(
            "QQL-GRPC-GEO-POLYGON",
            format!(
                "geo_polygon {which} ring has {} point(s); a polygon ring needs at least 3 vertices",
                ring.points.len()
            ),
            None,
        ));
    }
    Ok(qdrant::GeoLineString {
        points: ring
            .points
            .iter()
            .map(|p| qdrant::GeoPoint {
                lat: p.lat,
                lon: p.lon,
            })
            .collect(),
    })
}

/// Convert a plan `geo_polygon` condition to the proto message (exterior plus
/// interior holes), failing closed on degenerate rings.
fn to_geo_polygon(polygon: &GeoPolygon) -> Result<qdrant::GeoPolygon, QqlError> {
    let exterior = to_geo_line_string(&polygon.exterior, "exterior")?;
    let interiors = polygon
        .interiors
        .iter()
        .map(|ring| to_geo_line_string(ring, "interior"))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(qdrant::GeoPolygon {
        exterior: Some(exterior),
        interiors,
    })
}

/// Convert an `IN`/`NOT IN` value list to the gRPC `Match`.
///
/// The pinned proto's `Match` carries either a repeated string list
/// (`keywords` / `except_keywords`) or a repeated int64 list (`integers` /
/// `except_integers`); there is no repeated bool or double list. Every entry
/// must therefore be the same kind and representable as the target type.
/// Mixed lists, non-integral floats, and `u64` values above `i64::MAX`
/// produce a structured error instead of being silently dropped or wrapped
/// into negative integers.
pub(crate) fn exact_list_match(
    values: &[qql_core::ast::Value],
    any: bool,
) -> Result<qdrant::Match, QqlError> {
    use qdrant::r#match::MatchValue as Mv;

    let any_string = values
        .iter()
        .any(|v| matches!(v, qql_core::ast::Value::Str(_)));
    let all_strings = values
        .iter()
        .all(|v| matches!(v, qql_core::ast::Value::Str(_)));
    if any_string && !all_strings {
        let offending = values
            .iter()
            .find(|v| !matches!(v, qql_core::ast::Value::Str(_)))
            .map(qql_plan::value_error_text)
            .unwrap_or_else(|| "non-string entry".to_string());
        return Err(QqlError::validation(
            "QQL-GRPC-LIST-TYPE",
            format!(
                "IN/NOT IN list mixes strings with non-string entry {offending}: the bundled Qdrant proto only supports homogeneous string or int64 lists"
            ),
            None,
        ));
    }
    if all_strings {
        let strings: Vec<String> = values
            .iter()
            .map(|v| match v {
                qql_core::ast::Value::Str(s) => s.clone(),
                _ => unreachable!("guarded by all_strings"),
            })
            .collect();
        return Ok(qdrant::Match {
            match_value: Some(if any {
                Mv::Keywords(qdrant::RepeatedStrings { strings })
            } else {
                Mv::ExceptKeywords(qdrant::RepeatedStrings { strings })
            }),
        });
    }

    // No strings: every entry must fit the proto's repeated int64 list.
    // Integral floats map to integer matches (mirroring single-value
    // `to_match`); anything else is a structured error.
    let integers = values
        .iter()
        .map(list_integer)
        .collect::<Result<Vec<i64>, QqlError>>()?;
    Ok(qdrant::Match {
        match_value: Some(if any {
            Mv::Integers(qdrant::RepeatedIntegers { integers })
        } else {
            Mv::ExceptIntegers(qdrant::RepeatedIntegers { integers })
        }),
    })
}

/// Convert one `IN`/`NOT IN` entry to the int64 wire type, rejecting values
/// the bundled proto cannot carry.
pub(crate) fn list_integer(value: &qql_core::ast::Value) -> Result<i64, QqlError> {
    use qql_core::ast::Value;
    match value {
        Value::Int(n) => Ok(*n),
        Value::UInt(n) => i64::try_from(*n).map_err(|_| {
            QqlError::validation(
                "QQL-GRPC-LIST-INT",
                format!(
                    "integer {n} in an IN/NOT IN list cannot be represented on the gRPC path: the bundled Qdrant proto stores match lists as int64 (max {})",
                    i64::MAX
                ),
                None,
            )
        }),
        Value::Float(f) => {
            // Mirror single-value `to_match`: an integral float is carried as an
            // integer match (Qdrant compares payload numbers numerically).
            let integral = f.is_finite()
                && f.fract() == 0.0
                && *f >= i64::MIN as f64
                && *f <= i64::MAX as f64
                && (*f as i64) as f64 == *f;
            if integral {
                return Ok(*f as i64);
            }
            Err(unrepresentable_list_entry(value))
        }
        _ => Err(unrepresentable_list_entry(value)),
    }
}

/// Structured error for an `IN`/`NOT IN` entry the proto cannot carry.
fn unrepresentable_list_entry(value: &qql_core::ast::Value) -> QqlError {
    QqlError::validation(
        "QQL-GRPC-LIST-TYPE",
        format!(
            "IN/NOT IN list entry {} cannot be represented on the gRPC path: the bundled Qdrant proto only supports homogeneous string or int64 lists; use an exact integer value or a RANGE filter",
            qql_plan::value_error_text(value)
        ),
        None,
    )
}

/// Convert one plan range bound to the gRPC double wire type.
///
/// The bundled proto's `Range` carries doubles only: string and datetime
/// bounds have no wire representation, so they error here instead of
/// lowering to a silent `None` (an empty range that matches wrong rows).
fn range_double(bound: Option<&PlanRangeBound>) -> Result<Option<f64>, QqlError> {
    bound
        .map(|b| {
            b.as_f64().ok_or_else(|| {
                QqlError::validation(
                    "QQL-GRPC-RANGE-TYPE",
                    format!(
                        "range bound {b:?} cannot be represented on the gRPC path: the bundled Qdrant proto stores ranges as doubles; use the REST path for string or datetime bounds"
                    ),
                    None,
                )
            })
        })
        .transpose()
}

/// Structured error for a float (or overflowing `u64`) equality value: the
/// bundled proto's `Match` has no double field. Renders with std `Display`
/// exactly like the old JSON pipeline did.
fn float_match_error(f: f64) -> QqlError {
    QqlError::validation(
        "QQL-GRPC-FLOAT-MATCH",
        format!(
            "float equality value {f} cannot be represented on the gRPC path: the bundled Qdrant proto's Match has no double field; use a RANGE filter or an exact integer value"
        ),
        None,
    )
}

pub(crate) fn to_match(mv: &MatchValue) -> Result<qdrant::Match, QqlError> {
    use qdrant::r#match::MatchValue as Mv;
    use qql_core::ast::Value;
    match mv {
        MatchValue::Value { value } => match value {
            Value::Str(s) => Ok(qdrant::Match {
                match_value: Some(Mv::Keyword(s.clone())),
            }),
            Value::Bool(b) => Ok(qdrant::Match {
                match_value: Some(Mv::Boolean(*b)),
            }),
            Value::Int(n) => Ok(qdrant::Match {
                match_value: Some(Mv::Integer(*n)),
            }),
            Value::UInt(n) => match i64::try_from(*n) {
                Ok(n) => Ok(qdrant::Match {
                    match_value: Some(Mv::Integer(n)),
                }),
                Err(_) => Err(float_match_error(*n as f64)),
            },
            Value::Float(f) => {
                // The pinned proto's `Match` has no `double_value` field, so a
                // float equality filter (`WHERE x = 1.5`) has no exact wire
                // representation. An integral value can be carried as an
                // integer match (Qdrant compares payload numbers numerically);
                // anything else returns a structured error instead of emitting
                // an empty `Match` and silently matching nothing.
                // Non-finite floats ride the generic arm below: the old JSON
                // pipeline rendered them `null`, which never matched here.
                let integral = f.is_finite()
                    && f.fract() == 0.0
                    && *f >= i64::MIN as f64
                    && *f <= i64::MAX as f64
                    && (*f as i64) as f64 == *f;
                if integral {
                    Ok(qdrant::Match {
                        match_value: Some(Mv::Integer(*f as i64)),
                    })
                } else if f.is_finite() {
                    Err(float_match_error(*f))
                } else {
                    Err(QqlError::validation(
                        "QQL-GRPC-MATCH-VALUE",
                        format!(
                            "match value {} cannot be represented on the gRPC path",
                            qql_plan::value_error_text(value)
                        ),
                        None,
                    ))
                }
            }
            Value::Param(name, _) => {
                panic!(
                    "invariant violation: unbound parameter :{name} reached gRPC match conversion"
                );
            }
            Value::PositionalParam(idx, _) => {
                panic!(
                    "invariant violation: unbound positional parameter ?{idx} reached gRPC match conversion"
                );
            }
            _ => Err(QqlError::validation(
                "QQL-GRPC-MATCH-VALUE",
                format!(
                    "match value {} cannot be represented on the gRPC path",
                    qql_plan::value_error_text(value)
                ),
                None,
            )),
        },
        MatchValue::Text { text } => Ok(qdrant::Match {
            match_value: Some(Mv::Text(text.clone())),
        }),
        MatchValue::TextAny { text_any } => Ok(qdrant::Match {
            match_value: Some(Mv::TextAny(text_any.clone())),
        }),
        MatchValue::Any { any } => exact_list_match(any, true),
        MatchValue::Except { except } => exact_list_match(except, false),
        MatchValue::Phrase { phrase } => Ok(qdrant::Match {
            match_value: Some(Mv::Phrase(phrase.clone())),
        }),
        MatchValue::Prefix { prefix } => Ok(qdrant::Match {
            match_value: Some(Mv::Prefix(prefix.clone())),
        }),
    }
}