retrieval-kit 0.1.0

A Rust library for local document ingestion, vector search, keyword search, and MCP-style retrieval tool definitions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
use std::path::Path;
use std::sync::Arc;

use arrow_array::{
    Array, FixedSizeListArray, Float32Array, RecordBatch, RecordBatchIterator, StringArray,
    UInt64Array, cast::AsArray, types::Float32Type,
};
use arrow_schema::{DataType, Field, Schema};
use futures::TryStreamExt;
use lancedb::database::CreateTableMode;
use lancedb::index::scalar::FullTextSearchQuery;
use lancedb::index::{Index, scalar::FtsIndexBuilder};
use lancedb::query::{ExecutableQuery, QueryBase, Select};
use lancedb::{Connection, Error, Result, Table, connect};

const DOCUMENTS_TABLE_NAME: &str = "documents";
const CHUNKS_TABLE_NAME: &str = "chunks";
const MIN_VECTOR_INDEX_ROWS: usize = 256;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DocumentRecord {
    pub document_id: String,
    pub content: String,
}

pub struct Chunk {
    pub document_id: String,
    pub chunk_index: u64,
    pub text: String,
    pub vector: Vec<f32>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ChunkSearchRecord {
    pub document_id: String,
    pub text: String,
    pub distance: f32,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ChunkKeywordSearchRecord {
    pub document_id: String,
    pub text: String,
    pub score: f32,
}

pub struct LanceDbBackend {
    connection: Connection,
    vector_dimensions: i32,
}

impl LanceDbBackend {
    pub async fn new(path: impl AsRef<Path>, vector_dimensions: i32) -> Result<Self> {
        if vector_dimensions <= 0 {
            return Err(Error::InvalidInput {
                message: "vector_dimensions must be greater than zero".to_string(),
            });
        }

        let uri = path.as_ref().to_string_lossy();
        let connection = connect(uri.as_ref()).execute().await?;

        Ok(Self {
            connection,
            vector_dimensions,
        })
    }

    pub async fn create_tables(&self) -> Result<()> {
        self.create_documents_table().await?;
        self.create_chunks_table().await?;
        Ok(())
    }

    pub async fn create_documents_table(&self) -> Result<Table> {
        self.connection
            .create_empty_table(DOCUMENTS_TABLE_NAME, self.documents_schema())
            .mode(CreateTableMode::exist_ok(|request| request))
            .execute()
            .await
    }

    pub async fn create_chunks_table(&self) -> Result<Table> {
        self.connection
            .create_empty_table(CHUNKS_TABLE_NAME, self.chunks_schema())
            .mode(CreateTableMode::exist_ok(|request| request))
            .execute()
            .await
    }

    pub async fn insert_data(&self, documents: &[DocumentRecord], chunks: &[Chunk]) -> Result<()> {
        let documents_batch = self.documents_batch(documents)?;
        let chunks_batch = self.chunks_batch(chunks)?;

        let documents_table = self
            .connection
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await?;
        let chunks_table = self
            .connection
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await?;

        chunks_table.add(chunks_batch).execute().await?;
        if let Err(error) = documents_table.add(documents_batch).execute().await {
            self.delete_chunks_for_documents(&chunks_table, documents)
                .await;
            return Err(error);
        }
        self.ensure_chunks_indices(&chunks_table).await?;

        Ok(())
    }

    pub async fn upsert_data(&self, document: &DocumentRecord, chunks: &[Chunk]) -> Result<()> {
        let documents_batch = self.documents_batch(std::slice::from_ref(document))?;
        let chunks_batch = self.chunks_batch(chunks)?;
        let previous_chunks = self.chunks_for_document(&document.document_id).await?;
        let documents_table = self
            .connection
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await?;
        let chunks_table = self
            .connection
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await?;

        self.merge_replace_document_chunks(&chunks_table, &document.document_id, chunks_batch)
            .await?;
        if let Err(error) = self
            .merge_upsert_documents(&documents_table, documents_batch)
            .await
        {
            let _ = self
                .restore_document_chunks(&chunks_table, &document.document_id, previous_chunks)
                .await;
            return Err(error);
        }

        self.ensure_chunks_indices(&chunks_table).await?;

        Ok(())
    }

    pub async fn vector_search(
        &self,
        query_vector: Vec<f32>,
        limit: usize,
    ) -> Result<Vec<ChunkSearchRecord>> {
        let table = self
            .connection
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await?;
        let rows = table
            .query()
            .nearest_to(query_vector)?
            .column("vector")
            .limit(limit)
            .select(Select::columns(&["document_id", "text", "_distance"]))
            .execute()
            .await?;
        let batches = rows.try_collect::<Vec<_>>().await?;

        Ok(chunk_search_records_from_batches(&batches))
    }

    pub async fn keyword_search(
        &self,
        query: String,
        limit: usize,
    ) -> Result<Vec<ChunkKeywordSearchRecord>> {
        let table = self
            .connection
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await?;
        let full_text_query = FullTextSearchQuery::new(query).with_column("text".to_string())?;
        let rows = table
            .query()
            .full_text_search(full_text_query)
            .limit(limit)
            .select(Select::columns(&["document_id", "text", "_score"]))
            .execute()
            .await?;
        let batches = rows.try_collect::<Vec<_>>().await?;

        Ok(chunk_keyword_search_records_from_batches(&batches))
    }

    pub async fn list_documents(&self) -> Result<Vec<DocumentRecord>> {
        let table = self
            .connection
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await?;
        let rows = table
            .query()
            .select(Select::columns(&["document_id", "content"]))
            .execute()
            .await?;
        let batches = rows.try_collect::<Vec<_>>().await?;
        let mut documents = document_records_from_batches(&batches);

        documents.sort_by(|left, right| left.document_id.cmp(&right.document_id));
        Ok(documents)
    }

    pub async fn get_document(&self, document_id: &str) -> Result<Option<DocumentRecord>> {
        let table = self
            .connection
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await?;
        let rows = table
            .query()
            .only_if(document_id_predicate(document_id))
            .select(Select::columns(&["document_id", "content"]))
            .limit(1)
            .execute()
            .await?;
        let batches = rows.try_collect::<Vec<_>>().await?;

        Ok(document_records_from_batches(&batches).into_iter().next())
    }

    pub async fn delete_document(&self, document_id: &str) -> Result<()> {
        let predicate = document_id_predicate(document_id);
        let documents_table = self
            .connection
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await?;
        let chunks_table = self
            .connection
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await?;

        documents_table.delete(&predicate).await?;
        chunks_table.delete(&predicate).await?;

        Ok(())
    }

    pub fn connection(&self) -> &Connection {
        &self.connection
    }

    pub fn vector_dimensions(&self) -> i32 {
        self.vector_dimensions
    }

    async fn ensure_chunks_vector_index(&self, chunks_table: &Table) -> Result<()> {
        let indices = chunks_table.list_indices().await?;
        if indices
            .iter()
            .any(|index| index.columns == vec!["vector".to_string()])
        {
            return Ok(());
        }
        if chunks_table.count_rows(None).await? < MIN_VECTOR_INDEX_ROWS {
            return Ok(());
        }

        chunks_table
            .create_index(&["vector"], Index::Auto)
            .execute()
            .await?;
        Ok(())
    }

    async fn ensure_chunks_keyword_index(&self, chunks_table: &Table) -> Result<()> {
        let indices = chunks_table.list_indices().await?;
        if indices
            .iter()
            .any(|index| index.columns == vec!["text".to_string()])
        {
            return Ok(());
        }

        chunks_table
            .create_index(&["text"], Index::FTS(FtsIndexBuilder::default()))
            .execute()
            .await?;
        Ok(())
    }

    fn documents_schema(&self) -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("document_id", DataType::Utf8, false),
            Field::new("content", DataType::Utf8, false),
        ]))
    }

    fn chunks_schema(&self) -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("document_id", DataType::Utf8, false),
            Field::new("chunk_index", DataType::UInt64, false),
            Field::new("text", DataType::Utf8, false),
            Field::new(
                "vector",
                DataType::FixedSizeList(
                    Arc::new(Field::new("item", DataType::Float32, true)),
                    self.vector_dimensions,
                ),
                false,
            ),
        ]))
    }

    fn documents_batch(&self, data: &[DocumentRecord]) -> Result<RecordBatch> {
        let document_id_values = Arc::new(StringArray::from_iter_values(
            data.iter().map(|document| document.document_id.as_str()),
        ));
        let content_values = Arc::new(StringArray::from_iter_values(
            data.iter().map(|document| document.content.as_str()),
        ));

        Ok(RecordBatch::try_new(
            self.documents_schema(),
            vec![document_id_values, content_values],
        )?)
    }

    fn chunks_batch(&self, data: &[Chunk]) -> Result<RecordBatch> {
        let expected_dimensions = self.vector_dimensions as usize;
        for chunk in data {
            if chunk.vector.len() != expected_dimensions {
                return Err(Error::InvalidInput {
                    message: format!(
                        "chunk vector has dimension {}, expected {}",
                        chunk.vector.len(),
                        expected_dimensions
                    ),
                });
            }
        }

        let document_id_values = Arc::new(StringArray::from_iter_values(
            data.iter().map(|chunk| chunk.document_id.as_str()),
        ));
        let chunk_index_values = Arc::new(UInt64Array::from_iter_values(
            data.iter().map(|chunk| chunk.chunk_index),
        ));
        let text_values = Arc::new(StringArray::from_iter_values(
            data.iter().map(|chunk| chunk.text.as_str()),
        ));
        let vector_values = Arc::new(
            FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
                data.iter()
                    .map(|chunk| Some(chunk.vector.iter().copied().map(Some))),
                self.vector_dimensions,
            ),
        );

        Ok(RecordBatch::try_new(
            self.chunks_schema(),
            vec![
                document_id_values,
                chunk_index_values,
                text_values,
                vector_values,
            ],
        )?)
    }

    async fn merge_upsert_documents(&self, table: &Table, batch: RecordBatch) -> Result<()> {
        let mut merge = table.merge_insert(&["document_id"]);
        merge
            .when_matched_update_all(None)
            .when_not_matched_insert_all();
        merge.execute(record_batch_reader(batch)).await?;
        Ok(())
    }

    async fn merge_replace_document_chunks(
        &self,
        table: &Table,
        document_id: &str,
        batch: RecordBatch,
    ) -> Result<()> {
        let mut merge = table.merge_insert(&["document_id", "chunk_index"]);
        merge
            .when_matched_update_all(None)
            .when_not_matched_insert_all()
            .when_not_matched_by_source_delete(Some(document_id_predicate(document_id)));
        merge.execute(record_batch_reader(batch)).await?;
        Ok(())
    }

    async fn restore_document_chunks(
        &self,
        table: &Table,
        document_id: &str,
        chunks: Vec<Chunk>,
    ) -> Result<()> {
        if chunks.is_empty() {
            table.delete(&document_id_predicate(document_id)).await?;
            return Ok(());
        }

        let batch = self.chunks_batch(&chunks)?;
        self.merge_replace_document_chunks(table, document_id, batch)
            .await
    }

    async fn chunks_for_document(&self, document_id: &str) -> Result<Vec<Chunk>> {
        let table = self
            .connection
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await?;
        let rows = table
            .query()
            .only_if(document_id_predicate(document_id))
            .select(Select::columns(&[
                "document_id",
                "chunk_index",
                "text",
                "vector",
            ]))
            .execute()
            .await?;
        let batches = rows.try_collect::<Vec<_>>().await?;

        Ok(chunks_from_batches(&batches))
    }

    async fn delete_chunks_for_documents(&self, table: &Table, documents: &[DocumentRecord]) {
        for document in documents {
            let _ = table
                .delete(&document_id_predicate(&document.document_id))
                .await;
        }
    }

    async fn ensure_chunks_indices(&self, chunks_table: &Table) -> Result<()> {
        self.ensure_chunks_vector_index(chunks_table).await?;
        self.ensure_chunks_keyword_index(chunks_table).await
    }
}

fn record_batch_reader(batch: RecordBatch) -> Box<dyn arrow_array::RecordBatchReader + Send> {
    let schema = batch.schema();
    Box::new(RecordBatchIterator::new(
        vec![Ok(batch)].into_iter(),
        schema,
    ))
}

fn document_records_from_batches(batches: &[RecordBatch]) -> Vec<DocumentRecord> {
    batches
        .iter()
        .flat_map(|batch| {
            let document_ids = batch
                .column_by_name("document_id")
                .expect("documents query should include document_id")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("document_id column should be Utf8");
            let contents = batch
                .column_by_name("content")
                .expect("documents query should include content")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("content column should be Utf8");

            (0..batch.num_rows())
                .map(|index| DocumentRecord {
                    document_id: document_ids.value(index).to_string(),
                    content: contents.value(index).to_string(),
                })
                .collect::<Vec<_>>()
        })
        .collect()
}

fn chunk_search_records_from_batches(batches: &[RecordBatch]) -> Vec<ChunkSearchRecord> {
    batches
        .iter()
        .flat_map(|batch| {
            let document_ids = batch
                .column_by_name("document_id")
                .expect("chunks query should include document_id")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("document_id column should be Utf8");
            let texts = batch
                .column_by_name("text")
                .expect("chunks query should include text")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("text column should be Utf8");
            let distances = batch
                .column_by_name("_distance")
                .expect("chunks query should include _distance")
                .as_primitive::<Float32Type>();

            (0..batch.num_rows())
                .map(|index| ChunkSearchRecord {
                    document_id: document_ids.value(index).to_string(),
                    text: texts.value(index).to_string(),
                    distance: distances.value(index),
                })
                .collect::<Vec<_>>()
        })
        .collect()
}

fn chunk_keyword_search_records_from_batches(
    batches: &[RecordBatch],
) -> Vec<ChunkKeywordSearchRecord> {
    batches
        .iter()
        .flat_map(|batch| {
            let document_ids = batch
                .column_by_name("document_id")
                .expect("chunks query should include document_id")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("document_id column should be Utf8");
            let texts = batch
                .column_by_name("text")
                .expect("chunks query should include text")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("text column should be Utf8");
            let scores = batch
                .column_by_name("_score")
                .expect("chunks query should include _score")
                .as_primitive::<Float32Type>();

            (0..batch.num_rows())
                .map(|index| ChunkKeywordSearchRecord {
                    document_id: document_ids.value(index).to_string(),
                    text: texts.value(index).to_string(),
                    score: scores.value(index),
                })
                .collect::<Vec<_>>()
        })
        .collect()
}

fn chunks_from_batches(batches: &[RecordBatch]) -> Vec<Chunk> {
    batches
        .iter()
        .flat_map(|batch| {
            let document_ids = batch
                .column_by_name("document_id")
                .expect("chunks query should include document_id")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("document_id column should be Utf8");
            let chunk_indices = batch
                .column_by_name("chunk_index")
                .expect("chunks query should include chunk_index")
                .as_any()
                .downcast_ref::<UInt64Array>()
                .expect("chunk_index column should be UInt64");
            let texts = batch
                .column_by_name("text")
                .expect("chunks query should include text")
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("text column should be Utf8");
            let vectors = batch
                .column_by_name("vector")
                .expect("chunks query should include vector")
                .as_any()
                .downcast_ref::<FixedSizeListArray>()
                .expect("vector column should be FixedSizeList");

            (0..batch.num_rows())
                .map(|index| Chunk {
                    document_id: document_ids.value(index).to_string(),
                    chunk_index: chunk_indices.value(index),
                    text: texts.value(index).to_string(),
                    vector: vectors
                        .value(index)
                        .as_any()
                        .downcast_ref::<Float32Array>()
                        .expect("vector item column should be Float32")
                        .values()
                        .to_vec(),
                })
                .collect::<Vec<_>>()
        })
        .collect()
}

fn document_id_predicate(document_id: &str) -> String {
    format!("document_id = '{}'", document_id.replace('\'', "''"))
}

#[cfg(test)]
mod tests {
    use super::{CHUNKS_TABLE_NAME, Chunk, DOCUMENTS_TABLE_NAME, DocumentRecord, LanceDbBackend};
    use arrow_array::StringArray;
    use futures::TryStreamExt;
    use lancedb::Error;
    use lancedb::query::ExecutableQuery;

    fn demo_document() -> DocumentRecord {
        DocumentRecord {
            document_id: "demo-doc".to_string(),
            content: "knight ranger priest rogue".to_string(),
        }
    }

    fn demo_chunks() -> Vec<Chunk> {
        vec![
            Chunk {
                document_id: "demo-doc".to_string(),
                chunk_index: 0,
                text: "knight".to_string(),
                vector: vec![0.9, 0.4, 0.8],
            },
            Chunk {
                document_id: "demo-doc".to_string(),
                chunk_index: 1,
                text: "ranger".to_string(),
                vector: vec![0.8, 0.4, 0.7],
            },
            Chunk {
                document_id: "demo-doc".to_string(),
                chunk_index: 2,
                text: "priest".to_string(),
                vector: vec![0.6, 0.2, 0.6],
            },
            Chunk {
                document_id: "demo-doc".to_string(),
                chunk_index: 3,
                text: "rogue".to_string(),
                vector: vec![0.7, 0.4, 0.7],
            },
        ]
    }

    fn five_dimensional_chunks() -> Vec<Chunk> {
        vec![
            Chunk {
                document_id: "five-dim-doc".to_string(),
                chunk_index: 0,
                text: "mage".to_string(),
                vector: vec![0.1, 0.2, 0.3, 0.4, 0.5],
            },
            Chunk {
                document_id: "five-dim-doc".to_string(),
                chunk_index: 1,
                text: "paladin".to_string(),
                vector: vec![0.5, 0.4, 0.3, 0.2, 0.1],
            },
        ]
    }

    #[tokio::test]
    async fn initializes_lancedb_from_local_path() {
        let temp_dir = tempfile::tempdir().unwrap();

        let backend = LanceDbBackend::new(temp_dir.path(), 3).await;

        assert!(backend.is_ok());
    }

    #[tokio::test]
    async fn creates_empty_tables() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 5).await.unwrap();

        backend.create_tables().await.unwrap();

        assert_eq!(backend.vector_dimensions(), 5);
        let documents_table = backend
            .connection()
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        let chunks_table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(documents_table.count_rows(None).await.unwrap(), 0);
        assert_eq!(chunks_table.count_rows(None).await.unwrap(), 0);
    }

    #[tokio::test]
    async fn inserts_demo_rows_into_tables() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();

        let documents_table = backend
            .connection()
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        let chunks_table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(documents_table.count_rows(None).await.unwrap(), 1);
        assert_eq!(chunks_table.count_rows(None).await.unwrap(), 4);
    }

    #[tokio::test]
    async fn create_tables_is_idempotent() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();
        backend.create_tables().await.unwrap();

        let chunks_table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(chunks_table.count_rows(None).await.unwrap(), 4);
    }

    #[tokio::test]
    async fn inserts_matching_non_default_dimensions() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 5).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(
                &[DocumentRecord {
                    document_id: "five-dim-doc".to_string(),
                    content: "mage paladin".to_string(),
                }],
                &five_dimensional_chunks(),
            )
            .await
            .unwrap();

        let chunks_table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(chunks_table.count_rows(None).await.unwrap(), 2);
    }

    #[tokio::test]
    async fn rejects_mismatched_vector_dimensions() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 5).await.unwrap();

        backend.create_tables().await.unwrap();
        let error = backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap_err();

        assert!(matches!(error, Error::InvalidInput { .. }));
    }

    #[tokio::test]
    async fn vector_search_returns_ranked_chunk_records() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();

        let results = backend.vector_search(vec![0.9, 0.4, 0.8], 2).await.unwrap();

        assert_eq!(results.len(), 2);
        assert_eq!(results[0].document_id, "demo-doc");
        assert_eq!(results[0].text, "knight");
        assert_eq!(results[0].distance, 0.0);
    }

    #[tokio::test]
    async fn keyword_search_returns_ranked_chunk_records() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(
                &[DocumentRecord {
                    document_id: "search-doc".to_string(),
                    content: "rust database rust search ranger".to_string(),
                }],
                &[
                    Chunk {
                        document_id: "search-doc".to_string(),
                        chunk_index: 0,
                        text: "rust database rust search".to_string(),
                        vector: vec![0.1, 0.2, 0.3],
                    },
                    Chunk {
                        document_id: "search-doc".to_string(),
                        chunk_index: 1,
                        text: "ranger path".to_string(),
                        vector: vec![0.4, 0.5, 0.6],
                    },
                ],
            )
            .await
            .unwrap();

        let results = backend.keyword_search("rust".to_string(), 1).await.unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].document_id, "search-doc");
        assert_eq!(results[0].text, "rust database rust search");
        assert!(results[0].score > 0.0);
    }

    #[tokio::test]
    async fn keyword_search_returns_empty_for_missing_terms() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();

        let results = backend
            .keyword_search("warlock".to_string(), 10)
            .await
            .unwrap();

        assert!(results.is_empty());
    }

    #[tokio::test]
    async fn upsert_replaces_rows_for_document_id() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();
        backend
            .upsert_data(
                &DocumentRecord {
                    document_id: "demo-doc".to_string(),
                    content: "replacement next".to_string(),
                },
                &[
                    Chunk {
                        document_id: "demo-doc".to_string(),
                        chunk_index: 0,
                        text: "replacement".to_string(),
                        vector: vec![0.1, 0.2, 0.3],
                    },
                    Chunk {
                        document_id: "demo-doc".to_string(),
                        chunk_index: 1,
                        text: "next".to_string(),
                        vector: vec![0.4, 0.5, 0.6],
                    },
                ],
            )
            .await
            .unwrap();

        let table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(table.count_rows(None).await.unwrap(), 2);

        let rows = table.query().execute().await.unwrap();
        let batches = rows.try_collect::<Vec<_>>().await.unwrap();
        let texts = batches
            .iter()
            .flat_map(|batch| {
                batch
                    .column_by_name("text")
                    .unwrap()
                    .as_any()
                    .downcast_ref::<StringArray>()
                    .unwrap()
                    .iter()
                    .flatten()
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();

        assert_eq!(texts, vec!["replacement".to_string(), "next".to_string()]);
        assert_eq!(
            backend.get_document("demo-doc").await.unwrap(),
            Some(DocumentRecord {
                document_id: "demo-doc".to_string(),
                content: "replacement next".to_string(),
            })
        );
    }

    #[tokio::test]
    async fn upsert_preserves_repeated_chunk_text_by_index() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();
        backend
            .upsert_data(
                &DocumentRecord {
                    document_id: "demo-doc".to_string(),
                    content: "repeat repeat".to_string(),
                },
                &[
                    Chunk {
                        document_id: "demo-doc".to_string(),
                        chunk_index: 0,
                        text: "repeat".to_string(),
                        vector: vec![0.1, 0.2, 0.3],
                    },
                    Chunk {
                        document_id: "demo-doc".to_string(),
                        chunk_index: 1,
                        text: "repeat".to_string(),
                        vector: vec![0.4, 0.5, 0.6],
                    },
                ],
            )
            .await
            .unwrap();

        let table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        let rows = table.query().execute().await.unwrap();
        let batches = rows.try_collect::<Vec<_>>().await.unwrap();
        let texts = batches
            .iter()
            .flat_map(|batch| {
                batch
                    .column_by_name("text")
                    .unwrap()
                    .as_any()
                    .downcast_ref::<StringArray>()
                    .unwrap()
                    .iter()
                    .flatten()
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();

        assert_eq!(texts, vec!["repeat".to_string(), "repeat".to_string()]);
    }

    #[tokio::test]
    async fn upsert_escapes_document_id_predicate() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(
                &[DocumentRecord {
                    document_id: "doc-'quoted'".to_string(),
                    content: "old".to_string(),
                }],
                &[Chunk {
                    document_id: "doc-'quoted'".to_string(),
                    chunk_index: 0,
                    text: "old".to_string(),
                    vector: vec![0.1, 0.2, 0.3],
                }],
            )
            .await
            .unwrap();
        backend
            .upsert_data(
                &DocumentRecord {
                    document_id: "doc-'quoted'".to_string(),
                    content: "new".to_string(),
                },
                &[Chunk {
                    document_id: "doc-'quoted'".to_string(),
                    chunk_index: 0,
                    text: "new".to_string(),
                    vector: vec![0.4, 0.5, 0.6],
                }],
            )
            .await
            .unwrap();

        let table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(table.count_rows(None).await.unwrap(), 1);
        assert_eq!(
            backend.get_document("doc-'quoted'").await.unwrap(),
            Some(DocumentRecord {
                document_id: "doc-'quoted'".to_string(),
                content: "new".to_string(),
            })
        );
    }

    #[tokio::test]
    async fn lists_documents_sorted_by_document_id() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(
                &[
                    DocumentRecord {
                        document_id: "b-doc".to_string(),
                        content: "second".to_string(),
                    },
                    DocumentRecord {
                        document_id: "a-doc".to_string(),
                        content: "first".to_string(),
                    },
                ],
                &[
                    Chunk {
                        document_id: "b-doc".to_string(),
                        chunk_index: 0,
                        text: "second".to_string(),
                        vector: vec![0.1, 0.2, 0.3],
                    },
                    Chunk {
                        document_id: "a-doc".to_string(),
                        chunk_index: 0,
                        text: "first".to_string(),
                        vector: vec![0.4, 0.5, 0.6],
                    },
                ],
            )
            .await
            .unwrap();

        let documents = backend.list_documents().await.unwrap();

        assert_eq!(
            documents,
            vec![
                DocumentRecord {
                    document_id: "a-doc".to_string(),
                    content: "first".to_string(),
                },
                DocumentRecord {
                    document_id: "b-doc".to_string(),
                    content: "second".to_string(),
                },
            ]
        );
    }

    #[tokio::test]
    async fn delete_document_removes_document_and_chunks() {
        let temp_dir = tempfile::tempdir().unwrap();
        let backend = LanceDbBackend::new(temp_dir.path(), 3).await.unwrap();

        backend.create_tables().await.unwrap();
        backend
            .insert_data(&[demo_document()], &demo_chunks())
            .await
            .unwrap();

        backend.delete_document("demo-doc").await.unwrap();

        let documents_table = backend
            .connection()
            .open_table(DOCUMENTS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        let chunks_table = backend
            .connection()
            .open_table(CHUNKS_TABLE_NAME)
            .execute()
            .await
            .unwrap();
        assert_eq!(documents_table.count_rows(None).await.unwrap(), 0);
        assert_eq!(chunks_table.count_rows(None).await.unwrap(), 0);
    }
}