Skip to main content

ragfs_store/
lancedb.rs

1//! `LanceDB` implementation of `VectorStore`.
2
3use arrow_array::{
4    Array, ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, RecordBatchIterator,
5    RecordBatchReader, StringArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
6};
7use arrow_schema::{DataType, Field, Schema};
8use async_trait::async_trait;
9use chrono::Utc;
10use futures::TryStreamExt;
11use lancedb::index::Index;
12use lancedb::index::scalar::{FtsIndexBuilder, FullTextSearchQuery};
13use lancedb::index::vector::IvfPqIndexBuilder;
14use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions};
15use lancedb::table::{NewColumnTransform, OptimizeAction, OptimizeOptions};
16use lancedb::{Connection, DistanceType, Table, connect};
17use ragfs_core::{
18    Chunk, ChunkMetadata, ContentType, DirectoryScope, DistanceMetric, FileRecord, FileStatus,
19    SearchFilter, SearchQuery, SearchResult, StoreError, StoreStats, VectorStore,
20};
21use std::collections::{HashMap, HashSet};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24
25use crate::schema::{
26    CHUNKS_SCHEMA_VERSION, SCHEMA_SIDECAR_FILENAME, SchemaSidecar, effective_index_revision,
27    missing_media_columns, missing_scope_columns,
28};
29use tokio::sync::RwLock;
30use tracing::{debug, info, warn};
31use uuid::Uuid;
32
33const CHUNKS_TABLE: &str = "chunks";
34const FILES_TABLE: &str = "files";
35/// Lance IVF training uses a default sample rate of 256. Below this, stay on exact scan.
36const MIN_ANN_ROWS: usize = 256;
37/// Product default search metric (`gte-small`). Train IVF-PQ with this so ANN is valid.
38const ANN_INDEX_METRIC: DistanceMetric = DistanceMetric::Cosine;
39
40/// LanceDB-based vector store.
41pub struct LanceStore {
42    /// Path to the `LanceDB` database
43    db_path: PathBuf,
44    /// Embedding dimension
45    embedding_dim: usize,
46    /// Embedder model id that should match this index, when known.
47    embedding_model: Option<String>,
48    min_alnum_chars: Option<usize>,
49    /// Database connection (lazy initialized)
50    connection: RwLock<Option<Connection>>,
51    /// Chunks table handle
52    chunks_table: RwLock<Option<Table>>,
53    /// Files table handle
54    files_table: RwLock<Option<Table>>,
55}
56
57impl LanceStore {
58    /// Create a new `LanceStore`.
59    ///
60    /// `embedding_dim` must come from `Embedder::dimension` at the call site.
61    /// Opening an existing index whose `vector` column width differs fails in `init`.
62    #[must_use]
63    pub fn new(db_path: PathBuf, embedding_dim: usize) -> Self {
64        Self {
65            db_path,
66            embedding_dim,
67            embedding_model: None,
68            min_alnum_chars: None,
69            connection: RwLock::new(None),
70            chunks_table: RwLock::new(None),
71            files_table: RwLock::new(None),
72        }
73    }
74
75    /// Record the embedder model id in the schema sidecar.
76    #[must_use]
77    pub fn with_embedding_model(mut self, model: impl Into<String>) -> Self {
78        self.embedding_model = Some(model.into());
79        self
80    }
81
82    /// Chunk policy for newly built indexes. Query opens preserve the stored value.
83    #[must_use]
84    pub fn with_min_alnum_chars(mut self, value: usize) -> Self {
85        self.min_alnum_chars = Some(value);
86        self
87    }
88
89    /// The actual policy that produced the index, absent on legacy sidecars.
90    pub async fn indexed_min_alnum_chars(&self) -> Option<usize> {
91        self.read_schema_sidecar()
92            .await
93            .and_then(|s| s.min_alnum_chars)
94    }
95
96    /// Explicitly rebuild this index before indexing with a new model or policy.
97    /// Existing retrieval receipts are retained; their revisions remain historical.
98    pub async fn rebuild(&self) -> Result<(), StoreError> {
99        let revision = self
100            .read_schema_sidecar()
101            .await
102            .map_or(1, |s| s.index_revision.saturating_add(1));
103        let conn = self.get_connection().await?;
104        let tables = conn
105            .table_names()
106            .execute()
107            .await
108            .map_err(|e| StoreError::Init(e.to_string()))?;
109        let mut sidecar = self.sidecar_with_revision(SchemaSidecar::default(), revision);
110        sidecar.rebuild_in_progress = true;
111        self.write_schema_sidecar(&sidecar).await?;
112        for name in [CHUNKS_TABLE, FILES_TABLE] {
113            if tables.iter().any(|table| table == name) {
114                conn.drop_table(name, &[])
115                    .await
116                    .map_err(|e| StoreError::Init(format!("Failed to rebuild {name}: {e}")))?;
117            }
118        }
119        *self.chunks_table.write().await = None;
120        *self.files_table.write().await = None;
121        self.initialize_tables().await?;
122        sidecar.rebuild_in_progress = false;
123        self.write_schema_sidecar(&sidecar).await
124    }
125
126    async fn ensure_model_matches(&self) -> Result<(), StoreError> {
127        let path = self.schema_sidecar_path();
128        let sidecar = match tokio::fs::read(&path).await {
129            Ok(bytes) => Some(
130                serde_json::from_slice::<SchemaSidecar>(&bytes).map_err(|e| {
131                    StoreError::Schema(format!("Invalid index fingerprint {}: {e}", path.display()))
132                })?,
133            ),
134            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
135            Err(error) => {
136                return Err(StoreError::Schema(format!(
137                    "Cannot read index fingerprint {}: {error}",
138                    path.display()
139                )));
140            }
141        };
142        if let Some(sidecar) = sidecar {
143            if sidecar.rebuild_in_progress {
144                return Err(StoreError::Schema(
145                    "Index rebuild was interrupted; run ragfs index <path> --force".into(),
146                ));
147            }
148            if let (Some(stored), Some(requested)) = (
149                sidecar.embedding_model.as_deref(),
150                self.embedding_model.as_deref(),
151            ) && stored != requested
152            {
153                return Err(StoreError::Schema(format!(
154                    "Index embedding model {stored:?} does not match requested model {requested:?}; run ragfs index <path> --force to rebuild"
155                )));
156            }
157            if let Some(stored) = sidecar.embedding_dim
158                && stored != self.embedding_dim
159            {
160                return Err(StoreError::Schema(format!(
161                    "Index embedding dimension {stored} does not match requested dimension {}; run ragfs index <path> --force to rebuild",
162                    self.embedding_dim
163                )));
164            }
165        }
166        Ok(())
167    }
168
169    async fn initialize_tables(&self) -> Result<(), StoreError> {
170        info!("Initializing LanceDB at {:?}", self.db_path);
171
172        // Ensure directory exists
173        if let Some(parent) = self.db_path.parent() {
174            tokio::fs::create_dir_all(parent)
175                .await
176                .map_err(|e| StoreError::Init(format!("Failed to create db directory: {e}")))?;
177        }
178
179        let conn = self.get_connection().await?;
180
181        // Check existing tables
182        let tables = conn
183            .table_names()
184            .execute()
185            .await
186            .map_err(|e| StoreError::Init(format!("Failed to list tables: {e}")))?;
187
188        if tables.contains(&CHUNKS_TABLE.to_string()) {
189            self.ensure_chunks_schema().await?;
190        } else {
191            info!("Creating chunks table");
192            let schema = Arc::new(self.chunks_schema());
193            conn.create_empty_table(CHUNKS_TABLE, schema)
194                .execute()
195                .await
196                .map_err(|e| StoreError::Init(format!("Failed to create chunks table: {e}")))?;
197
198            // Create FTS index on content column for hybrid search
199            info!("Creating FTS index on content column");
200            let table = conn
201                .open_table(CHUNKS_TABLE)
202                .execute()
203                .await
204                .map_err(|e| StoreError::Init(format!("Failed to open chunks table: {e}")))?;
205
206            if let Err(e) = table
207                .create_index(&["content"], Index::FTS(FtsIndexBuilder::default()))
208                .execute()
209                .await
210            {
211                warn!("Failed to create FTS index (may already exist): {e}");
212            }
213
214            self.ensure_index_revision().await?;
215        }
216
217        // Create files table if not exists
218        if !tables.contains(&FILES_TABLE.to_string()) {
219            info!("Creating files table");
220            let schema = Arc::new(self.files_schema());
221            conn.create_empty_table(FILES_TABLE, schema)
222                .execute()
223                .await
224                .map_err(|e| StoreError::Init(format!("Failed to create files table: {e}")))?;
225        }
226
227        // Existing tables may already have enough rows for ANN.
228        if let Err(e) = self.ensure_vector_index().await {
229            warn!("ANN index check on init failed: {e}");
230        }
231
232        self.ensure_index_revision().await?;
233
234        info!("LanceDB initialized successfully");
235        Ok(())
236    }
237
238    /// Get the database path.
239    pub fn db_path(&self) -> &Path {
240        &self.db_path
241    }
242
243    /// Get the embedding dimension.
244    pub fn embedding_dim(&self) -> usize {
245        self.embedding_dim
246    }
247
248    /// Width of the chunks `vector` `FixedSizeList`.
249    fn stored_embedding_dim(schema: &Schema) -> Result<usize, StoreError> {
250        let field = schema.field_with_name("vector").map_err(|_| {
251            StoreError::Schema("chunks table is missing the 'vector' column".into())
252        })?;
253        match field.data_type() {
254            DataType::FixedSizeList(_, size) => Ok(*size as usize),
255            other => Err(StoreError::Schema(format!(
256                "chunks 'vector' column has type {other:?}, expected FixedSizeList"
257            ))),
258        }
259    }
260
261    fn ensure_embedding_dim_matches(&self, schema: &Schema) -> Result<(), StoreError> {
262        let stored = Self::stored_embedding_dim(schema)?;
263        if stored != self.embedding_dim {
264            return Err(StoreError::Schema(format!(
265                "Index embedding dimension {stored} does not match embedder dimension {}",
266                self.embedding_dim
267            )));
268        }
269        Ok(())
270    }
271
272    /// Whether the table is large enough for Lance IVF-PQ training.
273    pub(crate) fn should_build_ann_index(row_count: usize) -> bool {
274        row_count >= MIN_ANN_ROWS
275    }
276
277    /// Refresh IVF-PQ once the unindexed tail is large enough to train another sample.
278    pub(crate) fn should_refresh_ann_index(unindexed_rows: usize) -> bool {
279        unindexed_rows >= MIN_ANN_ROWS
280    }
281
282    /// ANN is trained as cosine; other metrics must not use the index.
283    pub(crate) fn ann_index_covers_metric(metric: DistanceMetric) -> bool {
284        metric == ANN_INDEX_METRIC
285    }
286
287    /// Reuse/refresh only a cosine-trained vector index.
288    pub(crate) fn ann_index_is_cosine(distance_type: Option<DistanceType>) -> bool {
289        distance_type == Some(DistanceType::Cosine)
290    }
291
292    async fn vector_index_name(table: &Table) -> Option<String> {
293        match table.list_indices().await {
294            Ok(indices) => indices
295                .into_iter()
296                .find(|idx| idx.columns.iter().any(|col| col == "vector"))
297                .map(|idx| idx.name),
298            Err(_) => None,
299        }
300    }
301
302    async fn refresh_vector_index(table: &Table, index_name: &str) {
303        let unindexed = match table.index_stats(index_name).await {
304            Ok(Some(stats)) => stats.num_unindexed_rows,
305            Ok(None) => return,
306            Err(e) => {
307                debug!("Skipping ANN refresh; could not read index stats: {e}");
308                return;
309            }
310        };
311
312        if !Self::should_refresh_ann_index(unindexed) {
313            debug!("Skipping ANN refresh: {unindexed} unindexed rows < {MIN_ANN_ROWS}");
314            return;
315        }
316
317        info!("Refreshing IVF-PQ ANN index ({unindexed} unindexed rows)");
318        match table
319            .optimize(OptimizeAction::Index(
320                OptimizeOptions::append().index_names(vec![index_name.to_string()]),
321            ))
322            .await
323        {
324            Ok(_) => info!("IVF-PQ ANN index refreshed"),
325            Err(e) => warn!("IVF-PQ ANN index refresh failed (unindexed tail stays exact): {e}"),
326        }
327    }
328
329    /// Best-effort IVF-PQ on `vector`. Small tables keep exact scan.
330    /// Existing cosine indexes are incrementally refreshed after large appends.
331    /// A non-cosine vector index is dropped and replaced when the table is large enough.
332    async fn ensure_vector_index(&self) -> Result<(), StoreError> {
333        let table = self.get_chunks_table().await?;
334        if let Some(name) = Self::vector_index_name(&table).await {
335            match table.index_stats(&name).await {
336                Ok(Some(stats)) if Self::ann_index_is_cosine(stats.distance_type) => {
337                    Self::refresh_vector_index(&table, &name).await;
338                    return Ok(());
339                }
340                Ok(Some(stats)) => {
341                    info!(
342                        "Replacing vector index trained as {:?} with cosine IVF-PQ",
343                        stats.distance_type
344                    );
345                    if let Err(e) = table.drop_index(&name).await {
346                        warn!("Could not drop mismatched vector index (search may bypass): {e}");
347                        return Ok(());
348                    }
349                }
350                Ok(None) => {}
351                Err(e) => {
352                    debug!("Skipping ANN reuse; could not read index stats: {e}");
353                    return Ok(());
354                }
355            }
356        }
357
358        let count = match table.count_rows(None).await {
359            Ok(n) => n,
360            Err(e) => {
361                debug!("Skipping ANN index; could not count rows: {e}");
362                return Ok(());
363            }
364        };
365
366        if !Self::should_build_ann_index(count) {
367            debug!("Skipping IVF-PQ ANN index: {count} rows < {MIN_ANN_ROWS} (exact scan)");
368            return Ok(());
369        }
370
371        info!("Creating IVF-PQ ANN index on vector ({count} rows, cosine)");
372        match table
373            .create_index(
374                &["vector"],
375                Index::IvfPq(IvfPqIndexBuilder::default().distance_type(DistanceType::Cosine)),
376            )
377            .execute()
378            .await
379        {
380            Ok(()) => info!("IVF-PQ ANN index ready"),
381            Err(e) => warn!("IVF-PQ ANN index not created (search stays exact scan): {e}"),
382        }
383        Ok(())
384    }
385
386    /// Get or create connection.
387    async fn get_connection(&self) -> Result<Connection, StoreError> {
388        {
389            let conn = self.connection.read().await;
390            if let Some(ref c) = *conn {
391                return Ok(c.clone());
392            }
393        }
394
395        let mut conn = self.connection.write().await;
396        if conn.is_none() {
397            let db_path_str = self.db_path.to_string_lossy().to_string();
398            let new_conn = connect(&db_path_str)
399                .execute()
400                .await
401                .map_err(|e| StoreError::Init(format!("Failed to connect to LanceDB: {e}")))?;
402            *conn = Some(new_conn);
403        }
404        Ok(conn.as_ref().unwrap().clone())
405    }
406
407    /// Build chunks table schema.
408    fn chunks_schema(&self) -> Schema {
409        Schema::new(vec![
410            Field::new("chunk_id", DataType::Utf8, false),
411            Field::new("file_id", DataType::Utf8, false),
412            Field::new("file_path", DataType::Utf8, false),
413            Field::new("content", DataType::Utf8, false),
414            Field::new("content_type", DataType::Utf8, false),
415            Field::new("chunk_index", DataType::UInt32, false),
416            Field::new("start_byte", DataType::UInt64, false),
417            Field::new("end_byte", DataType::UInt64, false),
418            Field::new("start_line", DataType::UInt32, true),
419            Field::new("end_line", DataType::UInt32, true),
420            Field::new("parent_chunk_id", DataType::Utf8, true),
421            Field::new("depth", DataType::UInt8, false),
422            Field::new(
423                "vector",
424                DataType::FixedSizeList(
425                    Arc::new(Field::new("item", DataType::Float32, true)),
426                    self.embedding_dim as i32,
427                ),
428                false,
429            ),
430            Field::new("embedding_model", DataType::Utf8, true),
431            Field::new("indexed_at", DataType::Utf8, false),
432            Field::new("file_mime_type", DataType::Utf8, true),
433            Field::new("language", DataType::Utf8, true),
434            Field::new("symbol_type", DataType::Utf8, true),
435            Field::new("symbol_name", DataType::Utf8, true),
436            Field::new("dir_path", DataType::Utf8, false),
437            Field::new("dir_depth", DataType::UInt16, false),
438            Field::new("path_components", DataType::Utf8, false),
439            Field::new("modality", DataType::Utf8, true),
440            Field::new("start_ms", DataType::UInt64, true),
441            Field::new("end_ms", DataType::UInt64, true),
442        ])
443    }
444
445    /// Build files table schema.
446    fn files_schema(&self) -> Schema {
447        Schema::new(vec![
448            Field::new("file_id", DataType::Utf8, false),
449            Field::new("path", DataType::Utf8, false),
450            Field::new("size_bytes", DataType::UInt64, false),
451            Field::new("mime_type", DataType::Utf8, false),
452            Field::new("content_hash", DataType::Utf8, false),
453            Field::new("modified_at", DataType::Utf8, false),
454            Field::new("indexed_at", DataType::Utf8, true),
455            Field::new("chunk_count", DataType::UInt32, false),
456            Field::new("status", DataType::Utf8, false),
457            Field::new("error_message", DataType::Utf8, true),
458        ])
459    }
460
461    /// Get or open chunks table.
462    async fn get_chunks_table(&self) -> Result<Table, StoreError> {
463        {
464            let table = self.chunks_table.read().await;
465            if let Some(ref t) = *table {
466                return Ok(t.clone());
467            }
468        }
469
470        let conn = self.get_connection().await?;
471        let mut table_lock = self.chunks_table.write().await;
472
473        if table_lock.is_none() {
474            let t = conn
475                .open_table(CHUNKS_TABLE)
476                .execute()
477                .await
478                .map_err(|e| StoreError::Init(format!("Failed to open chunks table: {e}")))?;
479            *table_lock = Some(t);
480        }
481
482        Ok(table_lock.as_ref().unwrap().clone())
483    }
484
485    /// Get or open files table.
486    async fn get_files_table(&self) -> Result<Table, StoreError> {
487        {
488            let table = self.files_table.read().await;
489            if let Some(ref t) = *table {
490                return Ok(t.clone());
491            }
492        }
493
494        let conn = self.get_connection().await?;
495        let mut table_lock = self.files_table.write().await;
496
497        if table_lock.is_none() {
498            let t = conn
499                .open_table(FILES_TABLE)
500                .execute()
501                .await
502                .map_err(|e| StoreError::Init(format!("Failed to open files table: {e}")))?;
503            *table_lock = Some(t);
504        }
505
506        Ok(table_lock.as_ref().unwrap().clone())
507    }
508
509    fn schema_sidecar_path(&self) -> PathBuf {
510        self.db_path
511            .parent()
512            .unwrap_or(self.db_path.as_path())
513            .join(SCHEMA_SIDECAR_FILENAME)
514    }
515
516    async fn read_schema_sidecar(&self) -> Option<SchemaSidecar> {
517        let bytes = tokio::fs::read(self.schema_sidecar_path()).await.ok()?;
518        serde_json::from_slice::<SchemaSidecar>(&bytes).ok()
519    }
520
521    fn sidecar_with_revision(
522        &self,
523        mut sidecar: SchemaSidecar,
524        index_revision: u64,
525    ) -> SchemaSidecar {
526        sidecar.chunks_schema_version = sidecar.chunks_schema_version.max(CHUNKS_SCHEMA_VERSION);
527        if sidecar.embedding_dim.is_none() {
528            sidecar.embedding_dim = Some(self.embedding_dim);
529        }
530        if sidecar.embedding_model.is_none() {
531            sidecar.embedding_model.clone_from(&self.embedding_model);
532        }
533        if sidecar.min_alnum_chars.is_none() {
534            sidecar.min_alnum_chars = self.min_alnum_chars;
535        }
536        sidecar.index_revision = index_revision;
537        sidecar
538    }
539
540    async fn write_schema_sidecar(&self, sidecar: &SchemaSidecar) -> Result<(), StoreError> {
541        let path = self.schema_sidecar_path();
542        if let Some(parent) = path.parent() {
543            tokio::fs::create_dir_all(parent).await.map_err(|e| {
544                StoreError::Schema(format!(
545                    "Failed to create schema sidecar directory {}: {e}",
546                    parent.display()
547                ))
548            })?;
549        }
550        let json = serde_json::to_string_pretty(sidecar)
551            .map_err(|e| StoreError::Schema(format!("Failed to serialize schema sidecar: {e}")))?;
552        tokio::fs::write(&path, json).await.map_err(|e| {
553            StoreError::Schema(format!(
554                "Failed to write schema sidecar {}: {e}",
555                path.display()
556            ))
557        })?;
558        Ok(())
559    }
560
561    /// Persist `index_revision = 1` on old sidecars without rewriting Lance tables.
562    async fn ensure_index_revision(&self) -> Result<u64, StoreError> {
563        let existing = self.read_schema_sidecar().await;
564        if let Some(s) = &existing
565            && s.index_revision > 0
566        {
567            return Ok(s.index_revision);
568        }
569        let revision = effective_index_revision(existing.as_ref().map_or(0, |s| s.index_revision));
570        let sidecar = self.sidecar_with_revision(existing.unwrap_or_default(), revision);
571        self.write_schema_sidecar(&sidecar).await?;
572        Ok(revision)
573    }
574
575    async fn current_index_revision(&self) -> u64 {
576        effective_index_revision(
577            self.read_schema_sidecar()
578                .await
579                .map_or(0, |s| s.index_revision),
580        )
581    }
582
583    async fn bump_index_revision(&self) -> Result<u64, StoreError> {
584        let existing = self.read_schema_sidecar().await;
585        let next = effective_index_revision(existing.as_ref().map_or(0, |s| s.index_revision))
586            .saturating_add(1);
587        let sidecar = self.sidecar_with_revision(existing.unwrap_or_default(), next);
588        self.write_schema_sidecar(&sidecar).await?;
589        Ok(next)
590    }
591
592    /// Cheap revision read used by `ragfs query` / `ragfs status` (avoids a table scan).
593    pub async fn index_revision(&self) -> Result<u64, StoreError> {
594        Ok(self.current_index_revision().await)
595    }
596
597    async fn upsert_chunks_inner(&self, chunks: &[Chunk]) -> Result<(), StoreError> {
598        if chunks.is_empty() {
599            return Ok(());
600        }
601
602        debug!("Upserting {} chunks", chunks.len());
603
604        let table = self.get_chunks_table().await?;
605        let batch = self.chunks_to_batch(chunks)?;
606        let schema = batch.schema();
607
608        let batches = RecordBatchIterator::new(vec![Ok(batch)], schema);
609
610        table
611            .add(Box::new(batches) as Box<dyn RecordBatchReader + Send>)
612            .execute()
613            .await
614            .map_err(|e| StoreError::Insert(format!("Failed to insert chunks: {e}")))?;
615
616        debug!("Successfully upserted {} chunks", chunks.len());
617        if let Err(e) = self.ensure_vector_index().await {
618            warn!("ANN index check after upsert failed: {e}");
619        }
620        Ok(())
621    }
622
623    async fn delete_by_file_path_inner(&self, path: &Path) -> Result<u64, StoreError> {
624        let path_str = path.to_string_lossy().to_string();
625        debug!("Deleting chunks for file: {}", path_str);
626
627        let table = self.get_chunks_table().await?;
628
629        table
630            .delete(&format!("file_path = '{}'", path_str.replace('\'', "''")))
631            .await
632            .map_err(|e| StoreError::Delete(format!("Failed to delete chunks: {e}")))?;
633
634        let files_table = self.get_files_table().await?;
635        files_table
636            .delete(&format!("path = '{}'", path_str.replace('\'', "''")))
637            .await
638            .map_err(|e| StoreError::Delete(format!("Failed to delete file record: {e}")))?;
639
640        Ok(1) // LanceDB doesn't return count, we assume success
641    }
642
643    fn schema_migration_failed_message(db_path: &Path, error: &impl std::fmt::Display) -> String {
644        let index_dir = db_path.parent().unwrap_or(db_path);
645        format!(
646            "Existing Lance index is missing directory-scope columns \
647             (dir_path, dir_depth, path_components) and automatic schema \
648             migration to v{CHUNKS_SCHEMA_VERSION} failed ({error}). \
649             The index was not deleted. Remove `{}` and run \
650             `ragfs index <dir> --force` to rebuild.",
651            index_dir.display()
652        )
653    }
654
655    /// Detect a pre-v2 chunks table, add scope columns, and backfill from `file_path`.
656    ///
657    /// `--force` rewrites index-root-relative `dir_path` on new upserts; it cannot
658    /// add Lance columns. This path is what existing indexes need on upgrade.
659    async fn ensure_chunks_schema(&self) -> Result<(), StoreError> {
660        let table = {
661            let conn = self.get_connection().await?;
662            conn.open_table(CHUNKS_TABLE)
663                .execute()
664                .await
665                .map_err(|e| StoreError::Init(format!("Failed to open chunks table: {e}")))?
666        };
667
668        let schema = table
669            .schema()
670            .await
671            .map_err(|e| StoreError::Schema(format!("Failed to read chunks schema: {e}")))?;
672        self.ensure_embedding_dim_matches(&schema)?;
673        let mut missing = missing_scope_columns(&schema);
674        let needs_scope_backfill = !missing.is_empty();
675        missing.extend(missing_media_columns(&schema));
676        let sidecar_version = self
677            .read_schema_sidecar()
678            .await
679            .map_or(0, |s| s.chunks_schema_version);
680
681        if missing.is_empty() && sidecar_version >= CHUNKS_SCHEMA_VERSION {
682            return Ok(());
683        }
684
685        if !missing.is_empty() {
686            info!(
687                "Migrating chunks table to schema v{CHUNKS_SCHEMA_VERSION} \
688                 (adding scope and media columns)"
689            );
690            table
691                .add_columns()
692                .transform(NewColumnTransform::AllNulls(Arc::new(Schema::new(missing))))
693                .execute()
694                .await
695                .map_err(|e| {
696                    StoreError::Schema(Self::schema_migration_failed_message(&self.db_path, &e))
697                })?;
698
699            // Drop the cached handle so later ops see the evolved schema.
700            *self.chunks_table.write().await = None;
701        }
702
703        if needs_scope_backfill || sidecar_version < 2 {
704            self.backfill_scope_columns().await?;
705        }
706        self.get_chunks_table()
707            .await?
708            .update()
709            .only_if("modality IS NULL")
710            .column("modality", "'text'")
711            .execute()
712            .await
713            .map_err(|e| StoreError::Schema(format!("Media backfill failed: {e}")))?;
714        self.ensure_index_revision().await?;
715        info!("Chunks table schema is v{CHUNKS_SCHEMA_VERSION}");
716        Ok(())
717    }
718
719    async fn backfill_scope_columns(&self) -> Result<(), StoreError> {
720        let table = self.get_chunks_table().await?;
721        let mut results = table
722            .query()
723            .only_if("dir_path IS NULL OR dir_path = ''")
724            .execute()
725            .await
726            .map_err(|e| {
727                StoreError::Schema(format!(
728                    "Failed to scan chunks for directory-scope backfill: {e}"
729                ))
730            })?;
731
732        let mut paths = HashSet::new();
733        while let Some(batch) = results.try_next().await.map_err(|e| {
734            StoreError::Schema(format!(
735                "Failed to read chunks for directory-scope backfill: {e}"
736            ))
737        })? {
738            let Some(file_paths) = batch
739                .column_by_name("file_path")
740                .and_then(|c| c.as_any().downcast_ref::<StringArray>())
741            else {
742                continue;
743            };
744            for i in 0..batch.num_rows() {
745                if !file_paths.is_null(i) {
746                    paths.insert(file_paths.value(i).to_string());
747                }
748            }
749        }
750
751        if paths.is_empty() {
752            return Ok(());
753        }
754
755        info!(
756            "Backfilling directory-scope columns for {} file path(s)",
757            paths.len()
758        );
759        for path in paths {
760            let scope = DirectoryScope::from_file_path(Path::new(&path));
761            table
762                .update()
763                .only_if(format!("file_path = '{}'", escape_sql_literal(&path)))
764                .column(
765                    "dir_path",
766                    format!("'{}'", escape_sql_literal(&scope.dir_path)),
767                )
768                .column("dir_depth", scope.dir_depth.to_string())
769                .column(
770                    "path_components",
771                    format!("'{}'", escape_sql_literal(&scope.path_components)),
772                )
773                .execute()
774                .await
775                .map_err(|e| {
776                    StoreError::Schema(format!(
777                        "Failed to backfill directory-scope columns for '{path}': {e}"
778                    ))
779                })?;
780        }
781        Ok(())
782    }
783
784    /// Convert chunks to Arrow `RecordBatch`.
785    fn chunks_to_batch(&self, chunks: &[Chunk]) -> Result<RecordBatch, StoreError> {
786        for chunk in chunks {
787            chunk
788                .metadata
789                .media
790                .validate()
791                .map_err(StoreError::Insert)?;
792        }
793        let modalities: Vec<_> = chunks
794            .iter()
795            .map(|c| c.metadata.media.modality.clone())
796            .collect();
797        let start_ms: Vec<_> = chunks.iter().map(|c| c.metadata.media.start_ms).collect();
798        let end_ms: Vec<_> = chunks.iter().map(|c| c.metadata.media.end_ms).collect();
799        let chunk_ids: Vec<_> = chunks.iter().map(|c| c.id.to_string()).collect();
800        let file_ids: Vec<_> = chunks.iter().map(|c| c.file_id.to_string()).collect();
801        let file_paths: Vec<_> = chunks
802            .iter()
803            .map(|c| c.file_path.to_string_lossy().to_string())
804            .collect();
805        let contents: Vec<_> = chunks.iter().map(|c| c.content.clone()).collect();
806        let content_types: Vec<_> = chunks
807            .iter()
808            .map(|c| content_type_to_string(&c.content_type))
809            .collect();
810        let chunk_indices: Vec<_> = chunks.iter().map(|c| c.chunk_index).collect();
811        let start_bytes: Vec<_> = chunks.iter().map(|c| c.byte_range.start).collect();
812        let end_bytes: Vec<_> = chunks.iter().map(|c| c.byte_range.end).collect();
813        let start_lines: Vec<_> = chunks
814            .iter()
815            .map(|c| c.line_range.as_ref().map(|r| r.start))
816            .collect();
817        let end_lines: Vec<_> = chunks
818            .iter()
819            .map(|c| c.line_range.as_ref().map(|r| r.end))
820            .collect();
821        let parent_ids: Vec<_> = chunks
822            .iter()
823            .map(|c| c.parent_chunk_id.map(|id| id.to_string()))
824            .collect();
825        let depths: Vec<_> = chunks.iter().map(|c| c.depth).collect();
826
827        // Build embeddings as FixedSizeList
828        let embeddings: Vec<Option<Vec<Option<f32>>>> = chunks
829            .iter()
830            .map(|c| {
831                c.embedding
832                    .as_ref()
833                    .map(|e| e.iter().map(|&v| Some(v)).collect())
834            })
835            .collect();
836
837        let embedding_models: Vec<_> = chunks
838            .iter()
839            .map(|c| c.metadata.embedding_model.clone())
840            .collect();
841        let indexed_ats: Vec<_> = chunks
842            .iter()
843            .map(|c| {
844                c.metadata
845                    .indexed_at
846                    .map_or_else(|| Utc::now().to_rfc3339(), |t| t.to_rfc3339())
847            })
848            .collect();
849
850        // Extract language/symbol info from content_type
851        let languages: Vec<_> = chunks
852            .iter()
853            .map(|c| match &c.content_type {
854                ContentType::Code { language, .. } => Some(language.clone()),
855                _ => None,
856            })
857            .collect();
858        let symbol_types: Vec<_> = chunks
859            .iter()
860            .map(|c| match &c.content_type {
861                ContentType::Code { symbol, .. } => {
862                    symbol.as_ref().map(|s| format!("{:?}", s.kind))
863                }
864                _ => None,
865            })
866            .collect();
867        let symbol_names: Vec<_> = chunks
868            .iter()
869            .map(|c| match &c.content_type {
870                ContentType::Code { symbol, .. } => symbol.as_ref().map(|s| s.name.clone()),
871                _ => None,
872            })
873            .collect();
874
875        let mime_types: Vec<Option<String>> = chunks.iter().map(|c| c.mime_type.clone()).collect();
876
877        let dir_paths: Vec<_> = chunks.iter().map(|c| c.dir_path.clone()).collect();
878        let dir_depths: Vec<_> = chunks.iter().map(|c| c.dir_depth).collect();
879        let path_components: Vec<_> = chunks.iter().map(|c| c.path_components.clone()).collect();
880
881        // Build arrays
882        let schema = Arc::new(self.chunks_schema());
883
884        let vector_array = build_vector_array(&embeddings, self.embedding_dim)?;
885
886        let batch = RecordBatch::try_new(
887            schema,
888            vec![
889                Arc::new(StringArray::from(chunk_ids)),
890                Arc::new(StringArray::from(file_ids)),
891                Arc::new(StringArray::from(file_paths)),
892                Arc::new(StringArray::from(contents)),
893                Arc::new(StringArray::from(content_types)),
894                Arc::new(UInt32Array::from(chunk_indices)),
895                Arc::new(UInt64Array::from(start_bytes)),
896                Arc::new(UInt64Array::from(end_bytes)),
897                Arc::new(UInt32Array::from(start_lines)),
898                Arc::new(UInt32Array::from(end_lines)),
899                Arc::new(StringArray::from(parent_ids)),
900                Arc::new(UInt8Array::from(depths)),
901                vector_array,
902                Arc::new(StringArray::from(embedding_models)),
903                Arc::new(StringArray::from(indexed_ats)),
904                Arc::new(StringArray::from(mime_types.clone())),
905                Arc::new(StringArray::from(languages)),
906                Arc::new(StringArray::from(symbol_types)),
907                Arc::new(StringArray::from(symbol_names)),
908                Arc::new(StringArray::from(dir_paths)),
909                Arc::new(UInt16Array::from(dir_depths)),
910                Arc::new(StringArray::from(path_components)),
911                Arc::new(StringArray::from(modalities)),
912                Arc::new(UInt64Array::from(start_ms)),
913                Arc::new(UInt64Array::from(end_ms)),
914            ],
915        )
916        .map_err(|e| StoreError::Insert(format!("Failed to create RecordBatch: {e}")))?;
917
918        Ok(batch)
919    }
920
921    /// Convert file record to Arrow `RecordBatch`.
922    fn file_to_batch(&self, record: &FileRecord) -> Result<RecordBatch, StoreError> {
923        let schema = Arc::new(self.files_schema());
924
925        let batch = RecordBatch::try_new(
926            schema,
927            vec![
928                Arc::new(StringArray::from(vec![record.id.to_string()])),
929                Arc::new(StringArray::from(vec![
930                    record.path.to_string_lossy().to_string(),
931                ])),
932                Arc::new(UInt64Array::from(vec![record.size_bytes])),
933                Arc::new(StringArray::from(vec![record.mime_type.clone()])),
934                Arc::new(StringArray::from(vec![record.content_hash.clone()])),
935                Arc::new(StringArray::from(vec![record.modified_at.to_rfc3339()])),
936                Arc::new(StringArray::from(vec![
937                    record.indexed_at.map(|t| t.to_rfc3339()),
938                ])),
939                Arc::new(UInt32Array::from(vec![record.chunk_count])),
940                Arc::new(StringArray::from(vec![status_to_string(&record.status)])),
941                Arc::new(StringArray::from(vec![record.error_message.clone()])),
942            ],
943        )
944        .map_err(|e| StoreError::Insert(format!("Failed to create file RecordBatch: {e}")))?;
945
946        Ok(batch)
947    }
948
949    /// Combine chunk-column filters with source-file `modified_at` constraints.
950    async fn chunk_filter_sql(
951        &self,
952        filters: &[SearchFilter],
953    ) -> Result<Option<String>, StoreError> {
954        Ok(combine_predicates(
955            filters_to_sql(filters),
956            self.modified_at_path_predicate(filters).await?,
957        ))
958    }
959
960    /// Resolve `ModifiedAfter` / `ModifiedBefore` against the files table.
961    async fn modified_at_path_predicate(
962        &self,
963        filters: &[SearchFilter],
964    ) -> Result<Option<String>, StoreError> {
965        let Some(date_sql) = file_date_filters_to_sql(filters) else {
966            return Ok(None);
967        };
968
969        let table = self.get_files_table().await?;
970        let mut results = table
971            .query()
972            .only_if(date_sql)
973            .execute()
974            .await
975            .map_err(|e| StoreError::Query(format!("Failed to apply modified_at filter: {e}")))?;
976
977        let mut paths = Vec::new();
978        while let Some(batch) = results.try_next().await.map_err(|e| {
979            StoreError::Query(format!("Failed to fetch files for modified_at filter: {e}"))
980        })? {
981            for record in batch_to_file_records(&batch)? {
982                paths.push(record.path.to_string_lossy().to_string());
983            }
984        }
985
986        if paths.is_empty() {
987            return Ok(Some("1 = 0".to_string()));
988        }
989
990        let in_list = paths
991            .iter()
992            .map(|p| format!("'{}'", escape_sql_literal(p)))
993            .collect::<Vec<_>>()
994            .join(", ");
995        Ok(Some(format!("file_path IN ({in_list})")))
996    }
997}
998
999#[async_trait]
1000impl VectorStore for LanceStore {
1001    async fn init(&self) -> Result<(), StoreError> {
1002        self.ensure_model_matches().await?;
1003        self.initialize_tables().await
1004    }
1005
1006    async fn upsert_chunks(&self, chunks: &[Chunk]) -> Result<(), StoreError> {
1007        self.upsert_chunks_inner(chunks).await?;
1008        if !chunks.is_empty() {
1009            self.bump_index_revision().await?;
1010        }
1011        Ok(())
1012    }
1013
1014    async fn search(&self, query: SearchQuery) -> Result<Vec<SearchResult>, StoreError> {
1015        debug!(
1016            "Searching with limit {} metric {:?} filters {}",
1017            query.limit,
1018            query.metric,
1019            query.filters.len()
1020        );
1021
1022        let table = self.get_chunks_table().await?;
1023        let filter_sql = combine_predicates(
1024            self.chunk_filter_sql(&query.filters).await?,
1025            query.scope_prefix.as_deref().and_then(scope_prefix_sql),
1026        );
1027
1028        let mut search_q = table
1029            .vector_search(query.embedding.clone())
1030            .map_err(|e| StoreError::Query(format!("Failed to create search query: {e}")))?
1031            .distance_type(distance_type_from_metric(query.metric))
1032            .limit(query.limit);
1033
1034        if !Self::ann_index_covers_metric(query.metric) {
1035            search_q = search_q.bypass_vector_index();
1036        }
1037
1038        if let Some(ref filter) = filter_sql {
1039            debug!("Applying search filter: {filter}");
1040            search_q = search_q.only_if(filter);
1041        }
1042
1043        let mut results = search_q
1044            .execute()
1045            .await
1046            .map_err(|e| StoreError::Query(format!("Failed to execute search: {e}")))?;
1047
1048        let mut search_results = Vec::new();
1049
1050        while let Some(batch) = results
1051            .try_next()
1052            .await
1053            .map_err(|e| StoreError::Query(format!("Failed to fetch results: {e}")))?
1054        {
1055            search_results.extend(batch_to_search_results(&batch)?);
1056        }
1057
1058        debug!("Found {} results", search_results.len());
1059        Ok(search_results)
1060    }
1061
1062    async fn hybrid_search(&self, query: SearchQuery) -> Result<Vec<SearchResult>, StoreError> {
1063        // If no text query provided, fall back to vector-only search
1064        let query_text = match &query.text {
1065            Some(text) if !text.is_empty() => text.clone(),
1066            _ => return self.search(query).await,
1067        };
1068
1069        debug!(
1070            "Performing hybrid search with text: '{}' limit {} metric {:?} filters {}",
1071            query_text,
1072            query.limit,
1073            query.metric,
1074            query.filters.len()
1075        );
1076
1077        let table = self.get_chunks_table().await?;
1078        let filter_sql = combine_predicates(
1079            self.chunk_filter_sql(&query.filters).await?,
1080            query.scope_prefix.as_deref().and_then(scope_prefix_sql),
1081        );
1082
1083        // Build hybrid query combining FTS and vector search
1084        let fts_query = FullTextSearchQuery::new(query_text);
1085
1086        let mut search_q = table
1087            .query()
1088            .full_text_search(fts_query)
1089            .nearest_to(query.embedding.clone())
1090            .map_err(|e| StoreError::Query(format!("Failed to create hybrid query: {e}")))?
1091            .distance_type(distance_type_from_metric(query.metric))
1092            .limit(query.limit);
1093
1094        if !Self::ann_index_covers_metric(query.metric) {
1095            search_q = search_q.bypass_vector_index();
1096        }
1097
1098        if let Some(ref filter) = filter_sql {
1099            debug!("Applying hybrid search filter: {filter}");
1100            search_q = search_q.only_if(filter);
1101        }
1102
1103        let mut results = search_q
1104            .execute_hybrid(QueryExecutionOptions::default())
1105            .await
1106            .map_err(|e| StoreError::Query(format!("Failed to execute hybrid search: {e}")))?;
1107
1108        let mut search_results = Vec::new();
1109
1110        while let Some(batch) = results
1111            .try_next()
1112            .await
1113            .map_err(|e| StoreError::Query(format!("Failed to fetch hybrid results: {e}")))?
1114        {
1115            search_results.extend(batch_to_search_results(&batch)?);
1116        }
1117
1118        debug!("Hybrid search found {} results", search_results.len());
1119        Ok(search_results)
1120    }
1121
1122    async fn delete_by_file_path(&self, path: &Path) -> Result<u64, StoreError> {
1123        let deleted = self.delete_by_file_path_inner(path).await?;
1124        self.bump_index_revision().await?;
1125        Ok(deleted)
1126    }
1127
1128    async fn update_file_path(&self, from: &Path, to: &Path) -> Result<u64, StoreError> {
1129        // LanceDB doesn't support UPDATE directly, so we read-delete-insert
1130        debug!("Updating file path from {:?} to {:?}", from, to);
1131
1132        // 1. Get all chunks for the old path
1133        let mut chunks = self.get_chunks_for_file(from).await?;
1134        if chunks.is_empty() {
1135            debug!("No chunks found for path {:?}", from);
1136            return Ok(0);
1137        }
1138
1139        let chunk_count = chunks.len() as u64;
1140
1141        // 2. Update the file_path and directory-scope fields in each chunk
1142        for chunk in &mut chunks {
1143            let root = DirectoryScope::infer_root(&chunk.file_path, &chunk.dir_path);
1144            let scope = DirectoryScope::from_paths(to, root.as_deref());
1145            chunk.file_path = to.to_path_buf();
1146            chunk.dir_path = scope.dir_path;
1147            chunk.dir_depth = scope.dir_depth;
1148            chunk.path_components = scope.path_components;
1149        }
1150
1151        // 3. Delete old chunks
1152        self.delete_by_file_path_inner(from).await?;
1153
1154        // 4. Insert updated chunks
1155        self.upsert_chunks_inner(&chunks).await?;
1156
1157        // 5. Also update file record if exists
1158        if let Ok(Some(mut file_record)) = self.get_file(from).await {
1159            file_record.path = to.to_path_buf();
1160            self.upsert_file(&file_record).await?;
1161        }
1162
1163        self.bump_index_revision().await?;
1164        info!("Updated {} chunks from {:?} to {:?}", chunk_count, from, to);
1165        Ok(chunk_count)
1166    }
1167
1168    async fn get_chunks_for_file(&self, path: &Path) -> Result<Vec<Chunk>, StoreError> {
1169        let path_str = path.to_string_lossy().to_string();
1170        debug!("Getting chunks for file: {}", path_str);
1171
1172        let table = self.get_chunks_table().await?;
1173
1174        let mut results = table
1175            .query()
1176            .only_if(format!("file_path = '{}'", path_str.replace('\'', "''")))
1177            .execute()
1178            .await
1179            .map_err(|e| StoreError::Query(format!("Failed to query chunks: {e}")))?;
1180
1181        let mut chunks = Vec::new();
1182
1183        while let Some(batch) = results
1184            .try_next()
1185            .await
1186            .map_err(|e| StoreError::Query(format!("Failed to fetch chunks: {e}")))?
1187        {
1188            chunks.extend(batch_to_chunks(&batch)?);
1189        }
1190
1191        Ok(chunks)
1192    }
1193
1194    async fn get_file(&self, path: &Path) -> Result<Option<FileRecord>, StoreError> {
1195        let path_str = path.to_string_lossy().to_string();
1196        debug!("Getting file record: {}", path_str);
1197
1198        let table = self.get_files_table().await?;
1199
1200        let mut results = table
1201            .query()
1202            .only_if(format!("path = '{}'", path_str.replace('\'', "''")))
1203            .limit(1)
1204            .execute()
1205            .await
1206            .map_err(|e| StoreError::Query(format!("Failed to query file: {e}")))?;
1207
1208        if let Some(batch) = results
1209            .try_next()
1210            .await
1211            .map_err(|e| StoreError::Query(format!("Failed to fetch file: {e}")))?
1212        {
1213            let records = batch_to_file_records(&batch)?;
1214            return Ok(records.into_iter().next());
1215        }
1216
1217        Ok(None)
1218    }
1219
1220    async fn upsert_file(&self, record: &FileRecord) -> Result<(), StoreError> {
1221        debug!("Upserting file record: {:?}", record.path);
1222
1223        let path_str = record.path.to_string_lossy().to_string();
1224
1225        // Delete existing file record only (not chunks!)
1226        let files_table = self.get_files_table().await?;
1227        let _ = files_table
1228            .delete(&format!("path = '{}'", path_str.replace('\'', "''")))
1229            .await;
1230
1231        // Insert new record
1232        let batch = self.file_to_batch(record)?;
1233        let schema = batch.schema();
1234
1235        let batches = RecordBatchIterator::new(vec![Ok(batch)], schema);
1236
1237        files_table
1238            .add(Box::new(batches) as Box<dyn RecordBatchReader + Send>)
1239            .execute()
1240            .await
1241            .map_err(|e| StoreError::Insert(format!("Failed to insert file record: {e}")))?;
1242
1243        Ok(())
1244    }
1245
1246    async fn stats(&self) -> Result<StoreStats, StoreError> {
1247        let chunks_table = self.get_chunks_table().await?;
1248        let files_table = self.get_files_table().await?;
1249
1250        // Count chunks - use exact same pattern as get_chunks_for_file
1251        let mut chunk_count = 0u64;
1252        let mut results = chunks_table
1253            .query()
1254            .only_if("file_path LIKE '%'")
1255            .execute()
1256            .await
1257            .map_err(|e| StoreError::Query(format!("Failed to query chunks: {e}")))?;
1258
1259        while let Some(batch) = results
1260            .try_next()
1261            .await
1262            .map_err(|e| StoreError::Query(format!("Failed to count chunks: {e}")))?
1263        {
1264            chunk_count += batch.num_rows() as u64;
1265        }
1266
1267        // Count files - use filter
1268        let mut file_count = 0u64;
1269        let mut results = files_table
1270            .query()
1271            .only_if("size_bytes >= 0")
1272            .execute()
1273            .await
1274            .map_err(|e| StoreError::Query(format!("Failed to query files: {e}")))?;
1275
1276        while let Some(batch) = results
1277            .try_next()
1278            .await
1279            .map_err(|e| StoreError::Query(format!("Failed to count files: {e}")))?
1280        {
1281            file_count += batch.num_rows() as u64;
1282        }
1283
1284        // Calculate actual index size from disk
1285        let index_size_bytes = calculate_dir_size(&self.db_path);
1286
1287        Ok(StoreStats {
1288            total_chunks: chunk_count,
1289            total_files: file_count,
1290            index_size_bytes,
1291            last_updated: Some(Utc::now()),
1292            index_revision: self.current_index_revision().await,
1293        })
1294    }
1295
1296    async fn get_all_chunks(&self) -> Result<Vec<Chunk>, StoreError> {
1297        debug!("Getting all chunks");
1298
1299        let table = self.get_chunks_table().await?;
1300
1301        let mut results = table
1302            .query()
1303            .only_if("file_path LIKE '%'")
1304            .execute()
1305            .await
1306            .map_err(|e| StoreError::Query(format!("Failed to query all chunks: {e}")))?;
1307
1308        let mut chunks = Vec::new();
1309
1310        while let Some(batch) = results
1311            .try_next()
1312            .await
1313            .map_err(|e| StoreError::Query(format!("Failed to fetch chunks: {e}")))?
1314        {
1315            chunks.extend(batch_to_chunks(&batch)?);
1316        }
1317
1318        debug!("Retrieved {} chunks", chunks.len());
1319        Ok(chunks)
1320    }
1321
1322    async fn get_all_files(&self) -> Result<Vec<FileRecord>, StoreError> {
1323        debug!("Getting all file records");
1324
1325        let table = self.get_files_table().await?;
1326
1327        let mut results = table
1328            .query()
1329            .only_if("size_bytes >= 0")
1330            .execute()
1331            .await
1332            .map_err(|e| StoreError::Query(format!("Failed to query all files: {e}")))?;
1333
1334        let mut records = Vec::new();
1335
1336        while let Some(batch) = results
1337            .try_next()
1338            .await
1339            .map_err(|e| StoreError::Query(format!("Failed to fetch files: {e}")))?
1340        {
1341            records.extend(batch_to_file_records(&batch)?);
1342        }
1343
1344        debug!("Retrieved {} file records", records.len());
1345        Ok(records)
1346    }
1347}
1348
1349// ============================================================================
1350// Helper functions
1351// ============================================================================
1352
1353/// Calculate the total size of a directory recursively.
1354fn calculate_dir_size(path: &Path) -> u64 {
1355    if !path.exists() {
1356        return 0;
1357    }
1358
1359    let mut total_size = 0u64;
1360
1361    if let Ok(entries) = std::fs::read_dir(path) {
1362        for entry in entries.flatten() {
1363            let entry_path = entry.path();
1364            if entry_path.is_file() {
1365                if let Ok(metadata) = entry.metadata() {
1366                    total_size += metadata.len();
1367                }
1368            } else if entry_path.is_dir() {
1369                total_size += calculate_dir_size(&entry_path);
1370            }
1371        }
1372    }
1373
1374    total_size
1375}
1376
1377/// Map [`DistanceMetric`] to the `LanceDB` distance type used at query time.
1378fn distance_type_from_metric(metric: DistanceMetric) -> DistanceType {
1379    match metric {
1380        DistanceMetric::Cosine => DistanceType::Cosine,
1381        DistanceMetric::L2 => DistanceType::L2,
1382        DistanceMetric::Dot => DistanceType::Dot,
1383    }
1384}
1385
1386/// Escape a string for use inside a single-quoted SQL literal.
1387fn escape_sql_literal(value: &str) -> String {
1388    value.replace('\'', "''")
1389}
1390
1391/// Escape `%` and `_` so they are treated as literals in `LIKE` patterns.
1392fn escape_like_literal(value: &str) -> String {
1393    value
1394        .replace('\\', "\\\\")
1395        .replace('%', "\\%")
1396        .replace('_', "\\_")
1397}
1398
1399/// Convert a glob (`*`, `**`, `?`) into an anchored regular expression.
1400///
1401/// `*` and `?` do not cross `/`. `**` matches across directories; `**/` also
1402/// matches zero intervening segments without collapsing the following name.
1403fn glob_to_regex(glob: &str) -> String {
1404    let mut regex = String::from("^");
1405    let chars: Vec<char> = glob.chars().collect();
1406    let mut i = 0;
1407
1408    while i < chars.len() {
1409        match chars[i] {
1410            '*' => {
1411                if i + 1 < chars.len() && chars[i + 1] == '*' {
1412                    i += 2;
1413                    if i < chars.len() && chars[i] == '/' {
1414                        i += 1;
1415                        regex.push_str("(?:.*/)?");
1416                    } else {
1417                        regex.push_str(".*");
1418                    }
1419                } else {
1420                    regex.push_str("[^/]*");
1421                    i += 1;
1422                }
1423            }
1424            '?' => {
1425                regex.push_str("[^/]");
1426                i += 1;
1427            }
1428            c => {
1429                regex.push_str(&regex_escape_char(c));
1430                i += 1;
1431            }
1432        }
1433    }
1434
1435    regex.push('$');
1436    regex
1437}
1438
1439fn regex_escape_char(c: char) -> String {
1440    if matches!(
1441        c,
1442        '.' | '+' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$' | '\\'
1443    ) {
1444        format!("\\{c}")
1445    } else {
1446        c.to_string()
1447    }
1448}
1449
1450/// Convert one [`SearchFilter`] into a chunks-table SQL predicate.
1451///
1452/// Date filters are omitted here; they are resolved against `files.modified_at`.
1453fn filter_to_sql(filter: &SearchFilter) -> Option<String> {
1454    Some(match filter {
1455        SearchFilter::PathPrefix(prefix) => {
1456            let pattern = escape_sql_literal(&format!("{}%", escape_like_literal(prefix)));
1457            format!("file_path LIKE '{pattern}' ESCAPE '\\'")
1458        }
1459        SearchFilter::PathGlob(glob) => {
1460            let pattern = escape_sql_literal(&glob_to_regex(glob));
1461            format!("regexp_like(file_path, '{pattern}')")
1462        }
1463        SearchFilter::MimeType(value) => type_or_mime_sql(value),
1464        SearchFilter::Language(lang) => {
1465            let escaped = escape_sql_literal(&lang.to_lowercase());
1466            format!("(LOWER(language) = '{escaped}' OR LOWER(content_type) = 'code:{escaped}')")
1467        }
1468        SearchFilter::ModifiedAfter(_) | SearchFilter::ModifiedBefore(_) => return None,
1469        SearchFilter::MinDepth(depth) => format!("depth >= {depth}"),
1470        SearchFilter::MaxDepth(depth) => format!("depth <= {depth}"),
1471    })
1472}
1473
1474/// Files-table predicates for source modification time (inclusive).
1475fn file_date_filters_to_sql(filters: &[SearchFilter]) -> Option<String> {
1476    let clauses: Vec<String> = filters
1477        .iter()
1478        .filter_map(|filter| match filter {
1479            SearchFilter::ModifiedAfter(ts) => {
1480                let escaped = escape_sql_literal(&ts.to_rfc3339());
1481                Some(format!("modified_at >= '{escaped}'"))
1482            }
1483            SearchFilter::ModifiedBefore(ts) => {
1484                let escaped = escape_sql_literal(&ts.to_rfc3339());
1485                Some(format!("modified_at <= '{escaped}'"))
1486            }
1487            _ => None,
1488        })
1489        .collect();
1490
1491    if clauses.is_empty() {
1492        None
1493    } else {
1494        Some(clauses.join(" AND "))
1495    }
1496}
1497
1498fn combine_predicates(left: Option<String>, right: Option<String>) -> Option<String> {
1499    match (left, right) {
1500        (Some(a), Some(b)) => Some(format!("{a} AND {b}")),
1501        (Some(a), None) | (None, Some(a)) => Some(a),
1502        (None, None) => None,
1503    }
1504}
1505
1506/// `type:` / `mime:` values may name a content-type alias or a MIME type.
1507fn type_or_mime_sql(value: &str) -> String {
1508    let lowered = value.to_lowercase();
1509    let escaped = escape_sql_literal(&lowered);
1510
1511    if lowered.contains('/') {
1512        return format!("LOWER(file_mime_type) = '{escaped}'");
1513    }
1514
1515    match lowered.as_str() {
1516        "code" => "(LOWER(content_type) LIKE 'code:%' OR LOWER(content_type) = 'code')".to_string(),
1517        "text" => "LOWER(content_type) = 'text'".to_string(),
1518        "markdown" | "md" => "LOWER(content_type) = 'markdown'".to_string(),
1519        "pdf" => "(LOWER(content_type) LIKE 'pdf:%' OR LOWER(content_type) = 'pdf')".to_string(),
1520        "image" | "image_caption" => "LOWER(content_type) = 'image_caption'".to_string(),
1521        _ => format!(
1522            "(LOWER(content_type) = '{escaped}' OR LOWER(content_type) LIKE '{escaped}:%' OR LOWER(file_mime_type) = '{escaped}')"
1523        ),
1524    }
1525}
1526
1527/// Pre-filter for directory-scoped search (exact dir, subdirectory, or suffix).
1528///
1529/// Used with IVF-PQ ANN via `only_if`; this is not a replacement for ANN.
1530/// Suffix `LIKE` clauses cover schema-v1 rows backfilled from absolute `file_path`.
1531fn scope_prefix_sql(scope: &str) -> Option<String> {
1532    let scope = DirectoryScope::normalize_prefix(scope);
1533    if scope.is_empty() || scope == "." {
1534        return None;
1535    }
1536    let exact = escape_sql_literal(&scope);
1537    let prefix = escape_sql_literal(&format!("{}/%", escape_like_literal(&scope)));
1538    let suffix = escape_sql_literal(&format!("%/{}", escape_like_literal(&scope)));
1539    let mid = escape_sql_literal(&format!("%/{}/%", escape_like_literal(&scope)));
1540    Some(format!(
1541        "dir_path = '{exact}' OR dir_path LIKE '{prefix}' ESCAPE '\\' \
1542         OR dir_path LIKE '{suffix}' ESCAPE '\\' OR dir_path LIKE '{mid}' ESCAPE '\\'"
1543    ))
1544}
1545
1546/// Combine [`SearchQuery`] filters into a single SQL predicate, if any.
1547fn filters_to_sql(filters: &[SearchFilter]) -> Option<String> {
1548    if filters.is_empty() {
1549        return None;
1550    }
1551
1552    let clauses: Vec<String> = filters.iter().filter_map(filter_to_sql).collect();
1553    if clauses.is_empty() {
1554        None
1555    } else {
1556        Some(clauses.join(" AND "))
1557    }
1558}
1559
1560fn content_type_to_string(ct: &ContentType) -> String {
1561    match ct {
1562        ContentType::Text => "text".to_string(),
1563        ContentType::Code { language, .. } => format!("code:{language}"),
1564        ContentType::ImageCaption => "image_caption".to_string(),
1565        ContentType::PdfPage { page_num } => format!("pdf:{page_num}"),
1566        ContentType::Markdown => "markdown".to_string(),
1567    }
1568}
1569
1570fn string_to_content_type(s: &str) -> ContentType {
1571    if s == "text" {
1572        ContentType::Text
1573    } else if s == "markdown" {
1574        ContentType::Markdown
1575    } else if s == "image_caption" {
1576        ContentType::ImageCaption
1577    } else if let Some(lang) = s.strip_prefix("code:") {
1578        ContentType::Code {
1579            language: lang.to_string(),
1580            symbol: None,
1581        }
1582    } else if let Some(page) = s.strip_prefix("pdf:") {
1583        ContentType::PdfPage {
1584            page_num: page.parse().unwrap_or(1),
1585        }
1586    } else {
1587        ContentType::Text
1588    }
1589}
1590
1591fn status_to_string(status: &FileStatus) -> String {
1592    match status {
1593        FileStatus::Pending => "pending".to_string(),
1594        FileStatus::Indexing => "indexing".to_string(),
1595        FileStatus::Indexed => "indexed".to_string(),
1596        FileStatus::Error => "error".to_string(),
1597        FileStatus::Deleted => "deleted".to_string(),
1598    }
1599}
1600
1601fn string_to_status(s: &str) -> FileStatus {
1602    match s {
1603        "pending" => FileStatus::Pending,
1604        "indexing" => FileStatus::Indexing,
1605        "indexed" => FileStatus::Indexed,
1606        "error" => FileStatus::Error,
1607        "deleted" => FileStatus::Deleted,
1608        _ => FileStatus::Pending,
1609    }
1610}
1611
1612fn build_vector_array(
1613    embeddings: &[Option<Vec<Option<f32>>>],
1614    dim: usize,
1615) -> Result<ArrayRef, StoreError> {
1616    use arrow_array::builder::{FixedSizeListBuilder, Float32Builder};
1617
1618    let mut builder = FixedSizeListBuilder::new(Float32Builder::new(), dim as i32);
1619
1620    for emb in embeddings {
1621        if let Some(values) = emb {
1622            let values_builder = builder.values();
1623            for &v in values {
1624                values_builder.append_option(v);
1625            }
1626            builder.append(true);
1627        } else {
1628            // Append zeros for missing embeddings
1629            let values_builder = builder.values();
1630            for _ in 0..dim {
1631                values_builder.append_value(0.0);
1632            }
1633            builder.append(true);
1634        }
1635    }
1636
1637    Ok(Arc::new(builder.finish()))
1638}
1639
1640fn media_from_batch(batch: &RecordBatch, row: usize) -> Result<ragfs_core::MediaInfo, StoreError> {
1641    let modality = batch
1642        .column_by_name("modality")
1643        .and_then(|column| column.as_any().downcast_ref::<StringArray>())
1644        .filter(|array| !array.is_null(row))
1645        .map_or("text", |array| array.value(row))
1646        .to_string();
1647    let time = |name| {
1648        batch
1649            .column_by_name(name)
1650            .and_then(|column| column.as_any().downcast_ref::<UInt64Array>())
1651            .filter(|array| !array.is_null(row))
1652            .map(|array| array.value(row))
1653    };
1654    let media = ragfs_core::MediaInfo {
1655        modality,
1656        start_ms: time("start_ms"),
1657        end_ms: time("end_ms"),
1658    };
1659    media.validate().map_err(StoreError::Query)?;
1660    Ok(media)
1661}
1662
1663fn batch_to_search_results(batch: &RecordBatch) -> Result<Vec<SearchResult>, StoreError> {
1664    let mut results = Vec::new();
1665
1666    let chunk_ids = batch
1667        .column_by_name("chunk_id")
1668        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1669    let file_paths = batch
1670        .column_by_name("file_path")
1671        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1672    let contents = batch
1673        .column_by_name("content")
1674        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1675    let start_bytes = batch
1676        .column_by_name("start_byte")
1677        .and_then(|c| c.as_any().downcast_ref::<UInt64Array>());
1678    let end_bytes = batch
1679        .column_by_name("end_byte")
1680        .and_then(|c| c.as_any().downcast_ref::<UInt64Array>());
1681    let start_lines = batch
1682        .column_by_name("start_line")
1683        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>());
1684    let end_lines = batch
1685        .column_by_name("end_line")
1686        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>());
1687    let distances = batch
1688        .column_by_name("_distance")
1689        .and_then(|c| c.as_any().downcast_ref::<Float32Array>());
1690
1691    let (Some(chunk_ids), Some(file_paths), Some(contents), Some(start_bytes), Some(end_bytes)) =
1692        (chunk_ids, file_paths, contents, start_bytes, end_bytes)
1693    else {
1694        return Err(StoreError::Query("Missing required columns".to_string()));
1695    };
1696
1697    for i in 0..batch.num_rows() {
1698        let chunk_id = chunk_ids.value(i);
1699        let file_path = file_paths.value(i);
1700        let content = contents.value(i);
1701        let start = start_bytes.value(i);
1702        let end = end_bytes.value(i);
1703
1704        let line_range = match (start_lines, end_lines) {
1705            (Some(sl), Some(el)) if !sl.is_null(i) && !el.is_null(i) => {
1706                Some(sl.value(i)..el.value(i))
1707            }
1708            _ => None,
1709        };
1710
1711        let score = distances.map_or(0.0, |d| 1.0 - d.value(i));
1712
1713        results.push(SearchResult {
1714            media: media_from_batch(batch, i)?,
1715            chunk_id: Uuid::parse_str(chunk_id).unwrap_or_default(),
1716            file_path: PathBuf::from(file_path),
1717            content: content.to_string(),
1718            score,
1719            byte_range: start..end,
1720            line_range,
1721            metadata: HashMap::new(),
1722        });
1723    }
1724
1725    Ok(results)
1726}
1727
1728fn batch_to_chunks(batch: &RecordBatch) -> Result<Vec<Chunk>, StoreError> {
1729    let mut chunks = Vec::new();
1730
1731    // Similar to batch_to_search_results but returns full Chunk structs
1732    // Simplified for now - full implementation would parse all fields
1733
1734    let chunk_ids = batch
1735        .column_by_name("chunk_id")
1736        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1737    let file_ids = batch
1738        .column_by_name("file_id")
1739        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1740    let file_paths = batch
1741        .column_by_name("file_path")
1742        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1743    let contents = batch
1744        .column_by_name("content")
1745        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1746    let content_types = batch
1747        .column_by_name("content_type")
1748        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1749    let chunk_indices = batch
1750        .column_by_name("chunk_index")
1751        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>());
1752    let start_bytes = batch
1753        .column_by_name("start_byte")
1754        .and_then(|c| c.as_any().downcast_ref::<UInt64Array>());
1755    let end_bytes = batch
1756        .column_by_name("end_byte")
1757        .and_then(|c| c.as_any().downcast_ref::<UInt64Array>());
1758    let depths = batch
1759        .column_by_name("depth")
1760        .and_then(|c| c.as_any().downcast_ref::<UInt8Array>());
1761    let mime_types = batch
1762        .column_by_name("mime_type")
1763        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1764    let start_lines = batch
1765        .column_by_name("start_line")
1766        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>());
1767    let end_lines = batch
1768        .column_by_name("end_line")
1769        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>());
1770    let embeddings = batch
1771        .column_by_name("vector")
1772        .and_then(|c| c.as_any().downcast_ref::<FixedSizeListArray>());
1773    let dir_paths = batch
1774        .column_by_name("dir_path")
1775        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1776    let dir_depths = batch
1777        .column_by_name("dir_depth")
1778        .and_then(|c| c.as_any().downcast_ref::<UInt16Array>());
1779    let path_components_arr = batch
1780        .column_by_name("path_components")
1781        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1782
1783    let (
1784        Some(chunk_ids),
1785        Some(file_ids),
1786        Some(file_paths),
1787        Some(contents),
1788        Some(content_types),
1789        Some(chunk_indices),
1790        Some(start_bytes),
1791        Some(end_bytes),
1792        Some(depths),
1793    ) = (
1794        chunk_ids,
1795        file_ids,
1796        file_paths,
1797        contents,
1798        content_types,
1799        chunk_indices,
1800        start_bytes,
1801        end_bytes,
1802        depths,
1803    )
1804    else {
1805        return Err(StoreError::Query(
1806            "Missing required columns in chunks".to_string(),
1807        ));
1808    };
1809
1810    for i in 0..batch.num_rows() {
1811        let mime_type = mime_types.and_then(|m| {
1812            if m.is_null(i) {
1813                None
1814            } else {
1815                Some(m.value(i).to_string())
1816            }
1817        });
1818
1819        // Parse line range from start_line and end_line columns
1820        let line_range = match (start_lines, end_lines) {
1821            (Some(starts), Some(ends)) if !starts.is_null(i) && !ends.is_null(i) => {
1822                Some(starts.value(i)..ends.value(i))
1823            }
1824            _ => None,
1825        };
1826
1827        // Parse embedding vector
1828        let embedding = embeddings.and_then(|emb_array| {
1829            if emb_array.is_null(i) {
1830                None
1831            } else {
1832                let values = emb_array.value(i);
1833                values
1834                    .as_any()
1835                    .downcast_ref::<Float32Array>()
1836                    .map(|arr| arr.values().to_vec())
1837            }
1838        });
1839
1840        chunks.push(Chunk {
1841            id: Uuid::parse_str(chunk_ids.value(i)).unwrap_or_default(),
1842            file_id: Uuid::parse_str(file_ids.value(i)).unwrap_or_default(),
1843            file_path: PathBuf::from(file_paths.value(i)),
1844            content: contents.value(i).to_string(),
1845            content_type: string_to_content_type(content_types.value(i)),
1846            mime_type,
1847            chunk_index: chunk_indices.value(i),
1848            byte_range: start_bytes.value(i)..end_bytes.value(i),
1849            line_range,
1850            parent_chunk_id: None,
1851            depth: depths.value(i),
1852            embedding,
1853            dir_path: dir_paths.map_or_else(
1854                || DirectoryScope::from_file_path(&PathBuf::from(file_paths.value(i))).dir_path,
1855                |arr| {
1856                    if arr.is_null(i) {
1857                        String::new()
1858                    } else {
1859                        arr.value(i).to_string()
1860                    }
1861                },
1862            ),
1863            dir_depth: dir_depths.map_or(0, |arr| if arr.is_null(i) { 0 } else { arr.value(i) }),
1864            path_components: path_components_arr.map_or_else(String::new, |arr| {
1865                if arr.is_null(i) {
1866                    String::new()
1867                } else {
1868                    arr.value(i).to_string()
1869                }
1870            }),
1871            metadata: ChunkMetadata {
1872                media: media_from_batch(batch, i)?,
1873                ..Default::default()
1874            },
1875        });
1876    }
1877
1878    Ok(chunks)
1879}
1880
1881fn batch_to_file_records(batch: &RecordBatch) -> Result<Vec<FileRecord>, StoreError> {
1882    let mut records = Vec::new();
1883
1884    let file_ids = batch
1885        .column_by_name("file_id")
1886        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1887    let paths = batch
1888        .column_by_name("path")
1889        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1890    let sizes = batch
1891        .column_by_name("size_bytes")
1892        .and_then(|c| c.as_any().downcast_ref::<UInt64Array>());
1893    let mime_types = batch
1894        .column_by_name("mime_type")
1895        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1896    let hashes = batch
1897        .column_by_name("content_hash")
1898        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1899    let modified_ats = batch
1900        .column_by_name("modified_at")
1901        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1902    let chunk_counts = batch
1903        .column_by_name("chunk_count")
1904        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>());
1905    let statuses = batch
1906        .column_by_name("status")
1907        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1908    let indexed_ats = batch
1909        .column_by_name("indexed_at")
1910        .and_then(|c| c.as_any().downcast_ref::<StringArray>());
1911
1912    let (
1913        Some(file_ids),
1914        Some(paths),
1915        Some(sizes),
1916        Some(mime_types),
1917        Some(hashes),
1918        Some(modified_ats),
1919        Some(chunk_counts),
1920        Some(statuses),
1921    ) = (
1922        file_ids,
1923        paths,
1924        sizes,
1925        mime_types,
1926        hashes,
1927        modified_ats,
1928        chunk_counts,
1929        statuses,
1930    )
1931    else {
1932        return Err(StoreError::Query(
1933            "Missing required columns in files".to_string(),
1934        ));
1935    };
1936
1937    for i in 0..batch.num_rows() {
1938        let modified_at = chrono::DateTime::parse_from_rfc3339(modified_ats.value(i))
1939            .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));
1940
1941        // Parse indexed_at timestamp
1942        let indexed_at = indexed_ats.and_then(|arr| {
1943            if arr.is_null(i) {
1944                None
1945            } else {
1946                chrono::DateTime::parse_from_rfc3339(arr.value(i))
1947                    .map(|dt| dt.with_timezone(&Utc))
1948                    .ok()
1949            }
1950        });
1951
1952        records.push(FileRecord {
1953            id: Uuid::parse_str(file_ids.value(i)).unwrap_or_default(),
1954            path: PathBuf::from(paths.value(i)),
1955            size_bytes: sizes.value(i),
1956            mime_type: mime_types.value(i).to_string(),
1957            content_hash: hashes.value(i).to_string(),
1958            modified_at,
1959            indexed_at,
1960            chunk_count: chunk_counts.value(i),
1961            status: string_to_status(statuses.value(i)),
1962            error_message: None,
1963        });
1964    }
1965
1966    Ok(records)
1967}
1968
1969#[cfg(test)]
1970mod tests {
1971    use super::*;
1972    use crate::schema::{CHUNKS_SCHEMA_VERSION, SCHEMA_SIDECAR_FILENAME, SchemaSidecar};
1973    use ragfs_core::{DistanceMetric, SearchFilter};
1974    use std::collections::HashMap;
1975    use tempfile::tempdir;
1976
1977    const TEST_DIM: usize = 384;
1978
1979    fn create_test_chunk(
1980        file_path: &Path,
1981        content: &str,
1982        embedding: Vec<f32>,
1983        chunk_index: u32,
1984    ) -> Chunk {
1985        Chunk {
1986            id: Uuid::new_v4(),
1987            file_id: Uuid::new_v4(),
1988            file_path: file_path.to_path_buf(),
1989            content: content.to_string(),
1990            content_type: ContentType::Text,
1991            mime_type: Some("text/plain".to_string()),
1992            chunk_index,
1993            byte_range: 0..content.len() as u64,
1994            line_range: Some(0..1),
1995            parent_chunk_id: None,
1996            depth: 0,
1997            embedding: Some(embedding),
1998            dir_path: DirectoryScope::from_file_path(file_path).dir_path,
1999            dir_depth: DirectoryScope::from_file_path(file_path).dir_depth,
2000            path_components: DirectoryScope::from_file_path(file_path).path_components,
2001            metadata: ChunkMetadata {
2002                media: Default::default(),
2003                indexed_at: Some(Utc::now()),
2004                embedding_model: Some("test-model".to_string()),
2005                token_count: None,
2006                extra: HashMap::new(),
2007            },
2008        }
2009    }
2010
2011    fn create_random_embedding(dim: usize) -> Vec<f32> {
2012        (0..dim).map(|i| (i as f32 * 0.001).sin()).collect()
2013    }
2014
2015    fn create_test_file_record(path: &Path) -> FileRecord {
2016        FileRecord {
2017            id: Uuid::new_v4(),
2018            path: path.to_path_buf(),
2019            size_bytes: 1024,
2020            mime_type: "text/plain".to_string(),
2021            content_hash: "abc123".to_string(),
2022            modified_at: Utc::now(),
2023            indexed_at: Some(Utc::now()),
2024            chunk_count: 1,
2025            status: FileStatus::Indexed,
2026            error_message: None,
2027        }
2028    }
2029
2030    #[tokio::test]
2031    async fn test_init_creates_tables() {
2032        let temp = tempdir().unwrap();
2033        let db_path = temp.path().join("test.lance");
2034        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2035
2036        let result = store.init().await;
2037        assert!(result.is_ok(), "Init failed: {:?}", result.err());
2038
2039        // Verify tables exist
2040        let conn = store.get_connection().await.unwrap();
2041        let tables = conn.table_names().execute().await.unwrap();
2042        assert!(tables.contains(&"chunks".to_string()));
2043        assert!(tables.contains(&"files".to_string()));
2044    }
2045
2046    #[tokio::test]
2047    async fn test_init_idempotent() {
2048        let temp = tempdir().unwrap();
2049        let db_path = temp.path().join("test.lance");
2050        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2051
2052        // Init twice should succeed
2053        store.init().await.unwrap();
2054        let result = store.init().await;
2055        assert!(result.is_ok());
2056    }
2057
2058    #[tokio::test]
2059    async fn test_init_rejects_embedding_dim_mismatch() {
2060        let temp = tempdir().unwrap();
2061        let db_path = temp.path().join("test.lance");
2062        LanceStore::new(db_path.clone(), TEST_DIM)
2063            .init()
2064            .await
2065            .unwrap();
2066
2067        let err = LanceStore::new(db_path, 768).init().await.unwrap_err();
2068        let msg = err.to_string();
2069        assert!(
2070            matches!(err, StoreError::Schema(_)),
2071            "expected Schema, got {err:?}"
2072        );
2073        assert!(
2074            msg.contains("384") && msg.contains("768"),
2075            "mismatch message should name both dimensions: {msg}"
2076        );
2077    }
2078
2079    #[tokio::test]
2080    async fn test_upsert_and_get_chunks() {
2081        let temp = tempdir().unwrap();
2082        let db_path = temp.path().join("test.lance");
2083        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2084        store.init().await.unwrap();
2085
2086        let file_path = PathBuf::from("/test/file.txt");
2087        let embedding = create_random_embedding(TEST_DIM);
2088        let chunk = create_test_chunk(&file_path, "Hello world", embedding, 0);
2089
2090        // Upsert
2091        let result = store.upsert_chunks(&[chunk]).await;
2092        assert!(result.is_ok(), "Upsert failed: {:?}", result.err());
2093
2094        // Get chunks back
2095        let chunks = store.get_chunks_for_file(&file_path).await.unwrap();
2096        assert_eq!(chunks.len(), 1);
2097        assert_eq!(chunks[0].content, "Hello world");
2098    }
2099
2100    #[tokio::test]
2101    async fn test_upsert_multiple_chunks() {
2102        let temp = tempdir().unwrap();
2103        let db_path = temp.path().join("test.lance");
2104        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2105        store.init().await.unwrap();
2106
2107        let file_path = PathBuf::from("/test/multi.txt");
2108        let chunks: Vec<Chunk> = (0..5)
2109            .map(|i| {
2110                create_test_chunk(
2111                    &file_path,
2112                    &format!("Chunk content {i}"),
2113                    create_random_embedding(TEST_DIM),
2114                    i,
2115                )
2116            })
2117            .collect();
2118
2119        store.upsert_chunks(&chunks).await.unwrap();
2120
2121        let retrieved = store.get_chunks_for_file(&file_path).await.unwrap();
2122        assert_eq!(retrieved.len(), 5);
2123    }
2124
2125    #[tokio::test]
2126    async fn test_upsert_empty_chunks() {
2127        let temp = tempdir().unwrap();
2128        let db_path = temp.path().join("test.lance");
2129        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2130        store.init().await.unwrap();
2131
2132        // Empty vec should succeed
2133        let result = store.upsert_chunks(&[]).await;
2134        assert!(result.is_ok());
2135    }
2136
2137    #[tokio::test]
2138    async fn test_search_returns_results() {
2139        let temp = tempdir().unwrap();
2140        let db_path = temp.path().join("test.lance");
2141        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2142        store.init().await.unwrap();
2143
2144        // Insert some chunks
2145        let file_path = PathBuf::from("/test/search.txt");
2146        let embedding = create_random_embedding(TEST_DIM);
2147        let chunk = create_test_chunk(&file_path, "Authentication logic", embedding.clone(), 0);
2148        store.upsert_chunks(&[chunk]).await.unwrap();
2149
2150        // Search with same embedding should find it
2151        let query = SearchQuery {
2152            text: Some("auth".to_string()),
2153            embedding: embedding.clone(),
2154            limit: 10,
2155            filters: vec![],
2156            metric: DistanceMetric::Cosine,
2157            scope_prefix: None,
2158        };
2159
2160        let results = store.search(query).await.unwrap();
2161        assert!(!results.is_empty());
2162        assert_eq!(results[0].content, "Authentication logic");
2163    }
2164
2165    #[tokio::test]
2166    async fn test_search_respects_limit() {
2167        let temp = tempdir().unwrap();
2168        let db_path = temp.path().join("test.lance");
2169        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2170        store.init().await.unwrap();
2171
2172        // Insert 10 chunks
2173        let file_path = PathBuf::from("/test/limit.txt");
2174        let chunks: Vec<Chunk> = (0..10)
2175            .map(|i| {
2176                create_test_chunk(
2177                    &file_path,
2178                    &format!("Content {i}"),
2179                    create_random_embedding(TEST_DIM),
2180                    i,
2181                )
2182            })
2183            .collect();
2184        store.upsert_chunks(&chunks).await.unwrap();
2185
2186        // Search with limit 3
2187        let query = SearchQuery {
2188            text: Some("test".to_string()),
2189            embedding: create_random_embedding(TEST_DIM),
2190            limit: 3,
2191            filters: vec![],
2192            metric: DistanceMetric::Cosine,
2193            scope_prefix: None,
2194        };
2195
2196        let results = store.search(query).await.unwrap();
2197        assert!(results.len() <= 3);
2198    }
2199
2200    #[tokio::test]
2201    async fn test_delete_by_file_path() {
2202        let temp = tempdir().unwrap();
2203        let db_path = temp.path().join("test.lance");
2204        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2205        store.init().await.unwrap();
2206
2207        let file_path = PathBuf::from("/test/delete.txt");
2208        let chunk = create_test_chunk(
2209            &file_path,
2210            "To be deleted",
2211            create_random_embedding(TEST_DIM),
2212            0,
2213        );
2214        store.upsert_chunks(&[chunk]).await.unwrap();
2215
2216        // Verify it exists
2217        let chunks = store.get_chunks_for_file(&file_path).await.unwrap();
2218        assert_eq!(chunks.len(), 1);
2219
2220        // Delete
2221        store.delete_by_file_path(&file_path).await.unwrap();
2222
2223        // Verify it's gone
2224        let chunks = store.get_chunks_for_file(&file_path).await.unwrap();
2225        assert_eq!(chunks.len(), 0);
2226    }
2227
2228    #[tokio::test]
2229    async fn test_upsert_and_get_file_record() {
2230        let temp = tempdir().unwrap();
2231        let db_path = temp.path().join("test.lance");
2232        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2233        store.init().await.unwrap();
2234
2235        let file_path = PathBuf::from("/test/record.txt");
2236        let record = create_test_file_record(&file_path);
2237
2238        // Upsert
2239        store.upsert_file(&record).await.unwrap();
2240
2241        // Get
2242        let retrieved = store.get_file(&file_path).await.unwrap();
2243        assert!(retrieved.is_some());
2244        let retrieved = retrieved.unwrap();
2245        assert_eq!(retrieved.path, file_path);
2246        assert_eq!(retrieved.mime_type, "text/plain");
2247    }
2248
2249    #[tokio::test]
2250    async fn test_get_nonexistent_file() {
2251        let temp = tempdir().unwrap();
2252        let db_path = temp.path().join("test.lance");
2253        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2254        store.init().await.unwrap();
2255
2256        let result = store
2257            .get_file(&PathBuf::from("/nonexistent"))
2258            .await
2259            .unwrap();
2260        assert!(result.is_none());
2261    }
2262
2263    #[tokio::test]
2264    async fn test_stats() {
2265        let temp = tempdir().unwrap();
2266        let db_path = temp.path().join("test.lance");
2267        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2268        store.init().await.unwrap();
2269
2270        // Initially empty
2271        let stats = store.stats().await.unwrap();
2272        assert_eq!(stats.total_chunks, 0);
2273        assert_eq!(stats.total_files, 0);
2274
2275        // Add chunk
2276        let file_path = PathBuf::from("/test/stats.txt");
2277        let chunk = create_test_chunk(
2278            &file_path,
2279            "Stats test",
2280            create_random_embedding(TEST_DIM),
2281            0,
2282        );
2283        store.upsert_chunks(&[chunk]).await.unwrap();
2284
2285        // Add file record (should NOT delete chunks)
2286        let record = create_test_file_record(&file_path);
2287        store.upsert_file(&record).await.unwrap();
2288
2289        // Verify chunks still exist after upsert_file
2290        let chunks = store.get_chunks_for_file(&file_path).await.unwrap();
2291        assert_eq!(
2292            chunks.len(),
2293            1,
2294            "Chunks should still exist after upsert_file"
2295        );
2296
2297        // Verify file exists
2298        let file = store.get_file(&file_path).await.unwrap();
2299        assert!(file.is_some(), "File should be retrievable");
2300
2301        // Check stats
2302        let stats = store.stats().await.unwrap();
2303        assert_eq!(stats.total_chunks, 1);
2304        assert_eq!(stats.total_files, 1);
2305        assert!(
2306            stats.index_size_bytes > 0,
2307            "index_size_bytes should be > 0, got {}",
2308            stats.index_size_bytes
2309        );
2310    }
2311
2312    #[tokio::test]
2313    async fn test_content_type_conversion() {
2314        assert_eq!(content_type_to_string(&ContentType::Text), "text");
2315        assert_eq!(content_type_to_string(&ContentType::Markdown), "markdown");
2316        assert_eq!(
2317            content_type_to_string(&ContentType::Code {
2318                language: "rust".to_string(),
2319                symbol: None
2320            }),
2321            "code:rust"
2322        );
2323        assert_eq!(
2324            content_type_to_string(&ContentType::PdfPage { page_num: 5 }),
2325            "pdf:5"
2326        );
2327
2328        assert!(matches!(string_to_content_type("text"), ContentType::Text));
2329        assert!(matches!(
2330            string_to_content_type("markdown"),
2331            ContentType::Markdown
2332        ));
2333        assert!(matches!(
2334            string_to_content_type("code:python"),
2335            ContentType::Code { language, .. } if language == "python"
2336        ));
2337    }
2338
2339    #[tokio::test]
2340    async fn test_file_status_conversion() {
2341        assert_eq!(status_to_string(&FileStatus::Pending), "pending");
2342        assert_eq!(status_to_string(&FileStatus::Indexed), "indexed");
2343        assert_eq!(status_to_string(&FileStatus::Error), "error");
2344
2345        assert!(matches!(string_to_status("pending"), FileStatus::Pending));
2346        assert!(matches!(string_to_status("indexed"), FileStatus::Indexed));
2347        assert!(matches!(string_to_status("error"), FileStatus::Error));
2348        assert!(matches!(string_to_status("unknown"), FileStatus::Pending));
2349    }
2350
2351    #[tokio::test]
2352    async fn test_chunks_with_code_content_type() {
2353        let temp = tempdir().unwrap();
2354        let db_path = temp.path().join("test.lance");
2355        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2356        store.init().await.unwrap();
2357
2358        let file_path = PathBuf::from("/test/code.rs");
2359        let chunk = Chunk {
2360            id: Uuid::new_v4(),
2361            file_id: Uuid::new_v4(),
2362            file_path: file_path.clone(),
2363            content: "fn main() {}".to_string(),
2364            content_type: ContentType::Code {
2365                language: "rust".to_string(),
2366                symbol: None,
2367            },
2368            mime_type: Some("text/x-rust".to_string()),
2369            chunk_index: 0,
2370            byte_range: 0..12,
2371            line_range: Some(0..1),
2372            parent_chunk_id: None,
2373            depth: 0,
2374            embedding: Some(create_random_embedding(TEST_DIM)),
2375            dir_path: DirectoryScope::from_file_path(&file_path).dir_path,
2376            dir_depth: DirectoryScope::from_file_path(&file_path).dir_depth,
2377            path_components: DirectoryScope::from_file_path(&file_path).path_components,
2378            metadata: ChunkMetadata::default(),
2379        };
2380
2381        store.upsert_chunks(&[chunk]).await.unwrap();
2382
2383        let chunks = store.get_chunks_for_file(&file_path).await.unwrap();
2384        assert_eq!(chunks.len(), 1);
2385        assert!(matches!(
2386            &chunks[0].content_type,
2387            ContentType::Code { language, .. } if language == "rust"
2388        ));
2389    }
2390
2391    #[tokio::test]
2392    async fn test_get_all_files_empty() {
2393        let temp = tempdir().unwrap();
2394        let db_path = temp.path().join("test.lance");
2395        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2396        store.init().await.unwrap();
2397
2398        let files = store.get_all_files().await.unwrap();
2399        assert!(files.is_empty());
2400    }
2401
2402    #[tokio::test]
2403    async fn test_delete_nonexistent_file() {
2404        let temp = tempdir().unwrap();
2405        let db_path = temp.path().join("test.lance");
2406        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2407        store.init().await.unwrap();
2408
2409        let path = PathBuf::from("/nonexistent/file.txt");
2410        // Deleting a nonexistent file should not error
2411        let result = store.delete_by_file_path(&path).await;
2412        assert!(result.is_ok());
2413    }
2414
2415    #[test]
2416    fn test_ann_threshold() {
2417        assert!(!LanceStore::should_build_ann_index(0));
2418        assert!(!LanceStore::should_build_ann_index(255));
2419        assert!(LanceStore::should_build_ann_index(256));
2420        assert!(LanceStore::should_build_ann_index(10_000));
2421    }
2422
2423    #[test]
2424    fn test_should_refresh_ann_index_after_post_threshold_appends() {
2425        // Repeated-batch ingest: first batch crosses 256, later batches are unindexed.
2426        assert!(LanceStore::should_build_ann_index(300));
2427        assert!(!LanceStore::should_refresh_ann_index(0));
2428        assert!(!LanceStore::should_refresh_ann_index(255));
2429        assert!(LanceStore::should_refresh_ann_index(256));
2430        assert!(LanceStore::should_refresh_ann_index(700));
2431        assert!(LanceStore::should_refresh_ann_index(9_700));
2432    }
2433
2434    #[test]
2435    fn test_ann_index_covers_cosine_only() {
2436        assert!(LanceStore::ann_index_covers_metric(DistanceMetric::Cosine));
2437        assert!(!LanceStore::ann_index_covers_metric(DistanceMetric::L2));
2438        assert!(!LanceStore::ann_index_covers_metric(DistanceMetric::Dot));
2439        assert!(LanceStore::ann_index_is_cosine(Some(DistanceType::Cosine)));
2440        assert!(!LanceStore::ann_index_is_cosine(Some(DistanceType::L2)));
2441        assert!(!LanceStore::ann_index_is_cosine(Some(DistanceType::Dot)));
2442        assert!(!LanceStore::ann_index_is_cosine(None));
2443    }
2444
2445    #[tokio::test]
2446    async fn test_small_table_skips_ann_and_still_searches() {
2447        let temp = tempdir().unwrap();
2448        let db_path = temp.path().join("test.lance");
2449        let store = LanceStore::new(db_path, TEST_DIM);
2450        store.init().await.unwrap();
2451
2452        let file_path = PathBuf::from("/test/small.txt");
2453        let chunk = create_test_chunk(
2454            &file_path,
2455            "hello ann",
2456            create_random_embedding(TEST_DIM),
2457            0,
2458        );
2459        store.upsert_chunks(&[chunk]).await.unwrap();
2460        store.ensure_vector_index().await.unwrap();
2461
2462        let results = store
2463            .search(SearchQuery {
2464                text: None,
2465                embedding: create_random_embedding(TEST_DIM),
2466                limit: 5,
2467                filters: vec![],
2468                metric: DistanceMetric::Cosine,
2469                scope_prefix: None,
2470            })
2471            .await
2472            .unwrap();
2473        assert!(!results.is_empty());
2474    }
2475
2476    #[tokio::test]
2477    async fn test_replaces_preexisting_l2_vector_index() {
2478        let temp = tempdir().unwrap();
2479        let db_path = temp.path().join("test.lance");
2480        let store = LanceStore::new(db_path, TEST_DIM);
2481        store.init().await.unwrap();
2482
2483        let file_path = PathBuf::from("/test/l2.txt");
2484        let chunks: Vec<Chunk> = (0..16)
2485            .map(|i| {
2486                create_test_chunk(
2487                    &file_path,
2488                    &format!("legacy l2 chunk {i}"),
2489                    create_random_embedding(TEST_DIM),
2490                    i,
2491                )
2492            })
2493            .collect();
2494        store.upsert_chunks(&chunks).await.unwrap();
2495
2496        let table = store.get_chunks_table().await.unwrap();
2497        let created = table
2498            .create_index(
2499                &["vector"],
2500                Index::IvfPq(
2501                    IvfPqIndexBuilder::default()
2502                        .distance_type(DistanceType::L2)
2503                        .num_partitions(1)
2504                        .sample_rate(4),
2505                ),
2506            )
2507            .execute()
2508            .await;
2509        if created.is_err() {
2510            // Fixture only: Lance may refuse a tiny L2 index. Cosine search must still work.
2511            let results = store
2512                .search(SearchQuery {
2513                    text: None,
2514                    embedding: create_random_embedding(TEST_DIM),
2515                    limit: 5,
2516                    filters: vec![],
2517                    metric: DistanceMetric::Cosine,
2518                    scope_prefix: None,
2519                })
2520                .await
2521                .unwrap();
2522            assert!(!results.is_empty());
2523            return;
2524        }
2525
2526        let name = LanceStore::vector_index_name(&table)
2527            .await
2528            .expect("L2 fixture index");
2529        let before = table.index_stats(&name).await.unwrap().unwrap();
2530        assert_eq!(before.distance_type, Some(DistanceType::L2));
2531
2532        store.ensure_vector_index().await.unwrap();
2533
2534        if let Some(after_name) = LanceStore::vector_index_name(&table).await {
2535            let after = table.index_stats(&after_name).await.unwrap().unwrap();
2536            assert!(
2537                LanceStore::ann_index_is_cosine(after.distance_type),
2538                "mismatched L2 index must be replaced with cosine"
2539            );
2540        } else {
2541            // Below MIN_ANN_ROWS: drop L2 and stay on exact scan.
2542        }
2543
2544        let results = store
2545            .search(SearchQuery {
2546                text: None,
2547                embedding: create_random_embedding(TEST_DIM),
2548                limit: 5,
2549                filters: vec![],
2550                metric: DistanceMetric::Cosine,
2551                scope_prefix: None,
2552            })
2553            .await
2554            .unwrap();
2555        assert!(!results.is_empty());
2556    }
2557
2558    #[tokio::test]
2559    async fn test_get_file_not_found() {
2560        let temp = tempdir().unwrap();
2561        let db_path = temp.path().join("test.lance");
2562        let store = LanceStore::new(db_path.clone(), TEST_DIM);
2563        store.init().await.unwrap();
2564
2565        let path = PathBuf::from("/nonexistent/file.txt");
2566        let result = store.get_file(&path).await.unwrap();
2567        assert!(result.is_none());
2568    }
2569
2570    fn create_chunk_with_meta(
2571        file_path: &Path,
2572        content: &str,
2573        embedding: Vec<f32>,
2574        content_type: ContentType,
2575        mime_type: Option<String>,
2576        depth: u8,
2577    ) -> Chunk {
2578        Chunk {
2579            id: Uuid::new_v4(),
2580            file_id: Uuid::new_v4(),
2581            file_path: file_path.to_path_buf(),
2582            content: content.to_string(),
2583            content_type,
2584            mime_type,
2585            chunk_index: 0,
2586            byte_range: 0..content.len() as u64,
2587            line_range: Some(0..1),
2588            parent_chunk_id: None,
2589            depth,
2590            embedding: Some(embedding),
2591            dir_path: DirectoryScope::from_file_path(file_path).dir_path,
2592            dir_depth: DirectoryScope::from_file_path(file_path).dir_depth,
2593            path_components: DirectoryScope::from_file_path(file_path).path_components,
2594            metadata: ChunkMetadata {
2595                media: Default::default(),
2596                indexed_at: Some(Utc::now()),
2597                embedding_model: Some("test-model".to_string()),
2598                token_count: None,
2599                extra: HashMap::new(),
2600            },
2601        }
2602    }
2603
2604    async fn seeded_filter_store() -> (tempfile::TempDir, LanceStore, Vec<f32>) {
2605        let temp = tempdir().unwrap();
2606        let db_path = temp.path().join("test.lance");
2607        let store = LanceStore::new(db_path, TEST_DIM);
2608        store.init().await.unwrap();
2609
2610        let embedding = create_random_embedding(TEST_DIM);
2611        let chunks = vec![
2612            create_chunk_with_meta(
2613                Path::new("src/lib.rs"),
2614                "fn rust_auth() {}",
2615                embedding.clone(),
2616                ContentType::Code {
2617                    language: "rust".to_string(),
2618                    symbol: None,
2619                },
2620                Some("text/x-rust".to_string()),
2621                0,
2622            ),
2623            create_chunk_with_meta(
2624                Path::new("src/app.py"),
2625                "def python_auth(): pass",
2626                embedding.clone(),
2627                ContentType::Code {
2628                    language: "python".to_string(),
2629                    symbol: None,
2630                },
2631                Some("text/x-python".to_string()),
2632                1,
2633            ),
2634            create_chunk_with_meta(
2635                Path::new("docs/readme.md"),
2636                "authentication notes",
2637                embedding.clone(),
2638                ContentType::Markdown,
2639                Some("text/markdown".to_string()),
2640                3,
2641            ),
2642            create_chunk_with_meta(
2643                Path::new("notes/plain.txt"),
2644                "plain authentication text",
2645                embedding.clone(),
2646                ContentType::Text,
2647                Some("text/plain".to_string()),
2648                2,
2649            ),
2650        ];
2651        store.upsert_chunks(&chunks).await.unwrap();
2652        (temp, store, embedding)
2653    }
2654
2655    fn search_query(
2656        embedding: Vec<f32>,
2657        filters: Vec<SearchFilter>,
2658        metric: DistanceMetric,
2659    ) -> SearchQuery {
2660        SearchQuery {
2661            text: Some("authentication".to_string()),
2662            embedding,
2663            limit: 10,
2664            filters,
2665            metric,
2666            scope_prefix: None,
2667        }
2668    }
2669
2670    #[test]
2671    fn test_filters_to_sql_language_path_type_depth() {
2672        let sql = filters_to_sql(&[
2673            SearchFilter::Language("Rust".to_string()),
2674            SearchFilter::PathPrefix("src/".to_string()),
2675            SearchFilter::MimeType("code".to_string()),
2676            SearchFilter::MaxDepth(2),
2677        ])
2678        .unwrap();
2679
2680        assert!(sql.contains("LOWER(language) = 'rust'"));
2681        assert!(sql.contains("LOWER(content_type) = 'code:rust'"));
2682        assert!(sql.contains("file_path LIKE 'src/%' ESCAPE '\\'"));
2683        assert!(sql.contains("LOWER(content_type) LIKE 'code:%'"));
2684        assert!(sql.contains("depth <= 2"));
2685        assert!(sql.contains(" AND "));
2686    }
2687
2688    #[test]
2689    fn test_filters_to_sql_path_glob_and_mime() {
2690        let sql = filters_to_sql(&[
2691            SearchFilter::PathGlob("src/**/*.rs".to_string()),
2692            SearchFilter::MimeType("text/x-rust".to_string()),
2693            SearchFilter::MinDepth(1),
2694        ])
2695        .unwrap();
2696
2697        assert!(sql.contains("regexp_like(file_path, '^src/(?:.*/)?[^/]*\\.rs$')"));
2698        assert!(sql.contains("LOWER(file_mime_type) = 'text/x-rust'"));
2699        assert!(sql.contains("depth >= 1"));
2700    }
2701
2702    #[test]
2703    fn test_filters_to_sql_escapes_quotes() {
2704        let sql = filters_to_sql(&[SearchFilter::PathPrefix("o'brien".to_string())]).unwrap();
2705        assert!(sql.contains("o''brien"));
2706    }
2707
2708    #[test]
2709    fn test_filters_to_sql_empty() {
2710        assert!(filters_to_sql(&[]).is_none());
2711    }
2712
2713    #[test]
2714    fn test_glob_to_regex_preserves_path_segments() {
2715        assert_eq!(glob_to_regex("src/*.rs"), r"^src/[^/]*\.rs$");
2716        assert_eq!(glob_to_regex("src/**/mod.rs"), r"^src/(?:.*/)?mod\.rs$");
2717        assert_eq!(glob_to_regex("src/**"), r"^src/.*$");
2718        assert_eq!(glob_to_regex("file?.txt"), r"^file[^/]\.txt$");
2719        assert!(!glob_to_regex("src/*.rs").contains(".*"));
2720        assert!(!glob_to_regex("src/**/mod.rs").contains("%mod"));
2721    }
2722
2723    #[test]
2724    fn test_file_date_filters_use_modified_at() {
2725        let after = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00+00:00")
2726            .unwrap()
2727            .with_timezone(&Utc);
2728        let sql = file_date_filters_to_sql(&[SearchFilter::ModifiedAfter(after)]).unwrap();
2729        assert!(sql.contains("modified_at >= "));
2730        assert!(!sql.contains("indexed_at"));
2731        assert!(filters_to_sql(&[SearchFilter::ModifiedAfter(after)]).is_none());
2732    }
2733
2734    #[test]
2735    fn test_distance_type_from_metric() {
2736        assert_eq!(
2737            distance_type_from_metric(DistanceMetric::Cosine),
2738            DistanceType::Cosine
2739        );
2740        assert_eq!(
2741            distance_type_from_metric(DistanceMetric::L2),
2742            DistanceType::L2
2743        );
2744        assert_eq!(
2745            distance_type_from_metric(DistanceMetric::Dot),
2746            DistanceType::Dot
2747        );
2748    }
2749
2750    #[tokio::test]
2751    async fn test_search_filters_by_language() {
2752        let (_temp, store, embedding) = seeded_filter_store().await;
2753        let results = store
2754            .search(search_query(
2755                embedding,
2756                vec![SearchFilter::Language("rust".to_string())],
2757                DistanceMetric::Cosine,
2758            ))
2759            .await
2760            .unwrap();
2761
2762        assert_eq!(results.len(), 1);
2763        assert_eq!(results[0].file_path, PathBuf::from("src/lib.rs"));
2764    }
2765
2766    #[tokio::test]
2767    async fn test_search_filters_by_path_prefix() {
2768        let (_temp, store, embedding) = seeded_filter_store().await;
2769        let results = store
2770            .search(search_query(
2771                embedding,
2772                vec![SearchFilter::PathPrefix("src/".to_string())],
2773                DistanceMetric::Cosine,
2774            ))
2775            .await
2776            .unwrap();
2777
2778        let paths: Vec<_> = results.iter().map(|r| r.file_path.clone()).collect();
2779        assert_eq!(results.len(), 2);
2780        assert!(paths.contains(&PathBuf::from("src/lib.rs")));
2781        assert!(paths.contains(&PathBuf::from("src/app.py")));
2782        assert!(!paths.contains(&PathBuf::from("docs/readme.md")));
2783    }
2784
2785    #[tokio::test]
2786    async fn test_search_filters_by_path_glob() {
2787        let (_temp, store, embedding) = seeded_filter_store().await;
2788        let results = store
2789            .search(search_query(
2790                embedding,
2791                vec![SearchFilter::PathGlob("src/**".to_string())],
2792                DistanceMetric::Cosine,
2793            ))
2794            .await
2795            .unwrap();
2796
2797        let paths: Vec<_> = results.iter().map(|r| r.file_path.clone()).collect();
2798        assert_eq!(results.len(), 2);
2799        assert!(paths.contains(&PathBuf::from("src/lib.rs")));
2800        assert!(paths.contains(&PathBuf::from("src/app.py")));
2801    }
2802
2803    #[tokio::test]
2804    async fn test_search_filters_by_type_code() {
2805        let (_temp, store, embedding) = seeded_filter_store().await;
2806        let results = store
2807            .search(search_query(
2808                embedding,
2809                vec![SearchFilter::MimeType("code".to_string())],
2810                DistanceMetric::Cosine,
2811            ))
2812            .await
2813            .unwrap();
2814
2815        let paths: Vec<_> = results.iter().map(|r| r.file_path.clone()).collect();
2816        assert_eq!(results.len(), 2);
2817        assert!(paths.contains(&PathBuf::from("src/lib.rs")));
2818        assert!(paths.contains(&PathBuf::from("src/app.py")));
2819        assert!(!paths.contains(&PathBuf::from("notes/plain.txt")));
2820    }
2821
2822    #[tokio::test]
2823    async fn test_search_filters_by_mime_type() {
2824        let (_temp, store, embedding) = seeded_filter_store().await;
2825        let results = store
2826            .search(search_query(
2827                embedding,
2828                vec![SearchFilter::MimeType("text/plain".to_string())],
2829                DistanceMetric::Cosine,
2830            ))
2831            .await
2832            .unwrap();
2833
2834        assert_eq!(results.len(), 1);
2835        assert_eq!(results[0].file_path, PathBuf::from("notes/plain.txt"));
2836    }
2837
2838    #[tokio::test]
2839    async fn test_search_filters_by_max_depth() {
2840        let (_temp, store, embedding) = seeded_filter_store().await;
2841        let results = store
2842            .search(search_query(
2843                embedding,
2844                vec![SearchFilter::MaxDepth(1)],
2845                DistanceMetric::Cosine,
2846            ))
2847            .await
2848            .unwrap();
2849
2850        let paths: Vec<_> = results.iter().map(|r| r.file_path.clone()).collect();
2851        assert_eq!(results.len(), 2);
2852        assert!(paths.contains(&PathBuf::from("src/lib.rs")));
2853        assert!(paths.contains(&PathBuf::from("src/app.py")));
2854        assert!(!paths.contains(&PathBuf::from("docs/readme.md")));
2855        assert!(!paths.contains(&PathBuf::from("notes/plain.txt")));
2856    }
2857
2858    #[tokio::test]
2859    async fn test_search_combines_filters() {
2860        let (_temp, store, embedding) = seeded_filter_store().await;
2861        let results = store
2862            .search(search_query(
2863                embedding,
2864                vec![
2865                    SearchFilter::PathPrefix("src/".to_string()),
2866                    SearchFilter::Language("python".to_string()),
2867                    SearchFilter::MaxDepth(2),
2868                ],
2869                DistanceMetric::Cosine,
2870            ))
2871            .await
2872            .unwrap();
2873
2874        assert_eq!(results.len(), 1);
2875        assert_eq!(results[0].file_path, PathBuf::from("src/app.py"));
2876    }
2877
2878    #[tokio::test]
2879    async fn test_search_applies_l2_and_dot_metrics() {
2880        let (_temp, store, embedding) = seeded_filter_store().await;
2881        let filters = vec![SearchFilter::Language("rust".to_string())];
2882
2883        for metric in [
2884            DistanceMetric::L2,
2885            DistanceMetric::Dot,
2886            DistanceMetric::Cosine,
2887        ] {
2888            let results = store
2889                .search(search_query(embedding.clone(), filters.clone(), metric))
2890                .await
2891                .unwrap();
2892            assert_eq!(
2893                results.len(),
2894                1,
2895                "metric {metric:?} should still honor language filter"
2896            );
2897            assert_eq!(results[0].file_path, PathBuf::from("src/lib.rs"));
2898        }
2899    }
2900
2901    #[tokio::test]
2902    async fn test_hybrid_search_applies_filters_and_metric() {
2903        let (_temp, store, embedding) = seeded_filter_store().await;
2904        let results = store
2905            .hybrid_search(search_query(
2906                embedding,
2907                vec![
2908                    SearchFilter::Language("rust".to_string()),
2909                    SearchFilter::MimeType("code".to_string()),
2910                    SearchFilter::MaxDepth(1),
2911                ],
2912                DistanceMetric::Cosine,
2913            ))
2914            .await
2915            .unwrap();
2916
2917        assert_eq!(results.len(), 1);
2918        assert_eq!(results[0].file_path, PathBuf::from("src/lib.rs"));
2919        assert!(results[0].content.contains("rust_auth"));
2920    }
2921
2922    async fn seeded_glob_boundary_store() -> (tempfile::TempDir, LanceStore, Vec<f32>) {
2923        let temp = tempdir().unwrap();
2924        let store = LanceStore::new(temp.path().join("test.lance"), TEST_DIM);
2925        store.init().await.unwrap();
2926        let embedding = create_random_embedding(TEST_DIM);
2927        store
2928            .upsert_chunks(&[
2929                create_test_chunk(Path::new("src/lib.rs"), "lib", embedding.clone(), 0),
2930                create_test_chunk(
2931                    Path::new("src/nested/file.rs"),
2932                    "nested",
2933                    embedding.clone(),
2934                    0,
2935                ),
2936                create_test_chunk(Path::new("src/mod.rs"), "mod file", embedding.clone(), 0),
2937                create_test_chunk(Path::new("src/notmod.rs"), "not mod", embedding.clone(), 0),
2938            ])
2939            .await
2940            .unwrap();
2941        (temp, store, embedding)
2942    }
2943
2944    #[tokio::test]
2945    async fn test_search_path_glob_star_does_not_cross_slash() {
2946        let (_temp, store, embedding) = seeded_glob_boundary_store().await;
2947        let results = store
2948            .search(search_query(
2949                embedding,
2950                vec![SearchFilter::PathGlob("src/*.rs".to_string())],
2951                DistanceMetric::Cosine,
2952            ))
2953            .await
2954            .unwrap();
2955
2956        let paths: Vec<_> = results.iter().map(|r| r.file_path.clone()).collect();
2957        assert!(paths.contains(&PathBuf::from("src/lib.rs")));
2958        assert!(paths.contains(&PathBuf::from("src/mod.rs")));
2959        assert!(paths.contains(&PathBuf::from("src/notmod.rs")));
2960        assert!(!paths.contains(&PathBuf::from("src/nested/file.rs")));
2961    }
2962
2963    #[tokio::test]
2964    async fn test_search_path_glob_doublestar_keeps_separator() {
2965        let (_temp, store, embedding) = seeded_glob_boundary_store().await;
2966        let results = store
2967            .search(search_query(
2968                embedding,
2969                vec![SearchFilter::PathGlob("src/**/mod.rs".to_string())],
2970                DistanceMetric::Cosine,
2971            ))
2972            .await
2973            .unwrap();
2974
2975        let paths: Vec<_> = results.iter().map(|r| r.file_path.clone()).collect();
2976        assert_eq!(results.len(), 1);
2977        assert!(paths.contains(&PathBuf::from("src/mod.rs")));
2978        assert!(!paths.contains(&PathBuf::from("src/notmod.rs")));
2979        assert!(!paths.contains(&PathBuf::from("src/lib.rs")));
2980    }
2981
2982    #[tokio::test]
2983    async fn test_search_filters_by_source_modified_at() {
2984        let temp = tempdir().unwrap();
2985        let store = LanceStore::new(temp.path().join("test.lance"), TEST_DIM);
2986        store.init().await.unwrap();
2987        let embedding = create_random_embedding(TEST_DIM);
2988
2989        let old_path = PathBuf::from("old.txt");
2990        let new_path = PathBuf::from("new.txt");
2991        store
2992            .upsert_chunks(&[
2993                create_test_chunk(&old_path, "old file", embedding.clone(), 0),
2994                create_test_chunk(&new_path, "new file", embedding.clone(), 0),
2995            ])
2996            .await
2997            .unwrap();
2998
2999        let old_modified = chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00+00:00")
3000            .unwrap()
3001            .with_timezone(&Utc);
3002        let new_modified = chrono::DateTime::parse_from_rfc3339("2024-06-01T00:00:00+00:00")
3003            .unwrap()
3004            .with_timezone(&Utc);
3005        let cutoff = chrono::DateTime::parse_from_rfc3339("2022-01-01T00:00:00+00:00")
3006            .unwrap()
3007            .with_timezone(&Utc);
3008
3009        let mut old_record = create_test_file_record(&old_path);
3010        old_record.modified_at = old_modified;
3011        let mut new_record = create_test_file_record(&new_path);
3012        new_record.modified_at = new_modified;
3013        store.upsert_file(&old_record).await.unwrap();
3014        store.upsert_file(&new_record).await.unwrap();
3015
3016        let results = store
3017            .search(search_query(
3018                embedding,
3019                vec![SearchFilter::ModifiedAfter(cutoff)],
3020                DistanceMetric::Cosine,
3021            ))
3022            .await
3023            .unwrap();
3024
3025        assert_eq!(results.len(), 1);
3026        assert_eq!(results[0].file_path, new_path);
3027    }
3028
3029    fn create_chunk_with_scope(
3030        file_path: &Path,
3031        root: Option<&Path>,
3032        content: &str,
3033        embedding: Vec<f32>,
3034    ) -> Chunk {
3035        let scope = DirectoryScope::from_paths(file_path, root);
3036        let mut chunk = create_test_chunk(file_path, content, embedding, 0);
3037        chunk.dir_path = scope.dir_path;
3038        chunk.dir_depth = scope.dir_depth;
3039        chunk.path_components = scope.path_components;
3040        chunk
3041    }
3042
3043    async fn seeded_scope_store() -> (tempfile::TempDir, LanceStore, Vec<f32>) {
3044        let temp = tempdir().unwrap();
3045        let db_path = temp.path().join("test.lance");
3046        let store = LanceStore::new(db_path, TEST_DIM);
3047        store.init().await.unwrap();
3048
3049        let root = Path::new("/project");
3050        let embedding = create_random_embedding(TEST_DIM);
3051        let chunks = vec![
3052            create_chunk_with_scope(
3053                Path::new("/project/src/auth/login.rs"),
3054                Some(root),
3055                "login handler",
3056                embedding.clone(),
3057            ),
3058            create_chunk_with_scope(
3059                Path::new("/project/src/auth/oauth/token.rs"),
3060                Some(root),
3061                "oauth token",
3062                embedding.clone(),
3063            ),
3064            create_chunk_with_scope(
3065                Path::new("/project/src/db.rs"),
3066                Some(root),
3067                "database pool",
3068                embedding.clone(),
3069            ),
3070            create_chunk_with_scope(
3071                Path::new("/project/docs/readme.md"),
3072                Some(root),
3073                "project readme",
3074                embedding.clone(),
3075            ),
3076        ];
3077        store.upsert_chunks(&chunks).await.unwrap();
3078        (temp, store, embedding)
3079    }
3080
3081    fn scoped_query(embedding: Vec<f32>, scope: &str) -> SearchQuery {
3082        SearchQuery {
3083            text: None,
3084            embedding,
3085            limit: 10,
3086            filters: vec![],
3087            metric: DistanceMetric::Cosine,
3088            scope_prefix: Some(scope.to_string()),
3089        }
3090    }
3091
3092    #[test]
3093    fn test_scope_prefix_sql_exact_or_subdirectory() {
3094        let sql = scope_prefix_sql("src/auth/").unwrap();
3095        assert!(sql.contains("dir_path = 'src/auth'"));
3096        assert!(sql.contains("dir_path LIKE 'src/auth/%'"));
3097        assert!(sql.contains("dir_path LIKE '%/src/auth'"));
3098        assert!(sql.contains("dir_path LIKE '%/src/auth/%'"));
3099        assert!(scope_prefix_sql("").is_none());
3100        assert!(scope_prefix_sql(".").is_none());
3101    }
3102
3103    #[test]
3104    fn test_scope_prefix_sql_escapes_quotes() {
3105        let sql = scope_prefix_sql("o'brien").unwrap();
3106        assert!(sql.contains("o''brien"));
3107    }
3108
3109    #[tokio::test]
3110    async fn test_scoped_search_stores_relative_dir_path() {
3111        let (_temp, store, _) = seeded_scope_store().await;
3112        let chunks = store
3113            .get_chunks_for_file(Path::new("/project/src/auth/login.rs"))
3114            .await
3115            .unwrap();
3116        assert_eq!(chunks.len(), 1);
3117        assert_eq!(chunks[0].dir_path, "src/auth");
3118        assert_eq!(chunks[0].dir_depth, 2);
3119        assert_eq!(chunks[0].path_components, "src,auth,login.rs");
3120        assert!(!chunks[0].dir_path.starts_with('/'));
3121    }
3122
3123    #[tokio::test]
3124    async fn test_scoped_search_exact_directory() {
3125        let (_temp, store, embedding) = seeded_scope_store().await;
3126        let results = store
3127            .search(scoped_query(embedding, "src/auth"))
3128            .await
3129            .unwrap();
3130        let paths: Vec<_> = results
3131            .iter()
3132            .map(|r| r.file_path.to_string_lossy().to_string())
3133            .collect();
3134        assert!(paths.iter().any(|p| p.ends_with("src/auth/login.rs")));
3135        assert!(paths.iter().any(|p| p.ends_with("src/auth/oauth/token.rs")));
3136        assert!(!paths.iter().any(|p| p.ends_with("src/db.rs")));
3137        assert!(!paths.iter().any(|p| p.ends_with("docs/readme.md")));
3138    }
3139
3140    #[tokio::test]
3141    async fn test_scoped_search_includes_subdirectory() {
3142        let (_temp, store, embedding) = seeded_scope_store().await;
3143        let results = store.search(scoped_query(embedding, "src")).await.unwrap();
3144        let paths: Vec<_> = results
3145            .iter()
3146            .map(|r| r.file_path.to_string_lossy().to_string())
3147            .collect();
3148        assert!(paths.iter().any(|p| p.ends_with("src/auth/login.rs")));
3149        assert!(paths.iter().any(|p| p.ends_with("src/auth/oauth/token.rs")));
3150        assert!(paths.iter().any(|p| p.ends_with("src/db.rs")));
3151        assert!(!paths.iter().any(|p| p.ends_with("docs/readme.md")));
3152    }
3153
3154    #[tokio::test]
3155    async fn test_scoped_search_excludes_outside_directory() {
3156        let (_temp, store, embedding) = seeded_scope_store().await;
3157        let results = store.search(scoped_query(embedding, "docs")).await.unwrap();
3158        assert_eq!(results.len(), 1);
3159        assert!(
3160            results[0]
3161                .file_path
3162                .to_string_lossy()
3163                .ends_with("docs/readme.md")
3164        );
3165    }
3166
3167    fn v1_chunks_schema(dim: usize) -> Schema {
3168        Schema::new(vec![
3169            Field::new("chunk_id", DataType::Utf8, false),
3170            Field::new("file_id", DataType::Utf8, false),
3171            Field::new("file_path", DataType::Utf8, false),
3172            Field::new("content", DataType::Utf8, false),
3173            Field::new("content_type", DataType::Utf8, false),
3174            Field::new("chunk_index", DataType::UInt32, false),
3175            Field::new("start_byte", DataType::UInt64, false),
3176            Field::new("end_byte", DataType::UInt64, false),
3177            Field::new("start_line", DataType::UInt32, true),
3178            Field::new("end_line", DataType::UInt32, true),
3179            Field::new("parent_chunk_id", DataType::Utf8, true),
3180            Field::new("depth", DataType::UInt8, false),
3181            Field::new(
3182                "vector",
3183                DataType::FixedSizeList(
3184                    Arc::new(Field::new("item", DataType::Float32, true)),
3185                    dim as i32,
3186                ),
3187                false,
3188            ),
3189            Field::new("embedding_model", DataType::Utf8, true),
3190            Field::new("indexed_at", DataType::Utf8, false),
3191            Field::new("file_mime_type", DataType::Utf8, true),
3192            Field::new("language", DataType::Utf8, true),
3193            Field::new("symbol_type", DataType::Utf8, true),
3194            Field::new("symbol_name", DataType::Utf8, true),
3195        ])
3196    }
3197
3198    async fn seed_v1_chunks_table(
3199        db_path: &Path,
3200        file_path: &str,
3201        content: &str,
3202        embedding: &[f32],
3203    ) {
3204        let conn = connect(db_path.to_str().unwrap()).execute().await.unwrap();
3205        let schema = Arc::new(v1_chunks_schema(TEST_DIM));
3206        conn.create_empty_table(CHUNKS_TABLE, schema.clone())
3207            .execute()
3208            .await
3209            .unwrap();
3210
3211        let embeddings = vec![Some(embedding.iter().copied().map(Some).collect())];
3212        let vector = build_vector_array(&embeddings, TEST_DIM).unwrap();
3213        let batch = RecordBatch::try_new(
3214            schema,
3215            vec![
3216                Arc::new(StringArray::from(vec![Uuid::new_v4().to_string()])),
3217                Arc::new(StringArray::from(vec![Uuid::new_v4().to_string()])),
3218                Arc::new(StringArray::from(vec![file_path.to_string()])),
3219                Arc::new(StringArray::from(vec![content.to_string()])),
3220                Arc::new(StringArray::from(vec!["text".to_string()])),
3221                Arc::new(UInt32Array::from(vec![0u32])),
3222                Arc::new(UInt64Array::from(vec![0u64])),
3223                Arc::new(UInt64Array::from(vec![content.len() as u64])),
3224                Arc::new(UInt32Array::from(vec![Some(0u32)])),
3225                Arc::new(UInt32Array::from(vec![Some(1u32)])),
3226                Arc::new(StringArray::from(vec![None::<String>])),
3227                Arc::new(UInt8Array::from(vec![0u8])),
3228                vector,
3229                Arc::new(StringArray::from(vec![Some("test-model".to_string())])),
3230                Arc::new(StringArray::from(vec![Utc::now().to_rfc3339()])),
3231                Arc::new(StringArray::from(vec![Some("text/plain".to_string())])),
3232                Arc::new(StringArray::from(vec![None::<String>])),
3233                Arc::new(StringArray::from(vec![None::<String>])),
3234                Arc::new(StringArray::from(vec![None::<String>])),
3235            ],
3236        )
3237        .unwrap();
3238
3239        let table = conn.open_table(CHUNKS_TABLE).execute().await.unwrap();
3240        let schema = batch.schema();
3241        let batches = RecordBatchIterator::new(vec![Ok(batch)], schema);
3242        table
3243            .add(Box::new(batches) as Box<dyn RecordBatchReader + Send>)
3244            .execute()
3245            .await
3246            .unwrap();
3247    }
3248
3249    #[tokio::test]
3250    async fn schema_v2_media_migration_is_idempotent() {
3251        let temp = tempdir().unwrap();
3252        let db_path = temp.path().join("old.lance");
3253        let store = LanceStore::new(db_path.clone(), TEST_DIM);
3254        let mut chunk = create_test_chunk(
3255            Path::new("/project/old.txt"),
3256            "old text",
3257            create_random_embedding(TEST_DIM),
3258            0,
3259        );
3260        chunk.dir_path = String::new();
3261        chunk.dir_depth = 0;
3262        chunk.path_components = "old.txt".into();
3263        let current = store.chunks_to_batch(&[chunk]).unwrap();
3264        let indices: Vec<usize> = (0..current.num_columns() - 3).collect();
3265        let old = current.project(&indices).unwrap();
3266        let conn = connect(db_path.to_str().unwrap()).execute().await.unwrap();
3267        let schema = old.schema();
3268        conn.create_table(
3269            CHUNKS_TABLE,
3270            Box::new(RecordBatchIterator::new(vec![Ok(old)], schema))
3271                as Box<dyn RecordBatchReader + Send>,
3272        )
3273        .execute()
3274        .await
3275        .unwrap();
3276        std::fs::write(
3277            temp.path().join(SCHEMA_SIDECAR_FILENAME),
3278            r#"{"chunks_schema_version":2,"index_revision":7}"#,
3279        )
3280        .unwrap();
3281        store.init().await.unwrap();
3282        let revision = store.index_revision().await.unwrap();
3283        store.init().await.unwrap();
3284        assert_eq!(store.index_revision().await.unwrap(), revision);
3285        let chunks = store.get_all_chunks().await.unwrap();
3286        assert_eq!(chunks.len(), 1);
3287        assert_eq!(chunks[0].dir_path, "");
3288        assert_eq!(chunks[0].path_components, "old.txt");
3289        assert_eq!(chunks[0].metadata.media, ragfs_core::MediaInfo::default());
3290    }
3291
3292    #[tokio::test]
3293    async fn media_roundtrips_through_storage_and_search() {
3294        let temp = tempdir().unwrap();
3295        let store = LanceStore::new(temp.path().join("media.lance"), TEST_DIM);
3296        store.init().await.unwrap();
3297        let embedding = create_random_embedding(TEST_DIM);
3298        let mut chunk = create_test_chunk(
3299            Path::new("/project/clip.mp4"),
3300            "authentication clip",
3301            embedding.clone(),
3302            0,
3303        );
3304        chunk.metadata.media = ragfs_core::MediaInfo {
3305            modality: "video".into(),
3306            start_ms: Some(100),
3307            end_ms: Some(900),
3308        };
3309        store.upsert_chunks(&[chunk.clone()]).await.unwrap();
3310        let stored = store.get_chunks_for_file(&chunk.file_path).await.unwrap();
3311        assert_eq!(stored[0].metadata.media, chunk.metadata.media);
3312        assert_eq!(stored[0].embedding, chunk.embedding);
3313        let query = search_query(embedding, vec![], DistanceMetric::Cosine);
3314        assert_eq!(
3315            store.search(query.clone()).await.unwrap()[0].media,
3316            chunk.metadata.media
3317        );
3318        assert_eq!(
3319            store.hybrid_search(query).await.unwrap()[0].media,
3320            chunk.metadata.media
3321        );
3322        chunk.metadata.media.end_ms = Some(0);
3323        assert!(store.upsert_chunks(&[chunk]).await.is_err());
3324    }
3325
3326    #[tokio::test]
3327    async fn test_schema_v3_migrates_existing_index() {
3328        let temp = tempdir().unwrap();
3329        let db_path = temp.path().join("test.lance");
3330        let file_path = "/project/src/auth/login.rs";
3331        let embedding = create_random_embedding(TEST_DIM);
3332        seed_v1_chunks_table(&db_path, file_path, "login handler", &embedding).await;
3333
3334        assert!(!temp.path().join(SCHEMA_SIDECAR_FILENAME).exists());
3335
3336        let store = LanceStore::new(db_path, TEST_DIM);
3337        store.init().await.unwrap();
3338
3339        let sidecar: SchemaSidecar = serde_json::from_slice(
3340            &std::fs::read(temp.path().join(SCHEMA_SIDECAR_FILENAME)).unwrap(),
3341        )
3342        .unwrap();
3343        assert_eq!(sidecar.chunks_schema_version, CHUNKS_SCHEMA_VERSION);
3344        assert_eq!(sidecar.embedding_dim, Some(TEST_DIM));
3345
3346        let chunks = store
3347            .get_chunks_for_file(Path::new(file_path))
3348            .await
3349            .unwrap();
3350        assert_eq!(chunks.len(), 1);
3351        assert_eq!(chunks[0].dir_path, "project/src/auth");
3352        assert_eq!(chunks[0].dir_depth, 3);
3353        assert_eq!(chunks[0].path_components, "project,src,auth,login.rs");
3354
3355        let results = store
3356            .search(scoped_query(embedding, "src/auth"))
3357            .await
3358            .unwrap();
3359        assert_eq!(results.len(), 1);
3360        assert!(
3361            results[0]
3362                .file_path
3363                .to_string_lossy()
3364                .ends_with("src/auth/login.rs")
3365        );
3366
3367        // Second init is idempotent (sidecar already v3, columns present).
3368        store.init().await.unwrap();
3369        let again = store
3370            .get_chunks_for_file(Path::new(file_path))
3371            .await
3372            .unwrap();
3373        assert_eq!(again[0].dir_path, "project/src/auth");
3374        assert_eq!(again.len(), 1);
3375        assert_eq!(again[0].metadata.media, ragfs_core::MediaInfo::default());
3376        assert_eq!(results[0].media, ragfs_core::MediaInfo::default());
3377    }
3378
3379    #[tokio::test]
3380    async fn test_new_index_writes_schema_v3_sidecar() {
3381        let temp = tempdir().unwrap();
3382        let db_path = temp.path().join("test.lance");
3383        let store = LanceStore::new(db_path, TEST_DIM).with_embedding_model("thenlper/gte-small");
3384        store.init().await.unwrap();
3385
3386        let sidecar: SchemaSidecar = serde_json::from_slice(
3387            &std::fs::read(temp.path().join(SCHEMA_SIDECAR_FILENAME)).unwrap(),
3388        )
3389        .unwrap();
3390        assert_eq!(sidecar.chunks_schema_version, CHUNKS_SCHEMA_VERSION);
3391        assert_eq!(sidecar.embedding_dim, Some(TEST_DIM));
3392        assert_eq!(
3393            sidecar.embedding_model.as_deref(),
3394            Some("thenlper/gte-small")
3395        );
3396        assert_eq!(sidecar.index_revision, 1);
3397        assert_eq!(sidecar.chunks_schema_version, CHUNKS_SCHEMA_VERSION);
3398    }
3399
3400    #[tokio::test]
3401    async fn index_revision_changes_on_writes_not_reads() {
3402        let temp = tempdir().unwrap();
3403        let db_path = temp.path().join("test.lance");
3404        let store = LanceStore::new(db_path, TEST_DIM);
3405        store.init().await.unwrap();
3406
3407        let initial = store.index_revision().await.unwrap();
3408        assert_eq!(initial, 1);
3409
3410        let embedding = create_random_embedding(TEST_DIM);
3411        store
3412            .search(SearchQuery {
3413                embedding: embedding.clone(),
3414                text: None,
3415                limit: 1,
3416                filters: vec![],
3417                metric: DistanceMetric::Cosine,
3418                scope_prefix: None,
3419            })
3420            .await
3421            .unwrap();
3422        store.stats().await.unwrap();
3423        store.init().await.unwrap();
3424        assert_eq!(store.index_revision().await.unwrap(), initial);
3425
3426        let path = Path::new("/tmp/rev.txt");
3427        store
3428            .upsert_chunks(&[create_test_chunk(path, "hello", embedding.clone(), 0)])
3429            .await
3430            .unwrap();
3431        let after_add = store.index_revision().await.unwrap();
3432        assert!(after_add > initial);
3433
3434        store.upsert_chunks(&[]).await.unwrap();
3435        assert_eq!(store.index_revision().await.unwrap(), after_add);
3436
3437        store
3438            .update_file_path(path, Path::new("/tmp/rev-renamed.txt"))
3439            .await
3440            .unwrap();
3441        let after_update = store.index_revision().await.unwrap();
3442        assert!(after_update > after_add);
3443
3444        store
3445            .delete_by_file_path(Path::new("/tmp/rev-renamed.txt"))
3446            .await
3447            .unwrap();
3448        assert!(store.index_revision().await.unwrap() > after_update);
3449    }
3450
3451    #[tokio::test]
3452    async fn old_sidecar_without_revision_is_initialized_without_reindex() {
3453        let temp = tempdir().unwrap();
3454        let db_path = temp.path().join("test.lance");
3455        let store = LanceStore::new(db_path, TEST_DIM);
3456        store.init().await.unwrap();
3457        let path = Path::new("/tmp/old.txt");
3458        let embedding = create_random_embedding(TEST_DIM);
3459        store
3460            .upsert_chunks(&[create_test_chunk(path, "existing", embedding, 0)])
3461            .await
3462            .unwrap();
3463        let chunks_before = store.get_chunks_for_file(path).await.unwrap();
3464        assert_eq!(chunks_before.len(), 1);
3465
3466        let sidecar_path = temp.path().join(SCHEMA_SIDECAR_FILENAME);
3467        std::fs::write(&sidecar_path, r#"{"chunks_schema_version":2}"#).unwrap();
3468
3469        store.init().await.unwrap();
3470        let sidecar: SchemaSidecar =
3471            serde_json::from_slice(&std::fs::read(&sidecar_path).unwrap()).unwrap();
3472        assert_eq!(sidecar.chunks_schema_version, CHUNKS_SCHEMA_VERSION);
3473        assert_eq!(sidecar.index_revision, 1);
3474
3475        let chunks_after = store.get_chunks_for_file(path).await.unwrap();
3476        assert_eq!(chunks_after.len(), 1);
3477        assert_eq!(chunks_after[0].content, "existing");
3478        assert_eq!(store.index_revision().await.unwrap(), 1);
3479        store.stats().await.unwrap();
3480        assert_eq!(store.index_revision().await.unwrap(), 1);
3481    }
3482    #[tokio::test]
3483    async fn different_same_width_model_requires_explicit_rebuild() {
3484        let temp = tempdir().unwrap();
3485        let path = temp.path().join("test.lance");
3486        let old = LanceStore::new(path.clone(), TEST_DIM).with_embedding_model("model-a");
3487        old.init().await.unwrap();
3488        old.upsert_chunks(&[create_test_chunk(
3489            Path::new("old.md"),
3490            "old",
3491            create_random_embedding(TEST_DIM),
3492            0,
3493        )])
3494        .await
3495        .unwrap();
3496        let new = LanceStore::new(path, TEST_DIM).with_embedding_model("model-b");
3497        let error = new.init().await.unwrap_err().to_string();
3498        assert!(
3499            error.contains("model-a") && error.contains("model-b") && error.contains("--force")
3500        );
3501        new.rebuild().await.unwrap();
3502        assert!(
3503            new.get_chunks_for_file(Path::new("old.md"))
3504                .await
3505                .unwrap()
3506                .is_empty()
3507        );
3508        let metadata = new.read_schema_sidecar().await.unwrap();
3509        assert_eq!(metadata.embedding_model.as_deref(), Some("model-b"));
3510        assert_eq!(metadata.embedding_dim, Some(TEST_DIM));
3511    }
3512
3513    #[tokio::test]
3514    async fn hybrid_finds_rows_inserted_after_empty_fts_creation() {
3515        let temp = tempdir().unwrap();
3516        let store = LanceStore::new(temp.path().join("test.lance"), TEST_DIM);
3517        store.init().await.unwrap();
3518        let embedding = create_random_embedding(TEST_DIM);
3519        store
3520            .upsert_chunks(&[create_test_chunk(
3521                Path::new("fresh.md"),
3522                "freshunique retrieval marker",
3523                embedding.clone(),
3524                0,
3525            )])
3526            .await
3527            .unwrap();
3528        let mut query = search_query(embedding, vec![], DistanceMetric::Cosine);
3529        query.text = Some("freshunique".into());
3530        let results = store.hybrid_search(query).await.unwrap();
3531        assert!(
3532            results
3533                .iter()
3534                .any(|hit| hit.file_path == Path::new("fresh.md"))
3535        );
3536        // Also assert the lexical leg itself, so vector fallback cannot mask stale FTS.
3537        let table = store.get_chunks_table().await.unwrap();
3538        let batches: Vec<RecordBatch> = table
3539            .query()
3540            .full_text_search(FullTextSearchQuery::new("freshunique".to_string()))
3541            .execute()
3542            .await
3543            .unwrap()
3544            .try_collect()
3545            .await
3546            .unwrap();
3547        assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 1);
3548    }
3549    #[tokio::test]
3550    async fn interrupted_rebuild_refuses_open_until_retried() {
3551        let temp = tempdir().unwrap();
3552        let store = LanceStore::new(temp.path().join("test.lance"), TEST_DIM)
3553            .with_embedding_model("model-a");
3554        store.init().await.unwrap();
3555        let mut metadata = store.read_schema_sidecar().await.unwrap();
3556        metadata.rebuild_in_progress = true;
3557        store.write_schema_sidecar(&metadata).await.unwrap();
3558        assert!(
3559            store
3560                .init()
3561                .await
3562                .unwrap_err()
3563                .to_string()
3564                .contains("--force")
3565        );
3566        store.rebuild().await.unwrap();
3567        assert!(
3568            !store
3569                .read_schema_sidecar()
3570                .await
3571                .unwrap()
3572                .rebuild_in_progress
3573        );
3574        store.init().await.unwrap();
3575    }
3576}