skardi 0.4.0

High performance query engine for both offline compute and online serving
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
//! Table function for Lance KNN search
//!
//! Usage:
//! ```sql
//! -- With literal vector
//! SELECT * FROM lance_knn('table_name', 'embedding', [0.1, 0.2, ...], 10)
//!
//! -- With subquery vector
//! SELECT * FROM lance_knn('table_name', 'embedding',
//!     (SELECT embedding FROM users WHERE id = $1), 10)
//!
//! -- With optional filter
//! SELECT * FROM lance_knn('table_name', 'embedding',
//!     (SELECT embedding FROM users WHERE id = $1), 10, 'category = ''electronics''')
//! ```

use arrow::array::{Array, ArrayRef, Float32Array, Float64Array};
use arrow::datatypes::{DataType, Field, SchemaRef};
use async_trait::async_trait;
use datafusion::catalog::{Session, TableFunctionImpl, TableProvider};
use datafusion::common::{Result as DFResult, ScalarValue, plan_err};
use datafusion::datasource::TableType;
use datafusion::logical_expr::Expr;
use datafusion::logical_expr::TableProviderFilterPushDown;
use datafusion::physical_plan::ExecutionPlan;
use lance::dataset::Dataset;
use std::any::Any;
use std::sync::Arc;

use super::knn_exec::LanceKnnExec;
use super::utils::expr_to_lance_sql;
use crate::sources::providers::knn_utils::extract_k;
use crate::sources::providers::{DatasetEntry, DatasetRegistry};

/// Table function that creates KNN search on Lance tables
#[derive(Debug)]
pub struct LanceKnnTableFunction {
    dataset_registry: DatasetRegistry,
}

impl LanceKnnTableFunction {
    pub fn new(dataset_registry: DatasetRegistry) -> Self {
        Self { dataset_registry }
    }
}

impl TableFunctionImpl for LanceKnnTableFunction {
    fn call(&self, exprs: &[Expr]) -> DFResult<Arc<dyn TableProvider>> {
        if exprs.len() < 4 || exprs.len() > 5 {
            return plan_err!(
                "lance_knn(table_name, vector_column, query_vector, k, [filter]) expects 4-5 arguments, got {}",
                exprs.len()
            );
        }

        // Extract string arguments
        let table_name = extract_string(&exprs[0], "table_name")?;
        let vector_column = extract_string(&exprs[1], "vector_column")?;
        let k = extract_k(&exprs[3], "lance_knn")?;
        let filter = if exprs.len() == 5 {
            Some(extract_string(&exprs[4], "filter")?)
        } else {
            None
        };

        // Get dataset from registry
        let dataset = {
            let registry = self.dataset_registry.read().map_err(|e| {
                datafusion::error::DataFusionError::Internal(format!("Registry lock error: {}", e))
            })?;
            let entry = registry.get(&table_name).cloned().ok_or_else(|| {
                datafusion::error::DataFusionError::Plan(format!(
                    "lance_knn: table '{}' not found in registry",
                    table_name
                ))
            })?;
            match entry {
                DatasetEntry::Lance(ds) => ds,
                _ => return plan_err!("lance_knn: table '{}' is not a Lance dataset", table_name),
            }
        };

        // Try to extract literal vector, otherwise store expr for subquery
        let query_vector_expr = exprs[2].clone();
        let literal_vector = try_extract_vector(&query_vector_expr)?;

        Ok(Arc::new(LanceKnnProvider {
            dataset,
            vector_column,
            literal_vector,
            query_vector_expr,
            k,
            filter,
        }))
    }
}

/// Thin wrapper that returns LanceKnnExec from scan()
struct LanceKnnProvider {
    dataset: Arc<Dataset>,
    vector_column: String,
    literal_vector: Option<ArrayRef>,
    query_vector_expr: Expr,
    k: usize,
    filter: Option<String>,
}

impl std::fmt::Debug for LanceKnnProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LanceKnnProvider")
            .field("vector_column", &self.vector_column)
            .field("k", &self.k)
            .finish()
    }
}

#[async_trait]
impl TableProvider for LanceKnnProvider {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn schema(&self) -> SchemaRef {
        // Build schema: dataset fields (excluding vector) + _distance
        let lance_schema = self.dataset.schema();
        let mut fields: Vec<Field> = lance_schema
            .fields
            .iter()
            .filter(|f| f.name.as_str() != self.vector_column)
            .map(|f| f.into())
            .collect();
        fields.push(Field::new("_distance", DataType::Float32, true));
        Arc::new(arrow::datatypes::Schema::new(fields))
    }

    fn table_type(&self) -> TableType {
        TableType::Base
    }

    fn supports_filters_pushdown(
        &self,
        filters: &[&Expr],
    ) -> DFResult<Vec<TableProviderFilterPushDown>> {
        // Accept all filters as exact pushdown — Lance's SQL filter parser handles
        // standard comparison operators (=, <, >, <=, >=, AND, OR, IN, etc.)
        Ok(filters
            .iter()
            .map(|_| TableProviderFilterPushDown::Exact)
            .collect())
    }

    async fn scan(
        &self,
        state: &dyn Session,
        projection: Option<&Vec<usize>>,
        filters: &[Expr],
        limit: Option<usize>,
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
        let mut exec = if let Some(ref vector) = self.literal_vector {
            // Literal vector path
            LanceKnnExec::try_new(
                self.dataset.clone(),
                self.vector_column.clone(),
                vector.clone(),
                self.k,
            )?
        } else {
            // Subquery path - create physical plan for deferred evaluation
            let Expr::ScalarSubquery(subquery) = &self.query_vector_expr else {
                return plan_err!(
                    "lance_knn: query_vector must be literal array or scalar subquery"
                );
            };

            let physical_plan = state
                .create_physical_plan(subquery.subquery.as_ref())
                .await?;

            let column_name = subquery
                .subquery
                .schema()
                .fields()
                .first()
                .map(|f| f.name().clone())
                .ok_or_else(|| {
                    datafusion::error::DataFusionError::Plan(
                        "lance_knn: subquery must return at least one column".to_string(),
                    )
                })?;

            LanceKnnExec::try_new_with_deferred_extraction(
                self.dataset.clone(),
                self.vector_column.clone(),
                physical_plan,
                column_name,
                self.k,
            )?
        };

        // Apply column projection if DataFusion requests a subset of columns
        if let Some(proj) = projection {
            exec = exec.with_projection(proj.clone())?;
        }

        // Combine inline filter (from function argument) with WHERE clause filters
        let mut filter_parts: Vec<String> = Vec::new();
        if let Some(ref f) = self.filter {
            filter_parts.push(f.clone());
        }
        if !filters.is_empty() {
            let where_filter = filters
                .iter()
                .map(|f| expr_to_lance_sql(f))
                .collect::<Vec<_>>()
                .join(" AND ");
            filter_parts.push(where_filter);
        }
        if !filter_parts.is_empty() {
            exec = exec.with_filter(filter_parts.join(" AND "));
        }

        // Apply scan limit if provided (e.g., from SQL LIMIT clause)
        if let Some(n) = limit {
            exec = exec.with_limit(n);
        }

        Ok(Arc::new(exec))
    }
}

// Helper functions for argument extraction

fn extract_string(expr: &Expr, name: &str) -> DFResult<String> {
    match expr {
        Expr::Literal(ScalarValue::Utf8(Some(s)), _) => Ok(s.clone()),
        Expr::Literal(ScalarValue::LargeUtf8(Some(s)), _) => Ok(s.clone()),
        _ => plan_err!("lance_knn: {} must be a string literal", name),
    }
}

fn try_extract_vector(expr: &Expr) -> DFResult<Option<ArrayRef>> {
    match expr {
        Expr::Literal(ScalarValue::List(arr), _) => {
            let list_arr = arr.as_ref();
            if list_arr.is_empty() {
                return plan_err!("lance_knn: query_vector cannot be empty");
            }
            let values = list_arr.value(0);
            extract_float32_array(&values)
        }
        Expr::Literal(ScalarValue::FixedSizeList(arr), _) => {
            let list_arr = arr.as_ref();
            if list_arr.is_empty() {
                return plan_err!("lance_knn: query_vector cannot be empty");
            }
            let values = list_arr.value(0);
            extract_float32_array(&values)
        }
        _ => Ok(None), // Not a literal, could be subquery
    }
}

/// Extract a Float32Array from an array, casting from Float64 if needed.
/// DataFusion parses untyped float literals (e.g. `[0.1, 0.2]`) as Float64,
/// but Lance expects Float32 vectors.
fn extract_float32_array(values: &dyn Array) -> DFResult<Option<ArrayRef>> {
    if let Some(f32_arr) = values.as_any().downcast_ref::<Float32Array>() {
        return Ok(Some(Arc::new(f32_arr.clone()) as ArrayRef));
    }
    if let Some(f64_arr) = values.as_any().downcast_ref::<Float64Array>() {
        let f32_arr: Float32Array = f64_arr.iter().map(|v| v.map(|x| x as f32)).collect();
        return Ok(Some(Arc::new(f32_arr) as ArrayRef));
    }
    plan_err!("lance_knn: query_vector must contain Float32 or Float64 values")
}

/// Register lance_knn table function with SessionContext
pub fn register_lance_knn_udtf(
    ctx: &datafusion::prelude::SessionContext,
    dataset_registry: DatasetRegistry,
) {
    ctx.register_udtf(
        "lance_knn",
        Arc::new(LanceKnnTableFunction::new(dataset_registry)),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sources::providers::DatasetRegistry;
    use arrow::array::{Float32Array, Int64Array, StringArray};
    use std::path::Path;

    // Uses test_data.lance which is a superset of vec_data.lance
    // with additional columns (description, category) for filter testing.
    // Schema: id (int64), vector (128-dim float), item_id (int64),
    //         revenue (float64), description (string), category (string)
    const DATASET_PATH: &str = "data/test_data.lance";

    async fn setup_knn_context() -> datafusion::prelude::SessionContext {
        use super::super::registration::register_lance_table;

        let dataset_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .join(DATASET_PATH);
        let dataset_path_str = dataset_path.to_str().unwrap();

        assert!(
            dataset_path.exists(),
            "Test dataset not found at {dataset_path_str}. \
             Run: python scripts/prepare_fts_test_data.py"
        );

        let mut ctx = datafusion::prelude::SessionContext::new();
        let registry: DatasetRegistry =
            Arc::new(std::sync::RwLock::new(std::collections::HashMap::new()));

        register_lance_table(&mut ctx, "knn_data", dataset_path_str, Some(&registry))
            .await
            .expect("Failed to register lance table");

        register_lance_knn_udtf(&ctx, registry);
        ctx
    }

    /// Read a real vector from the dataset to use as a query vector.
    /// Returns a SQL literal string like `[0.1, 0.2, ...]`.
    async fn read_query_vector(ctx: &datafusion::prelude::SessionContext) -> String {
        let df = ctx
            .sql("SELECT vector FROM knn_data LIMIT 1")
            .await
            .expect("Failed to read vector");
        let batches = df.collect().await.expect("Failed to collect vector");
        let batch = &batches[0];
        let list_col = batch
            .column(0)
            .as_any()
            .downcast_ref::<arrow::array::FixedSizeListArray>()
            .expect("vector column should be FixedSizeList");
        let values = list_col.value(0);
        let floats = values
            .as_any()
            .downcast_ref::<Float32Array>()
            .expect("vector values should be Float32");
        let elements: Vec<String> = (0..floats.len())
            .map(|i| {
                let v = floats.value(i);
                // Ensure values always have a decimal point so DataFusion parses as Float64
                if v.fract() == 0.0 {
                    format!("{:.1}", v)
                } else {
                    format!("{}", v)
                }
            })
            .collect();
        format!("[{}]", elements.join(", "))
    }

    // ── Integration tests ──
    // Require data/test_data.lance (run: python scripts/prepare_fts_test_data.py)
    // Run with: cargo test -p sources -- --ignored lance_knn

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_basic_search() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        let sql = format!(
            "SELECT id, item_id, _distance FROM lance_knn('knn_data', 'vector', {}, 5)",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");

        assert!(!batches.is_empty(), "Expected non-empty results");
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows > 0, "Expected at least 1 result");
        assert!(total_rows <= 5, "Expected at most 5 results (k=5)");

        // _distance should be non-negative
        let distances = batches[0]
            .column_by_name("_distance")
            .expect("Missing _distance column")
            .as_any()
            .downcast_ref::<Float32Array>()
            .expect("_distance should be Float32");
        for i in 0..distances.len() {
            assert!(
                !distances.is_null(i) && distances.value(i) >= 0.0,
                "_distance should be non-negative"
            );
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_distance_ordering() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        let sql = format!(
            "SELECT _distance FROM lance_knn('knn_data', 'vector', {}, 10)",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");

        let mut all_distances = Vec::new();
        for batch in &batches {
            let distances = batch
                .column_by_name("_distance")
                .unwrap()
                .as_any()
                .downcast_ref::<Float32Array>()
                .unwrap();
            for i in 0..distances.len() {
                all_distances.push(distances.value(i));
            }
        }

        // Distances should be in ascending order (nearest first)
        if all_distances.len() > 1 {
            for i in 1..all_distances.len() {
                assert!(
                    all_distances[i] >= all_distances[i - 1],
                    "Distances should be ascending: {} < {} at index {}",
                    all_distances[i],
                    all_distances[i - 1],
                    i
                );
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_schema_excludes_vector_column() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        let sql = format!(
            "SELECT * FROM lance_knn('knn_data', 'vector', {}, 1)",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let field_names: Vec<&str> = df
            .schema()
            .fields()
            .iter()
            .map(|f| f.name().as_str())
            .collect();

        assert!(field_names.contains(&"id"), "Should contain 'id'");
        assert!(field_names.contains(&"item_id"), "Should contain 'item_id'");
        assert!(
            field_names.contains(&"_distance"),
            "Should contain '_distance'"
        );
        assert!(
            !field_names.contains(&"vector"),
            "Should NOT contain 'vector' (excluded from output)"
        );
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_k_limits_results() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        for k in [1, 3, 7] {
            let sql = format!(
                "SELECT id FROM lance_knn('knn_data', 'vector', {}, {})",
                query_vec, k
            );
            let df = ctx.sql(&sql).await.expect("SQL parse failed");
            let batches = df.collect().await.expect("Query execution failed");
            let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
            assert!(
                total_rows <= k,
                "k={k}: expected at most {k} results, got {total_rows}"
            );
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_with_sql_limit() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        // Request k=10 but SQL LIMIT 3 — should return at most 3
        let sql = format!(
            "SELECT id, _distance FROM lance_knn('knn_data', 'vector', {}, 10) LIMIT 3",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(
            total_rows <= 3,
            "LIMIT 3 should restrict to at most 3 rows, got {total_rows}"
        );
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_where_category_filter() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        let sql = format!(
            "SELECT id, category, _distance \
             FROM lance_knn('knn_data', 'vector', {}, 50) \
             WHERE category = 'electronics'",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows > 0, "Expected results with category filter");

        // Every returned row must have category = 'electronics'
        for batch in &batches {
            let cats = batch
                .column_by_name("category")
                .unwrap()
                .as_any()
                .downcast_ref::<StringArray>()
                .unwrap();
            for i in 0..cats.len() {
                assert_eq!(
                    cats.value(i),
                    "electronics",
                    "WHERE filter should restrict category"
                );
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_where_numeric_filter() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        let sql = format!(
            "SELECT id, item_id, _distance \
             FROM lance_knn('knn_data', 'vector', {}, 50) \
             WHERE item_id > 500",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");

        for batch in &batches {
            let item_ids = batch
                .column_by_name("item_id")
                .unwrap()
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap();
            for i in 0..item_ids.len() {
                assert!(
                    item_ids.value(i) > 500,
                    "WHERE filter should restrict item_id > 500, got {}",
                    item_ids.value(i)
                );
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_where_compound_filter() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        let sql = format!(
            "SELECT id, category, item_id, _distance \
             FROM lance_knn('knn_data', 'vector', {}, 50) \
             WHERE category = 'electronics' AND item_id > 100",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");

        for batch in &batches {
            let cats = batch
                .column_by_name("category")
                .unwrap()
                .as_any()
                .downcast_ref::<StringArray>()
                .unwrap();
            let item_ids = batch
                .column_by_name("item_id")
                .unwrap()
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap();
            for i in 0..cats.len() {
                assert_eq!(cats.value(i), "electronics");
                assert!(item_ids.value(i) > 100);
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_where_filters_reduce_results() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        // Run without filter
        let sql_all = format!(
            "SELECT id FROM lance_knn('knn_data', 'vector', {}, 50)",
            query_vec
        );
        let df_all = ctx.sql(&sql_all).await.expect("SQL parse failed");
        let batches_all = df_all.collect().await.expect("Query execution failed");
        let rows_all: usize = batches_all.iter().map(|b| b.num_rows()).sum();

        // Run with category filter — should return fewer (or equal) rows
        let sql_filtered = format!(
            "SELECT id FROM lance_knn('knn_data', 'vector', {}, 50) \
             WHERE category = 'outdoor'",
            query_vec
        );
        let df_filtered = ctx.sql(&sql_filtered).await.expect("SQL parse failed");
        let batches_filtered = df_filtered.collect().await.expect("Query execution failed");
        let rows_filtered: usize = batches_filtered.iter().map(|b| b.num_rows()).sum();

        assert!(
            rows_filtered > 0,
            "Filtered query should still return results"
        );
        assert!(
            rows_filtered <= rows_all,
            "Filtered results ({rows_filtered}) should be <= unfiltered ({rows_all})"
        );
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_inline_filter_argument() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        // Use the 5th argument (inline filter) instead of WHERE clause
        let sql = format!(
            "SELECT id, category, _distance \
             FROM lance_knn('knn_data', 'vector', {}, 50, 'category = ''electronics''')",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(total_rows > 0, "Expected results with inline filter");

        for batch in &batches {
            let cats = batch
                .column_by_name("category")
                .unwrap()
                .as_any()
                .downcast_ref::<StringArray>()
                .unwrap();
            for i in 0..cats.len() {
                assert_eq!(
                    cats.value(i),
                    "electronics",
                    "Inline filter should restrict category"
                );
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_subquery_vector() {
        let ctx = setup_knn_context().await;

        // Use a subquery to fetch the vector for id = 1
        let sql = "SELECT id, _distance FROM lance_knn('knn_data', 'vector', \
                   (SELECT vector FROM knn_data WHERE id = 1), 5)";
        let df = ctx.sql(sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(
            total_rows > 0,
            "Subquery vector search should return results"
        );
        assert!(total_rows <= 5, "Expected at most 5 results (k=5)");

        // The first result should be the vector itself (distance ~0)
        let distances = batches[0]
            .column_by_name("_distance")
            .unwrap()
            .as_any()
            .downcast_ref::<Float32Array>()
            .unwrap();
        assert!(
            distances.value(0) < 0.001,
            "First result should be the query vector itself (distance ~0), got {}",
            distances.value(0)
        );
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_invalid_table_name() {
        let ctx = setup_knn_context().await;

        let result = ctx
            .sql("SELECT * FROM lance_knn('nonexistent_table', 'vector', [0.1, 0.2], 10)")
            .await;

        assert!(result.is_err(), "Expected error for nonexistent table");
    }

    #[tokio::test]
    #[ignore] // Requires test_data.lance
    async fn test_lance_knn_where_with_limit_combined() {
        let ctx = setup_knn_context().await;
        let query_vec = read_query_vector(&ctx).await;

        // Combine WHERE + LIMIT: k=50, filtered, then limited to 2
        let sql = format!(
            "SELECT id, category, _distance \
             FROM lance_knn('knn_data', 'vector', {}, 50) \
             WHERE category = 'electronics' \
             LIMIT 2",
            query_vec
        );
        let df = ctx.sql(&sql).await.expect("SQL parse failed");
        let batches = df.collect().await.expect("Query execution failed");
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert!(
            total_rows <= 2,
            "LIMIT 2 should restrict to at most 2 rows, got {total_rows}"
        );

        for batch in &batches {
            let cats = batch
                .column_by_name("category")
                .unwrap()
                .as_any()
                .downcast_ref::<StringArray>()
                .unwrap();
            for i in 0..cats.len() {
                assert_eq!(cats.value(i), "electronics");
            }
        }
    }
}