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
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::collections::HashMap;
use std::sync::Arc;

use qql_core::ast::{self, Stmt, Value};
use qql_core::error::QqlError;
use qql_core::parser;

use crate::backend::CollectionInfo;
use crate::client::QdrantOps;
use crate::config::QqlConfig;
use crate::embedder::Embedder;

/// `EXPLAIN ANALYZE`: static plan plus measured execution.
pub mod analyze;
pub(crate) mod batch;
/// DDL preparation and collection schema caching.
pub mod ddl;
pub(crate) mod dispatch;
pub(crate) mod dml;
/// Corpus-true BM25 `avg_len` estimation from sampled payloads.
pub mod estimate;
pub(crate) mod normalize;
pub(crate) mod prepared;
pub(crate) mod response;
/// Phase-1 telemetry types: client phase timings plus server `time`/`usage`.
pub mod telemetry;

pub use prepared::PreparedStatement;
pub use qql_embed::resolve::{DENSE_VECTOR_NAME, SPARSE_VECTOR_NAME};
pub use response::{
    AnalyzeReport, BackendResponse, ExecData, ExecResponse, ExecutionReport, FacetHit,
    GroupedSearchResult, OnError, SearchHit, score_f64,
};
pub use telemetry::{
    HardwareUsage, InferenceUsage, ModelUsage, PhaseTimings, ServerTelemetry, ServerUsage,
};

/// Collection vector name reserved for multivector (ColBERT) rerank vectors.
pub const RERANK_VECTOR_NAME: &str = "colbert";
/// Dense model used when a default embedder is required and none is configured.
pub const DENSE_MODEL_DEFAULT: &str = "sentence-transformers/all-minilm-l6-v2";
/// Sparse model id used when a default sparse embedder is required.
pub const SPARSE_MODEL_DEFAULT: &str = "qdrant/bm25";
/// Cross-encoder model used when `CROSS RERANK` runs without an explicit model.
pub const RERANK_MODEL_DEFAULT: &str = "answerdotai/answerai-colbert-small-v1";
/// Fallback dense vector dimension when no embedder is configured (all-minilm-l6-v2).
pub const DENSE_VECTOR_SIZE: u64 = 384;
/// Fallback per-token multivector dimension (ColBERT-small) when none is configured.
pub const RERANK_VECTOR_SIZE: u64 = 96;
/// Default inference mode (`local` fastembed; `remote` uses HTTP endpoints).
pub const INFERENCE_MODE_DEFAULT: &str = "local";

/// Cached schema entry: `Arc`-shared collection info plus the derived
/// topology names, so cache hits cost refcount bumps instead of clones.
pub(crate) type SchemaCacheEntry = (Arc<CollectionInfo>, Arc<qql_embed::TopologyNames>);

/// The QQL executor: prepare (schema `USING` resolution + embeddings) → `plan()`
/// → batch classification → dispatch over a `QdrantOps` backend.
pub struct Executor {
    pub(crate) client: Box<dyn QdrantOps>,
    pub(crate) config: Option<QqlConfig>,
    pub(crate) embedder: Option<Arc<dyn Embedder>>,
    /// Collection topology (dense / sparse / multivector names). Invalidated
    /// after DDL so `USING` routing does not `GET /collections/{name}` per query.
    /// Repeated SQL templates belong on [`Executor::prepare`], not here.
    ///
    /// Async lock: every critical section is a map lookup plus `Arc` clones
    /// (no I/O under the lock), so holders never stall the worker thread.
    /// Infos are `Arc`-shared so cache hits cost a refcount bump instead of a
    /// full `CollectionInfo` clone per operation.
    pub(crate) schema_cache: tokio::sync::RwLock<HashMap<String, SchemaCacheEntry>>,
    /// Set by [`Executor::close`]; every execution entry point fails after it.
    closed: std::sync::atomic::AtomicBool,
    close_lock: tokio::sync::Mutex<()>,
}

impl Executor {
    /// Create an executor connected to Qdrant over HTTP REST.
    #[cfg(feature = "rest")]
    pub fn rest(url: impl Into<String>, api_key: Option<String>) -> Result<Self, QqlError> {
        Ok(Self::new(
            Box::new(crate::rest::RestQdrant::new(url, api_key)),
            None,
        ))
    }

    /// Create an executor connected to Qdrant over gRPC.
    #[cfg(feature = "grpc")]
    pub fn grpc(url: impl Into<String>, api_key: Option<String>) -> Result<Self, QqlError> {
        let url = url.into();
        Ok(Self::new(
            Box::new(crate::grpc::GrpcQdrant::from_url(&url, api_key)?),
            None,
        ))
    }

    /// Construct an executor with a boxed backend and optional runtime configuration.
    pub fn new(client: Box<dyn QdrantOps>, config: Option<QqlConfig>) -> Self {
        Self {
            client,
            config,
            embedder: None,
            schema_cache: tokio::sync::RwLock::new(HashMap::new()),
            closed: std::sync::atomic::AtomicBool::new(false),
            close_lock: tokio::sync::Mutex::new(()),
        }
    }

    /// Construct an executor with a backend, config, and embedder.
    pub fn with_embedder(
        client: Box<dyn QdrantOps>,
        config: Option<QqlConfig>,
        embedder: Option<Arc<dyn Embedder>>,
    ) -> Self {
        Self {
            client,
            config,
            embedder,
            schema_cache: tokio::sync::RwLock::new(HashMap::new()),
            closed: std::sync::atomic::AtomicBool::new(false),
            close_lock: tokio::sync::Mutex::new(()),
        }
    }

    /// Borrow the underlying backend ops (alias of `client`).
    pub fn ops(&self) -> &dyn QdrantOps {
        self.client.as_ref()
    }

    /// Format an ASCII plan tree for the query without executing it.
    pub fn explain(query: &str) -> Result<String, QqlError> {
        qql_core::explain::explain(query)
    }

    /// Format plan trees for all statements in a multi-statement script.
    pub fn explain_all(query: &str) -> Result<String, QqlError> {
        qql_core::explain::explain_all(query)
    }

    /// Format the plan tree for a pre-parsed statement node.
    pub fn explain_node(stmt: &Stmt) -> Result<String, QqlError> {
        Ok(qql_core::explain::explain_node(stmt))
    }

    /// Reference to the underlying backend ops (`RestQdrant`, `GrpcQdrant`, or test mock).
    pub fn client(&self) -> &dyn QdrantOps {
        self.client.as_ref()
    }

    /// Close the executor: prevents new executions, clears the schema cache,
    /// and closes the backend (flushing/releasing resources; embedded
    /// backends override [`QdrantOps::close`] to release their store).
    /// In-flight statements that already passed
    /// `ensure_open` run to completion.
    ///
    /// Idempotent: a second call is a no-op and the backend is closed once.
    pub async fn close(&self) -> Result<(), QqlError> {
        let _guard = self.close_lock.lock().await;
        if self.closed.swap(true, std::sync::atomic::Ordering::SeqCst) {
            return Ok(());
        }
        self.schema_cache.write().await.clear();
        self.client.close().await
    }

    /// Check whether this executor has been closed.
    pub fn is_closed(&self) -> bool {
        self.closed.load(std::sync::atomic::Ordering::SeqCst)
    }

    pub(crate) fn ensure_open(&self) -> Result<(), QqlError> {
        if self.is_closed() {
            Err(QqlError::execution(
                "QQL-CLIENT-CLOSED",
                "cannot execute query on a closed executor",
                None,
            ))
        } else {
            Ok(())
        }
    }

    /// Borrow the embedder reference if configured.
    pub fn embedder(&self) -> Option<&Arc<dyn Embedder>> {
        self.embedder.as_ref()
    }

    /// Borrow the runtime configuration if set.
    pub fn config(&self) -> Option<&QqlConfig> {
        self.config.as_ref()
    }

    /// Request timeout in seconds, if configured.
    pub fn request_timeout(&self) -> Option<u64> {
        self.config.as_ref().and_then(|c| {
            if c.request_timeout > 0 {
                Some(c.request_timeout)
            } else {
                None
            }
        })
    }

    /// Execute a multi-statement QQL script string under the configured timeout.
    pub async fn execute(
        &self,
        query: &str,
        on_error: OnError,
    ) -> Result<ExecutionReport, QqlError> {
        self.ensure_open()?;
        let statements = match parser::Parser::parse_all(query) {
            Ok(statements) => statements,
            Err(error) if matches!(on_error, OnError::Stop) => return Err(error),
            Err(error) => {
                return Ok(ExecutionReport::from_results(vec![ExecResponse {
                    ok: false,
                    operation: "PARSE".to_string(),
                    message: error.to_string(),
                    data: None,
                    telemetry: None,
                }]));
            }
        };
        if statements.is_empty() {
            return Err(QqlError::validation(
                "QQL-VALIDATION-EMPTY-SCRIPT",
                "no statements to execute; the query string is empty or contains only comments",
                None,
            ));
        }
        let results = self.execute_batch_nodes(statements, on_error).await?;
        Ok(ExecutionReport::from_results(results))
    }

    /// Execute a parameterized query with named parameters (`:name`).
    pub async fn execute_with_params(
        &self,
        query: &str,
        params: &HashMap<String, Value>,
        on_error: OnError,
    ) -> Result<ExecutionReport, QqlError> {
        self.ensure_open()?;
        let mut statements = parser::Parser::parse_all(query)?;
        for stmt in &mut statements {
            qql_core::params::bind_stmt(stmt, |k| params.get(k).cloned(), &[])?;
        }
        let results = self.execute_batch_nodes(statements, on_error).await?;
        Ok(ExecutionReport::from_results(results))
    }

    /// Execute a parameterized query with named parameters given as a slice of `(name, value)` pairs.
    pub async fn execute_with_named_params<K: AsRef<str>>(
        &self,
        query: &str,
        params: &[(K, Value)],
        on_error: OnError,
    ) -> Result<ExecutionReport, QqlError> {
        self.ensure_open()?;
        let mut statements = parser::Parser::parse_all(query)?;
        // Index once: the bind closure runs per placeholder, so a linear
        // `find` per lookup would be O(placeholders × params) with a full
        // `Value` clone on every hit. The map borrows `params`; only the
        // per-lookup clone into the AST remains (required by the owned-
        // `Value` bind contract).
        let lookup_map: HashMap<&str, &Value> = params
            .iter()
            .map(|(name, value)| (name.as_ref(), value))
            .collect();
        for stmt in &mut statements {
            qql_core::params::bind_stmt(stmt, |k| lookup_map.get(k).map(|v| (*v).clone()), &[])?;
        }
        let results = self.execute_batch_nodes(statements, on_error).await?;
        Ok(ExecutionReport::from_results(results))
    }

    /// Execute a parameterized query with positional parameters (`?`).
    pub async fn execute_with_positional_params(
        &self,
        query: &str,
        params: &[Value],
        on_error: OnError,
    ) -> Result<ExecutionReport, QqlError> {
        self.ensure_open()?;
        let mut statements = parser::Parser::parse_all(query)?;
        for stmt in &mut statements {
            qql_core::params::bind_stmt(stmt, |_| None, params)?;
        }
        let results = self.execute_batch_nodes(statements, on_error).await?;
        Ok(ExecutionReport::from_results(results))
    }

    /// Shared preparation: embeddings, named-vector validation, and UPSERT
    /// collection auto-creation. Callers must preserve statement order because
    /// preparation may read or mutate backend state.
    pub(crate) async fn prepare_statement(&self, mut stmt: Stmt) -> Result<Stmt, QqlError> {
        let upsert_schema = match &mut stmt {
            Stmt::Query(query) => {
                if let ast::QueryCollection::Explicit(collection) = &query.collection {
                    let collection = collection.clone();
                    self.configure_query_vectors(&collection, query).await?;
                }
                None
            }
            Stmt::Upsert(upsert) => self.configure_upsert_embeddings(upsert).await?,
            _ => None,
        };

        if let Some(ref embedder) = self.embedder {
            self.resolve_embeddings(&mut stmt, embedder.as_ref())
                .await?;
        }

        if let Stmt::CreateCollection(create) = &mut stmt {
            self.prepare_create_collection(create).await?;
        }

        if let Stmt::AlterCollection(alter) = &stmt {
            self.configure_alter_collection(alter).await?;
        }

        if let Stmt::Upsert(u) = &stmt {
            if let Some(ref emb) = u.embedding {
                type SpecTuple<'a> = (
                    Option<&'a str>,
                    bool,
                    bool,
                    Option<&'a str>,
                    Option<&'a str>,
                );

                fn collect_specs(spec: &ast::EmbeddingSpec) -> Vec<SpecTuple<'_>> {
                    match spec {
                        ast::EmbeddingSpec::Dense { model, vector, .. } => {
                            vec![(model.as_deref(), true, false, vector.as_deref(), None)]
                        }
                        ast::EmbeddingSpec::Sparse { model, vector, .. } => {
                            vec![(model.as_deref(), false, true, None, vector.as_deref())]
                        }
                        ast::EmbeddingSpec::MultiVector { .. }
                        | ast::EmbeddingSpec::Image { .. } => Vec::new(),
                        ast::EmbeddingSpec::Hybrid {
                            dense_model,
                            dense_vector,
                            sparse_vector,
                            ..
                        } => vec![(
                            dense_model.as_deref(),
                            true,
                            true,
                            dense_vector.as_deref(),
                            sparse_vector.as_deref(),
                        )],
                        ast::EmbeddingSpec::Multi(specs) => {
                            specs.iter().flat_map(collect_specs).collect()
                        }
                    }
                }

                let specs = collect_specs(emb);
                if !specs.is_empty() {
                    let mut aggregated_dense = false;
                    let mut aggregated_sparse = false;
                    let mut main_model = None;
                    let mut main_dense_vec = None;
                    let mut main_sparse_vec = None;

                    // First-spec-wins creation covers one dense name, one
                    // sparse name, and one sizing model: every other spec must
                    // agree (or leave its target unset for inference).
                    // Otherwise the created schema would silently drop their
                    // vectors and the backend would fail opaquely later.
                    for (model, has_dense, has_sparse, dense_vec, sparse_vec) in specs {
                        if has_dense {
                            aggregated_dense = true;
                            match (main_dense_vec, dense_vec) {
                                (None, name) => main_dense_vec = name,
                                (Some(first), Some(name)) if first != name => {
                                    return Err(QqlError::execution(
                                        "QQL-EMBEDDING-TOPOLOGY",
                                        format!(
                                            "cannot auto-create collection '{}': conflicting dense vector names '{first}' vs '{name}'; create the collection explicitly",
                                            u.collection
                                        ),
                                        None,
                                    ));
                                }
                                _ => {}
                            }
                        }
                        if has_sparse {
                            aggregated_sparse = true;
                            match (main_sparse_vec, sparse_vec) {
                                (None, name) => main_sparse_vec = name,
                                (Some(first), Some(name)) if first != name => {
                                    return Err(QqlError::execution(
                                        "QQL-EMBEDDING-TOPOLOGY",
                                        format!(
                                            "cannot auto-create collection '{}': conflicting sparse vector names '{first}' vs '{name}'; create the collection explicitly",
                                            u.collection
                                        ),
                                        None,
                                    ));
                                }
                                _ => {}
                            }
                        }
                        if let Some(model) = model {
                            match main_model {
                                None => main_model = Some(model),
                                Some(first) if first != model => {
                                    return Err(QqlError::execution(
                                        "QQL-EMBEDDING-TOPOLOGY",
                                        format!(
                                            "cannot auto-create collection '{}': conflicting embedding models '{first}' vs '{model}'; create the collection explicitly",
                                            u.collection
                                        ),
                                        None,
                                    ));
                                }
                                _ => {}
                            }
                        }
                    }

                    self.ensure_collection_for_upsert(
                        &u.collection,
                        main_model,
                        aggregated_dense,
                        aggregated_sparse,
                        main_dense_vec,
                        main_sparse_vec,
                    )
                    .await?;
                }
            }
            if let Some(info) = upsert_schema.as_ref() {
                self.validate_embedded_upsert(u, info)?;
            }
        }

        Ok(stmt)
    }
}