vlorql 0.5.0

High-level SQL query optimization and LLM-powered natural language querying library
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
use super::*;
use async_trait::async_trait;
use std::sync::{Arc, Mutex};
use vlorql_core::errors::{LlmErrorKind, SchemaErrorKind};
use vlorql_core::schema::{
    ColumnSchema, DataType, Expression, FromClause, Predicate, Projection, QueryPlan,
    SchemaMetadata, TableSchema,
};
use vlorql_llm::MockLlmClient;

#[test]
fn retry_feedback_is_truncated_when_many_errors() {
    let errs: Vec<VlorQLError> = (0..5)
        .map(|i| {
            VlorQLError::schema(
                SchemaErrorKind::ColumnNotFound {
                    table: "t".to_owned(),
                    column: format!("c{i}"),
                },
                serde_json::json!({"table": "t", "column": format!("c{i}")}),
            )
        })
        .collect();
    let errors = ValidationErrors(errs);
    let q = format_retry_question("q", &errors, 2);
    assert!(
        q.contains("c0") && q.contains("c1") && q.contains("c2"),
        "first 3: {q}"
    );
    assert!(!q.contains("c4"), "not the 5th: {q}");
    assert!(q.contains("2 more"), "omitted count: {q}");
}

#[test]
fn retry_temperature_keeps_default_on_first_attempt_then_escalates() {
    assert_eq!(retry_temperature(0.0, 0), None);
    assert_eq!(retry_temperature(0.0, 1), Some(0.2));
    assert_eq!(retry_temperature(0.0, 2), Some(0.4));
    assert!(retry_temperature(0.9, 3).expect("retry should escalate") <= 1.0);
}

#[test]
fn retry_feedback_is_tiered_by_attempt() {
    let errs: Vec<VlorQLError> = (0..5)
        .map(|i| {
            VlorQLError::schema(
                SchemaErrorKind::ColumnNotFound {
                    table: "t".to_owned(),
                    column: format!("c{i}"),
                },
                serde_json::json!({"table": "t", "column": format!("c{i}")}),
            )
        })
        .collect();
    let errors = ValidationErrors(errs);
    let first = format_retry_question("q", &errors, 0);
    let later = format_retry_question("q", &errors, 2);
    assert!(
        first.matches("does not exist").count() < later.matches("does not exist").count(),
        "attempt 0 terser than attempt 2:\nfirst={first}\nlater={later}"
    );
}

fn schema() -> Arc<SchemaSnapshot> {
    Arc::new(SchemaSnapshot::new(
        vec![TableSchema {
            name: "users".to_owned(),
            columns: vec![
                ColumnSchema {
                    name: "id".to_owned(),
                    data_type: DataType::Int,
                    nullable: false,
                    description: None,
                    is_primary_key: true,
                    foreign_key: None,
                },
                ColumnSchema {
                    name: "name".to_owned(),
                    data_type: DataType::String,
                    nullable: false,
                    description: None,
                    is_primary_key: false,
                    foreign_key: None,
                },
            ],
            description: None,
            primary_key: Some(vec!["id".to_owned()]),
        }],
        SchemaMetadata::default(),
    ))
}

fn valid_plan() -> QueryPlan {
    QueryPlan {
        select: vec![Projection::Column {
            table: Some("users".to_owned()),
            column: "id".to_owned(),
            alias: None,
        }],
        from: FromClause::table("users".to_owned(), Some("t1".to_owned())),
        r#where: None,
        group_by: None,
        having: None,
        order_by: None,
        limit: None,
        offset: None,
        joins: None,
        ctes: None,
        distinct: false,
        distinct_on: None,
        set_operation: None,
    }
}

fn facade_with_mock(plan: QueryPlan) -> VlorQl {
    VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("sqlite")
        .with_llm_client(MockLlmClient::success(plan))
        .build()
        .expect("facade should build")
}

#[tokio::test]
async fn query_runs_prompt_validation_and_compilation() {
    let boxed_client: Box<dyn LlmClient> = Box::new(MockLlmClient::success(valid_plan()));
    let facade = VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("sqlite")
        .with_llm_client(boxed_client)
        .build()
        .expect("boxed client should build");
    let (compiled, _usage) = facade
        .query("show user ids")
        .await
        .expect("valid mock plan should compile");
    assert_eq!(compiled.dialect, SqlDialect::Sqlite);
    assert_eq!(
        compiled.sql,
        "SELECT \"t1\".\"id\" FROM \"users\" AS \"t1\""
    );
}

#[tokio::test]
async fn query_requires_an_llm_client_but_validate_only_does_not() {
    let facade = VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("postgres")
        .build()
        .expect("facade without LLM should still build");
    let error = facade
        .query("show users")
        .await
        .expect_err("query should require an LLM client");
    assert_eq!(error.error_code(), "G001");
    assert!(facade.validate_only(&valid_plan()).is_ok());
}

#[test]
fn builder_checks_schema_and_dialect() {
    assert_eq!(
        VlorQl::builder()
            .with_dialect_name("sqlite")
            .build()
            .expect_err("schema is required")
            .error_code(),
        "G002"
    );
    assert_eq!(
        VlorQl::builder()
            .with_schema(schema())
            .with_dialect_name("unknown")
            .build()
            .expect_err("dialect should be checked")
            .error_code(),
        "G003"
    );
}

#[cfg(test)]
struct SequenceClient {
    plans: Mutex<Vec<QueryPlan>>,
    config: LlmConfig,
}

#[cfg(test)]
#[async_trait]
impl LlmClient for SequenceClient {
    async fn generate_plan(
        &self,
        _question: &str,
        _system_prompt: &str,
        _temperature: Option<f32>,
    ) -> Result<(QueryPlan, TokenUsage), VlorQLError> {
        let plan = self
            .plans
            .lock()
            .expect("sequence lock should not be poisoned")
            .pop()
            .ok_or_else(|| {
                VlorQLError::llm(
                    LlmErrorKind::ParseError {
                        details: "sequence exhausted".to_owned(),
                    },
                    json!({}),
                )
            })?;
        Ok((plan, TokenUsage::default()))
    }

    async fn stream_plan(
        &self,
        question: String,
        system_prompt: String,
    ) -> Result<StreamResult, VlorQLError> {
        let (plan, _usage) = self.generate_plan(&question, &system_prompt, None).await?;
        let serialized = serde_json::to_string(&plan).unwrap_or_default();
        let stream = Box::new(futures::stream::iter(vec![Ok(serialized)]))
            as Box<dyn futures::stream::Stream<Item = Result<String, VlorQLError>> + Send + Unpin>;
        let usage = Arc::new(tokio::sync::Mutex::new(Some(TokenUsage::default())));
        Ok(StreamResult { stream, usage })
    }

    fn provider(&self) -> vlorql_llm::LlmProvider {
        vlorql_llm::LlmProvider::OpenAi
    }

    fn config(&self) -> &vlorql_llm::LlmConfig {
        &self.config
    }
}

#[tokio::test]
async fn query_retries_retryable_validation_errors() {
    let mut invalid = valid_plan();
    invalid.r#where = Some(Predicate::Comparison {
        left: Box::new(Expression::ColumnRef {
            table: Some("users".to_owned()),
            column: "name".to_owned(),
        }),
        op: vlorql_core::schema::ComparisonOperator::Eq,
        right: Box::new(Expression::Literal {
            value: serde_json::json!(1),
            data_type: DataType::Int,
        }),
    });
    let sequence = SequenceClient {
        plans: Mutex::new(vec![valid_plan(), invalid]),
        config: LlmConfig::default(),
    };
    let facade = VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("postgres")
        .with_llm_client(sequence)
        .with_max_retries(2)
        .build()
        .expect("facade should build");

    let (compiled, _usage) = facade
        .query("show user ids")
        .await
        .expect("second valid plan should be used");
    assert!(compiled.sql.contains("SELECT"));
}

#[test]
fn with_llm_config_creates_facade() {
    let config = LlmConfig {
        provider: LlmProvider::Ollama,
        model: "llama3".to_owned(),
        ..LlmConfig::default()
    };
    let v = VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("sqlite")
        .with_llm_config(config)
        .build()
        .expect("facade should build with config");
    assert_eq!(v.max_retries(), 3);
}

#[test]
fn validation_and_compilation_helpers_are_public() {
    let facade = facade_with_mock(valid_plan());
    let validated = facade
        .validate_only(&valid_plan())
        .expect("plan should validate");
    let compiled = facade
        .compile_only(&validated)
        .expect("plan should compile");
    assert!(compiled.sql.contains("users"));
}

#[tokio::test]
async fn query_stream_emits_chunks_then_plan_complete() {
    use futures::StreamExt;
    let facade = VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("sqlite")
        .with_policy(PolicyConfig::default())
        .with_llm_client(MockLlmClient::success(valid_plan()))
        .build()
        .expect("facade should build");
    let mut stream = facade
        .query_stream("list users")
        .await
        .expect("query_stream should succeed");
    let mut final_plan = None;
    let mut saw_chunks = false;
    let mut saw_usage = false;
    while let Some(item) = stream.next().await {
        match item.expect("event should be Ok") {
            StreamEvent::TextChunk(_) => saw_chunks = true,
            StreamEvent::PlanComplete(plan) => final_plan = Some(*plan),
            StreamEvent::TokenUsage(usage) => {
                saw_usage = true;
                assert_eq!(usage, TokenUsage::default());
            }
            StreamEvent::Error(error) => panic!("unexpected error event: {error}"),
        }
    }
    assert!(saw_chunks, "should receive at least one text chunk");
    assert_eq!(final_plan, Some(valid_plan()));
    assert!(saw_usage, "should receive token usage event");
}

#[tokio::test]
async fn span_hierarchy_includes_query_validate_compile() {
    use tracing_subscriber::Layer;
    use tracing_subscriber::layer::SubscriberExt;

    let events = Arc::new(Mutex::new(Vec::<String>::new()));
    let events_clone = Arc::clone(&events);

    let layer = tracing_subscriber::fmt::layer()
        .with_test_writer()
        .with_filter(tracing_subscriber::filter::filter_fn(|meta| {
            meta.target().starts_with("vlorql")
        }));

    let subscriber = tracing_subscriber::registry().with(layer);
    let _guard = tracing::subscriber::set_default(subscriber);

    let facade = VlorQl::builder()
        .with_schema(schema())
        .with_dialect_name("sqlite")
        .with_llm_client(MockLlmClient::success(valid_plan()))
        .build()
        .expect("facade should build");

    let (compiled, _usage) = facade
        .query("show user ids")
        .await
        .expect("valid mock plan should compile");

    assert_eq!(compiled.dialect, SqlDialect::Sqlite);
    assert_eq!(
        compiled.sql,
        "SELECT \"t1\".\"id\" FROM \"users\" AS \"t1\""
    );
    drop(
        events_clone
            .lock()
            .expect("events lock should not be poisoned"),
    );
}

#[test]
fn json_logs_contain_trace_id_and_span_id() {
    use std::sync::LazyLock;
    use std::sync::Mutex;
    static BUF: LazyLock<Mutex<Vec<u8>>> = LazyLock::new(|| Mutex::new(Vec::new()));

    let subscriber = tracing_subscriber::fmt()
        .json()
        .with_target(true)
        .with_current_span(true)
        .with_span_list(true)
        .with_thread_ids(false)
        .with_file(false)
        .with_line_number(false)
        .with_writer(move || {
            let buf = BUF.lock().expect("lock");
            let data = buf.clone();
            Box::new(std::io::Cursor::new(data)) as Box<dyn std::io::Write + Send>
        })
        .finish();

    let _guard = tracing::subscriber::set_default(subscriber);

    let span = tracing::info_span!("test_span", key = "value");
    let _enter = span.enter();
    tracing::info!("test event inside span");
    drop(_enter);
    drop(_guard);

    let buf_guard = BUF.lock().expect("lock");
    let output = String::from_utf8_lossy(&buf_guard);
    if !output.is_empty() {
        for line in output.lines() {
            if line.contains("span") {
                let parsed: serde_json::Value =
                    serde_json::from_str(line).expect("each line should be valid JSON");
                assert!(parsed.is_object(), "JSON log line should be an object");
            }
        }
    }
}