semquery-storage 0.4.0

SQLite-backed storage implementation for semquery.
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
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex, Once};

use chrono::{DateTime, Utc};
use rusqlite::ffi::sqlite3_auto_extension;
use rusqlite::{Connection, OptionalExtension, params, params_from_iter};
use semquery_core::{Chunk, Collection, Document, ModelRole, ModelSpec, Result, Storage, StorageTx, StoreError};
use sqlite_vec::sqlite3_vec_init;

use crate::error::map_rusqlite;

static VEC_EXT_LOADED: Once = Once::new();

fn ensure_vec_extension() {
  VEC_EXT_LOADED.call_once(|| unsafe {
    sqlite3_auto_extension(Some(std::mem::transmute::<
      *const (),
      unsafe extern "C" fn(
        *mut rusqlite::ffi::sqlite3,
        *mut *mut i8,
        *const rusqlite::ffi::sqlite3_api_routines,
      ) -> i32,
    >(sqlite3_vec_init as *const ())));
  });
}

fn embedding_to_bytes(vec: &[f32]) -> Vec<u8> {
  let mut bytes = Vec::with_capacity(vec.len() * 4);
  for &f in vec {
    bytes.extend_from_slice(&f.to_le_bytes());
  }
  bytes
}

pub struct SqliteStorage {
  conn: Arc<Mutex<Connection>>,
}

const DB_FILE_NAME: &str = "semq.db";

impl SqliteStorage {
  pub fn open(path: impl AsRef<Path>) -> Result<Self> {
    ensure_vec_extension();
    let conn = Connection::open(path).map_err(map_rusqlite)?;
    conn
      .execute_batch(
        "PRAGMA busy_timeout = 5000; \
         PRAGMA foreign_keys = ON; \
         PRAGMA journal_mode = WAL; \
         PRAGMA synchronous = NORMAL; \
         PRAGMA cache_size = -64000;",
      )
      .map_err(map_rusqlite)?;
    Ok(Self {
      conn: Arc::new(Mutex::new(conn)),
    })
  }

  pub fn open_in_memory() -> Result<Self> {
    ensure_vec_extension();
    let conn = Connection::open_in_memory().map_err(map_rusqlite)?;
    conn
      .execute_batch(
        "PRAGMA busy_timeout = 5000; \
       PRAGMA foreign_keys = ON; \
       PRAGMA synchronous = NORMAL; \
       PRAGMA cache_size = -64000;",
      )
      .map_err(map_rusqlite)?;
    Ok(Self {
      conn: Arc::new(Mutex::new(conn)),
    })
  }

  /// Open the default SQLite database inside a workspace directory.
  /// Keeps the concrete filename (`semq.db`) encapsulated in the storage crate
  /// so callers don't assume SQLite implementation details.
  pub fn open_workspace(workspace: impl AsRef<Path>) -> Result<Self> {
    let path = workspace.as_ref().join(DB_FILE_NAME);
    Self::open(path)
  }

  fn init_vectors(&self, conn: &Connection, dimension: usize) -> Result<()> {
    let expected_type = format!("FLOAT[{dimension}]");

    let existing_sql: Option<String> = conn
      .query_row(
        "SELECT sql FROM sqlite_master WHERE type='table' AND name='vec_chunks'",
        [],
        |r| r.get(0),
      )
      .optional()
      .map_err(map_rusqlite)?;

    if let Some(sql) = existing_sql {
      if !sql.contains(&expected_type) {
        return Err(
          StoreError::SchemaMismatch {
            expected: expected_type,
          }
          .into(),
        );
      }
      return Ok(());
    }

    let sql = format!(
      "CREATE VIRTUAL TABLE IF NOT EXISTS vec_chunks USING vec0(
         chunk_id  TEXT PRIMARY KEY,
         embedding {expected_type} distance_metric=cosine
       );"
    );
    conn.execute_batch(&sql).map_err(map_rusqlite)?;
    Ok(())
  }
}

fn poisoned() -> StoreError {
  StoreError::MutexPoisoned
}

fn insert_document(conn: &Connection, doc: &Document) -> rusqlite::Result<()> {
  conn.execute(
    "INSERT OR REPLACE INTO documents
     (doc_id, content_hash, content_size, indexed_at)
   VALUES (?1, ?2, ?3, ?4)",
    params![
      doc.id,
      doc.content_hash,
      doc.content_size as i64,
      doc.indexed_at.to_rfc3339(),
    ],
  )?;
  Ok(())
}

fn insert_chunks(conn: &Connection, chunks: &[Chunk]) -> rusqlite::Result<()> {
  let mut stmt = conn.prepare(
    "INSERT OR IGNORE INTO chunks (chunk_id, text, start_byte, end_byte)
     VALUES (?1, ?2, ?3, ?4)",
  )?;
  for chunk in chunks {
    stmt.execute(params![
      chunk.id,
      chunk.text,
      chunk.byte_range.start as i64,
      chunk.byte_range.end as i64,
    ])?;
  }
  Ok(())
}

fn insert_chunk_documents(conn: &Connection, chunk_ids: &[String], doc_id: &str) -> rusqlite::Result<()> {
  let mut stmt = conn.prepare("INSERT OR IGNORE INTO chunk_documents (chunk_id, doc_id) VALUES (?1, ?2)")?;
  for cid in chunk_ids {
    stmt.execute(params![cid, doc_id])?;
  }
  Ok(())
}

fn insert_vectors(conn: &Connection, chunk_ids: &[String], embeddings: &[Vec<f32>]) -> rusqlite::Result<()> {
  let mut stmt = conn.prepare("INSERT OR REPLACE INTO vec_chunks (chunk_id, embedding) VALUES (?1, ?2)")?;
  for (id, emb) in chunk_ids.iter().zip(embeddings.iter()) {
    let bytes = embedding_to_bytes(emb);
    stmt.execute(params![id, bytes])?;
  }
  Ok(())
}

fn insert_fts(conn: &Connection, chunk_ids: &[String], tokenized_texts: &[String]) -> rusqlite::Result<()> {
  let mut stmt = conn.prepare("INSERT OR REPLACE INTO fts_chunks (chunk_id, text) VALUES (?1, ?2)")?;
  for (id, text) in chunk_ids.iter().zip(tokenized_texts.iter()) {
    stmt.execute(params![id, text])?;
  }
  Ok(())
}

fn insert_document_path(conn: &Connection, doc_id: &str, path: &str) -> rusqlite::Result<()> {
  conn.execute(
    "INSERT OR REPLACE INTO document_paths (doc_id, file_path) VALUES (?1, ?2)",
    params![doc_id, path],
  )?;
  Ok(())
}

fn delete_document(conn: &Connection, doc_id: &str) -> rusqlite::Result<()> {
  conn.execute("DELETE FROM document_paths WHERE doc_id = ?1", params![doc_id])?;
  conn.execute("DELETE FROM documents WHERE doc_id = ?1", params![doc_id])?;
  Ok(())
}

fn delete_chunks_by_doc(conn: &Connection, doc_id: &str) -> rusqlite::Result<()> {
  conn.execute("DELETE FROM chunk_documents WHERE doc_id = ?1", params![doc_id])?;

  let orphaned = "chunk_id NOT IN (SELECT chunk_id FROM chunk_documents)";
  conn.execute(
    &format!("DELETE FROM vec_chunks WHERE chunk_id IN (SELECT chunk_id FROM chunks WHERE {orphaned})"),
    [],
  )?;
  conn.execute(
    &format!("DELETE FROM fts_chunks WHERE chunk_id IN (SELECT chunk_id FROM chunks WHERE {orphaned})"),
    [],
  )?;
  conn.execute(&format!("DELETE FROM chunks WHERE {orphaned}"), [])?;
  Ok(())
}

fn set_model_version(conn: &Connection, role: ModelRole, version: &ModelSpec) -> rusqlite::Result<()> {
  conn.execute(
    "INSERT OR REPLACE INTO model_versions (role, repo_id, filename, revision, checksum)
     VALUES (?1, ?2, ?3, ?4, ?5)",
    params![
      role.as_str(),
      version.repo_id,
      version.filename,
      version.revision,
      version.checksum
    ],
  )?;
  Ok(())
}

impl Storage for SqliteStorage {
  fn init(&self, vector_dimension: usize) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn
      .execute_batch(
        "CREATE TABLE IF NOT EXISTS documents (
         -- Indexed file; one row per .txt/.md added via `semq add`.
         -- `doc_id` is a stable identifier derived from the file path.
         doc_id       TEXT PRIMARY KEY,  -- stable document identifier
         content_hash TEXT NOT NULL,     -- SHA-256 of file bytes; drives incremental reindex
         content_size INTEGER NOT NULL,  -- byte length of the original file
         indexed_at   TEXT NOT NULL      -- RFC3339 UTC timestamp of last successful index
       );
       CREATE TABLE IF NOT EXISTS document_paths (
         -- Separates the mutable file system path from the stable document id.
         doc_id     TEXT PRIMARY KEY,
         file_path  TEXT NOT NULL UNIQUE,
         FOREIGN KEY (doc_id) REFERENCES documents(doc_id) ON DELETE CASCADE
       );
       CREATE TABLE IF NOT EXISTS chunks (
          -- Text block produced by the Chunker; `text` is the exact string embedded.
          -- chunk_id is the SHA-256 of `text`, so identical content is stored once.
          -- Parallel `vec_chunks` (sqlite-vec) and `fts_chunks` (FTS5) tables
          -- are keyed by the same chunk_id.
          -- doc_id is NOT stored here — the many-to-many mapping lives in
          -- `chunk_documents` so a shared chunk can belong to multiple files
          -- without one overwriting the other.
          chunk_id   TEXT PRIMARY KEY,  -- SHA-256 of `text`; content-addressed dedup
          text       TEXT NOT NULL,     -- full original text actually embedded
          start_byte INTEGER NOT NULL,  -- byte offset in the source file (inclusive)
          end_byte   INTEGER NOT NULL  -- byte offset in the source file (exclusive)
        );
        CREATE TABLE IF NOT EXISTS chunk_documents (
          -- Many-to-many junction: a chunk (identified by its text hash) can
          -- appear in multiple documents. This table records every (chunk, doc)
          -- pair so that deleting one document does not clobber the doc_id of
          -- a chunk still referenced by another document.
          chunk_id  TEXT NOT NULL,
          doc_id    TEXT NOT NULL,
          PRIMARY KEY (chunk_id, doc_id),
          FOREIGN KEY (chunk_id) REFERENCES chunks(chunk_id) ON DELETE CASCADE,
          FOREIGN KEY (doc_id) REFERENCES documents(doc_id) ON DELETE CASCADE
        );
       CREATE TABLE IF NOT EXISTS model_versions (
         -- Records which model produced the current embeddings / rerank scores / chat answers.
         -- On embedding-model upgrade the stored vectors become stale; the indexer compares
         -- the stored spec here against the live one and triggers an explicit reindex
         -- rather than serving silently-mismatched vectors.
         role     TEXT PRIMARY KEY,   -- 'embedding' / 'reranker' / 'chat'
         repo_id  TEXT NOT NULL,      -- HuggingFace repo id, e.g. 'BAAI/bge-small-zh-v1.5'
         filename TEXT NOT NULL,      -- on-disk artifact filename (.onnx / .gguf)
         revision TEXT NOT NULL,      -- HuggingFace revision or commit hash
         checksum TEXT                -- optional content checksum for verifying downloads
       );
        CREATE VIRTUAL TABLE IF NOT EXISTS fts_chunks USING fts5(
          -- FTS5 full-text index over jieba-pre-tokenised text.
          -- `text` here stores space-separated tokens (jieba output), NOT the raw chunk text.
          -- Raw text lives in `chunks.text`; this table only serves BM25 ranking.
          -- `unicode61` splits on the spaces between tokens, treating each jieba word as a term.
          chunk_id,
          text,
          tokenize='unicode61'
        );
        CREATE TABLE IF NOT EXISTS collections (
          name TEXT PRIMARY KEY,
          path TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS meta (
          key   TEXT PRIMARY KEY,
          value TEXT NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_chunk_documents_doc_id ON chunk_documents(doc_id);",
      )
      .map_err(map_rusqlite)?;
    if vector_dimension == 0 {
      return Ok(());
    }
    self.init_vectors(&conn, vector_dimension)
  }

  fn get_document(&self, doc_id: &str) -> Result<Option<Document>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let row = conn
      .query_row(
        "SELECT doc_id, content_hash, content_size, indexed_at
       FROM documents WHERE doc_id = ?1",
        params![doc_id],
        |r| {
          Ok((
            r.get::<_, String>(0)?,
            r.get::<_, String>(1)?,
            r.get::<_, i64>(2)?,
            r.get::<_, String>(3)?,
          ))
        },
      )
      .optional()
      .map_err(map_rusqlite)?;

    match row {
      Some((id, content_hash, content_size, ts)) => {
        let indexed_at = DateTime::parse_from_rfc3339(&ts)
          .map_err(|e| StoreError::InvalidTimestamp(e.to_string()))?
          .with_timezone(&Utc);
        Ok(Some(Document {
          id,
          content_hash,
          content_size: content_size as usize,
          indexed_at,
        }))
      }
      None => Ok(None),
    }
  }

  fn list_documents(&self) -> Result<Vec<Document>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let mut stmt = conn
      .prepare("SELECT doc_id, content_hash, content_size, indexed_at FROM documents")
      .map_err(map_rusqlite)?;

    let rows: Vec<(String, String, i64, String)> = stmt
      .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
      .map_err(map_rusqlite)?
      .collect::<rusqlite::Result<Vec<_>>>()
      .map_err(map_rusqlite)?;

    let docs = rows
      .into_iter()
      .map(|(id, content_hash, content_size, ts)| {
        let indexed_at = DateTime::parse_from_rfc3339(&ts)
          .map_err(|e| StoreError::InvalidTimestamp(e.to_string()))?
          .with_timezone(&Utc);
        Ok(Document {
          id,
          content_hash,
          content_size: content_size as usize,
          indexed_at,
        })
      })
      .collect::<Result<Vec<_>>>()?;
    Ok(docs)
  }

  fn get_document_paths(&self, doc_ids: &[String]) -> Result<HashMap<String, String>> {
    if doc_ids.is_empty() {
      return Ok(HashMap::new());
    }
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let placeholders = (0..doc_ids.len()).map(|_| "?").collect::<Vec<_>>().join(",");
    let sql = format!(
      "SELECT doc_id, file_path FROM document_paths WHERE doc_id IN ({})",
      placeholders
    );
    let mut stmt = conn.prepare(&sql).map_err(map_rusqlite)?;
    let rows = stmt
      .query_map(params_from_iter(doc_ids.iter()), |r| {
        Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
      })
      .map_err(map_rusqlite)?
      .collect::<rusqlite::Result<Vec<_>>>()
      .map_err(map_rusqlite)?;
    Ok(rows.into_iter().collect())
  }

  fn get_chunks(&self, chunk_ids: &[String]) -> Result<Vec<Chunk>> {
    if chunk_ids.is_empty() {
      return Ok(Vec::new());
    }
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let placeholders = (0..chunk_ids.len()).map(|_| "?").collect::<Vec<_>>().join(",");
    let sql = format!(
      "SELECT c.chunk_id, (
         SELECT cd.doc_id FROM chunk_documents cd
         WHERE cd.chunk_id = c.chunk_id
         ORDER BY cd.doc_id LIMIT 1
       ) AS doc_id, c.text, c.start_byte, c.end_byte
       FROM chunks c
       WHERE c.chunk_id IN ({})",
      placeholders
    );
    let mut stmt = conn.prepare(&sql).map_err(map_rusqlite)?;
    let rows = stmt
      .query_map(params_from_iter(chunk_ids.iter()), |r| {
        Ok((
          r.get::<_, String>(0)?,
          r.get::<_, Option<String>>(1)?,
          r.get::<_, String>(2)?,
          r.get::<_, i64>(3)?,
          r.get::<_, i64>(4)?,
        ))
      })
      .map_err(map_rusqlite)?
      .collect::<rusqlite::Result<Vec<_>>>()
      .map_err(map_rusqlite)?;

    let chunks = rows
      .into_iter()
      .map(|(id, doc_id, text, start, end)| Chunk {
        id,
        doc_id: doc_id.unwrap_or_default(),
        text,
        byte_range: start as usize..end as usize,
      })
      .collect();
    Ok(chunks)
  }

  fn search_vectors(&self, embedding: &[f32], top_k: usize) -> Result<Vec<(String, f32)>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let bytes = embedding_to_bytes(embedding);
    let mut stmt = conn
      .prepare(
        "SELECT chunk_id, distance
         FROM vec_chunks
         WHERE embedding MATCH ?1 AND k = ?2
         ORDER BY distance",
      )
      .map_err(map_rusqlite)?;
    // sqlite-vec returns cosine distance (0 = identical, 2 = opposite).
    // Convert to similarity (1.0 = identical, -1.0 = opposite) so all
    // channels follow the "higher is better" convention uniformly.
    let rows = stmt
      .query_map(params![bytes, top_k as i64], |r| {
        let distance: f32 = r.get(1)?;
        Ok((r.get::<_, String>(0)?, 1.0 - distance))
      })
      .map_err(map_rusqlite)?
      .collect::<rusqlite::Result<Vec<_>>>()
      .map_err(map_rusqlite)?;
    Ok(rows)
  }

  fn search_text(&self, query: &str, top_k: usize) -> Result<Vec<(String, f32)>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let mut stmt = conn
      .prepare(
        "SELECT chunk_id, bm25(fts_chunks) AS score
         FROM fts_chunks
         WHERE fts_chunks MATCH ?1
         ORDER BY rank
         LIMIT ?2",
      )
      .map_err(map_rusqlite)?;
    // FTS5 bm25() returns negative scores (0 = best, more negative = worse).
    // Negate so higher = more relevant, matching the convention of all other channels.
    let rows = stmt
      .query_map(params![query, top_k as i64], |r| {
        let raw: f32 = r.get(1)?;
        Ok((r.get::<_, String>(0)?, -raw))
      })
      .map_err(map_rusqlite)?
      .collect::<rusqlite::Result<Vec<_>>>()
      .map_err(map_rusqlite)?;
    Ok(rows)
  }

  fn get_model_version(&self, role: ModelRole) -> Result<Option<ModelSpec>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let row = conn
      .query_row(
        "SELECT repo_id, filename, revision, checksum FROM model_versions WHERE role = ?1",
        params![role.as_str()],
        |r| {
          Ok((
            r.get::<_, String>(0)?,
            r.get::<_, String>(1)?,
            r.get::<_, String>(2)?,
            r.get::<_, Option<String>>(3)?,
          ))
        },
      )
      .optional()
      .map_err(map_rusqlite)?;

    match row {
      Some((repo_id, filename, revision, checksum)) => Ok(Some(ModelSpec {
        role,
        repo_id,
        filename,
        revision,
        checksum,
      })),
      None => Ok(None),
    }
  }

  fn list_collections(&self) -> Result<Vec<Collection>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let mut stmt = conn.prepare("SELECT name, path FROM collections").map_err(map_rusqlite)?;
    let rows = stmt
      .query_map([], |r| {
        Ok(Collection {
          name: r.get(0)?,
          path: r.get::<_, String>(1)?.into(),
        })
      })
      .map_err(map_rusqlite)?
      .collect::<rusqlite::Result<Vec<_>>>()
      .map_err(map_rusqlite)?;
    Ok(rows)
  }

  fn count_chunks(&self) -> Result<usize> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let count: i64 = conn.query_row("SELECT COUNT(*) FROM chunks", [], |r| r.get(0)).map_err(map_rusqlite)?;
    Ok(count as usize)
  }

  fn set_model_version_atomic(&self, role: ModelRole, version: &ModelSpec) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    set_model_version(&conn, role, version).map_err(map_rusqlite)?;
    Ok(())
  }

  fn get_meta(&self, key: &str) -> Result<Option<String>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    let value: Option<String> = conn
      .query_row("SELECT value FROM meta WHERE key = ?1", params![key], |r| r.get(0))
      .optional()
      .map_err(map_rusqlite)?;
    Ok(value)
  }

  fn set_meta_atomic(&self, key: &str, value: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn
      .execute(
        "INSERT OR REPLACE INTO meta (key, value) VALUES (?1, ?2)",
        params![key, value],
      )
      .map_err(map_rusqlite)?;
    Ok(())
  }

  fn begin_tx(&self) -> Result<Box<dyn StorageTx + '_>> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn.execute_batch("BEGIN").map_err(map_rusqlite)?;
    Ok(Box::new(SqliteTransaction {
      conn: self.conn.clone(),
      committed: false,
    }))
  }
}

pub struct SqliteTransaction {
  conn: Arc<Mutex<Connection>>,
  committed: bool,
}

impl StorageTx for SqliteTransaction {
  fn add_document(&mut self, doc: &Document) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    insert_document(&conn, doc).map_err(map_rusqlite)?;
    Ok(())
  }

  fn set_document_path(&mut self, doc_id: &str, path: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    insert_document_path(&conn, doc_id, path).map_err(map_rusqlite)?;
    Ok(())
  }

  fn delete_document(&mut self, doc_id: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    crate::sqlite::delete_document(&conn, doc_id).map_err(map_rusqlite)?;
    Ok(())
  }

  fn add_chunks(&mut self, chunks: &[Chunk]) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    insert_chunks(&conn, chunks).map_err(map_rusqlite)?;
    Ok(())
  }

  fn add_chunk_documents(&mut self, chunk_ids: &[String], doc_id: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    insert_chunk_documents(&conn, chunk_ids, doc_id).map_err(map_rusqlite)?;
    Ok(())
  }

  fn delete_chunks_by_doc(&mut self, doc_id: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    crate::sqlite::delete_chunks_by_doc(&conn, doc_id).map_err(map_rusqlite)?;
    Ok(())
  }

  fn add_vectors(&mut self, chunk_ids: &[String], embeddings: &[Vec<f32>]) -> Result<()> {
    if chunk_ids.len() != embeddings.len() {
      return Err(
        StoreError::ArgumentMismatch {
          what: "chunk_ids and embeddings".into(),
          a: chunk_ids.len(),
          b: embeddings.len(),
        }
        .into(),
      );
    }
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    insert_vectors(&conn, chunk_ids, embeddings).map_err(map_rusqlite)?;
    Ok(())
  }

  fn add_fts_chunks(&mut self, chunk_ids: &[String], tokenized_texts: &[String]) -> Result<()> {
    if chunk_ids.len() != tokenized_texts.len() {
      return Err(
        StoreError::ArgumentMismatch {
          what: "chunk_ids and tokenized_texts".into(),
          a: chunk_ids.len(),
          b: tokenized_texts.len(),
        }
        .into(),
      );
    }
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    insert_fts(&conn, chunk_ids, tokenized_texts).map_err(map_rusqlite)?;
    Ok(())
  }

  fn set_model_version(&mut self, role: ModelRole, version: &ModelSpec) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    crate::sqlite::set_model_version(&conn, role, version).map_err(map_rusqlite)?;
    Ok(())
  }

  fn add_collection(&mut self, name: &str, path: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn
      .execute(
        "INSERT OR REPLACE INTO collections (name, path) VALUES (?1, ?2)",
        params![name, path],
      )
      .map_err(map_rusqlite)?;
    Ok(())
  }

  fn delete_collection(&mut self, name: &str) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn.execute("DELETE FROM collections WHERE name = ?1", params![name]).map_err(map_rusqlite)?;
    Ok(())
  }

  fn clear_collections(&mut self) -> Result<()> {
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn.execute("DELETE FROM collections", []).map_err(map_rusqlite)?;
    Ok(())
  }

  fn commit(&mut self) -> Result<()> {
    if self.committed {
      return Err(StoreError::TransactionAlreadyCommitted.into());
    }
    let conn = self.conn.lock().map_err(|_| poisoned())?;
    conn.execute_batch("COMMIT").map_err(map_rusqlite)?;
    self.committed = true;
    Ok(())
  }
}

impl Drop for SqliteTransaction {
  fn drop(&mut self) {
    if !self.committed
      && let Ok(conn) = self.conn.lock()
    {
      let _ = conn.execute_batch("ROLLBACK");
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use chrono::Utc;
  use semquery_core::{Chunk, Document, Storage, StorageTx};

  fn make_doc(id: &str, content: &str) -> Document {
    Document {
      id: id.to_string(),
      content_hash: format!("hash-{content}"),
      content_size: content.len(),
      indexed_at: Utc::now(),
    }
  }

  fn make_chunk(id: &str, doc_id: &str, text: &str, start: usize, end: usize) -> Chunk {
    Chunk {
      id: id.to_string(),
      doc_id: doc_id.to_string(),
      text: text.to_string(),
      byte_range: start..end,
    }
  }

  fn commit<F: FnOnce(&mut dyn StorageTx)>(storage: &SqliteStorage, body: F) {
    let mut tx = storage.begin_tx().unwrap();
    body(&mut *tx);
    tx.commit().unwrap();
  }

  #[test]
  fn test_init_zero_then_dimension() {
    // `semq init` / Engine::open use init(0), which must skip
    // creating the vec table so a later init(512) (lazy model loading)
    // can create it with the real dimension.
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(0).unwrap();
    storage.init(512).unwrap();
  }

  #[test]
  fn test_document_crud() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc1 = make_doc("doc1.txt", "hello world");
    let doc2 = make_doc("doc2.txt", "foo bar");
    commit(&storage, |tx| {
      tx.add_document(&doc1).unwrap();
      tx.add_document(&doc2).unwrap();
    });

    let got = storage.get_document("doc1.txt").unwrap();
    assert!(got.is_some());
    assert_eq!(got.unwrap().content_hash, "hash-hello world");

    let list = storage.list_documents().unwrap();
    assert_eq!(list.len(), 2);

    commit(&storage, |tx| {
      tx.delete_document("doc1.txt").unwrap();
    });
    assert!(storage.get_document("doc1.txt").unwrap().is_none());
    assert_eq!(storage.list_documents().unwrap().len(), 1);
  }

  #[test]
  fn test_chunk_crud() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "hello world");
    let c1 = make_chunk("c1", "doc1.txt", "hello", 0, 5);
    let c2 = make_chunk("c2", "doc1.txt", "world", 6, 11);
    commit(&storage, |tx| {
      tx.add_document(&doc).unwrap();
      tx.add_chunks(&[c1, c2]).unwrap();
      tx.add_chunk_documents(&["c1".to_string(), "c2".to_string()], "doc1.txt").unwrap();
    });

    let got = storage.get_chunks(&["c1".to_string(), "c2".to_string()]).unwrap();
    assert_eq!(got.len(), 2);

    commit(&storage, |tx| {
      tx.delete_chunks_by_doc("doc1.txt").unwrap();
    });
    let gone = storage.get_chunks(&["c1".to_string()]).unwrap();
    assert!(gone.is_empty());
  }

  #[test]
  fn test_shared_chunk_survives_deleting_one_doc() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc_a = make_doc("doc_a.txt", "shared text");
    let doc_b = make_doc("doc_b.txt", "shared text");
    let shared_chunk = make_chunk("shared", "doc_a.txt", "shared text", 0, 11);

    commit(&storage, |tx| {
      tx.add_document(&doc_a).unwrap();
      tx.add_chunks(&[shared_chunk]).unwrap();
      tx.add_chunk_documents(&["shared".to_string()], "doc_a.txt").unwrap();
    });
    commit(&storage, |tx| {
      tx.add_document(&doc_b).unwrap();
      tx.add_chunks(&[make_chunk("shared", "doc_b.txt", "shared text", 0, 11)]).unwrap();
      tx.add_chunk_documents(&["shared".to_string()], "doc_b.txt").unwrap();
    });

    let got = storage.get_chunks(&["shared".to_string()]).unwrap();
    assert_eq!(got.len(), 1);
    assert!(!got[0].text.is_empty());

    commit(&storage, |tx| {
      tx.delete_chunks_by_doc("doc_a.txt").unwrap();
    });

    let got = storage.get_chunks(&["shared".to_string()]).unwrap();
    assert_eq!(got.len(), 1, "shared chunk must survive when doc_b still references it");
  }

  #[test]
  fn test_delete_chunks_cascades_vectors_and_fts() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "content");
    let chunk = make_chunk("c1", "doc1.txt", "hello", 0, 5);
    let embedding = vec![0.1_f32; 512];
    let tokenized = "hello".to_string();

    commit(&storage, |tx| {
      tx.add_document(&doc).unwrap();
      tx.add_chunks(&[chunk]).unwrap();
      tx.add_chunk_documents(&["c1".to_string()], "doc1.txt").unwrap();
      tx.add_vectors(&["c1".to_string()], &[embedding]).unwrap();
      tx.add_fts_chunks(&["c1".to_string()], &[tokenized]).unwrap();
    });

    assert!(!storage.search_vectors(&vec![0.1_f32; 512], 10).unwrap().is_empty());
    assert!(!storage.search_text("hello", 10).unwrap().is_empty());

    commit(&storage, |tx| {
      tx.delete_chunks_by_doc("doc1.txt").unwrap();
    });

    assert!(storage.get_chunks(&["c1".to_string()]).unwrap().is_empty());
    assert!(storage.search_vectors(&vec![0.1_f32; 512], 10).unwrap().is_empty());
    assert!(storage.search_text("hello", 10).unwrap().is_empty());
  }

  #[test]
  fn test_model_version() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    assert!(storage.get_model_version(ModelRole::Embedding).unwrap().is_none());

    let spec = ModelSpec {
      role: ModelRole::Embedding,
      repo_id: "BAAI/bge-small-zh-v1.5".into(),
      filename: "model.onnx".into(),
      revision: "main".into(),
      checksum: Some("abc123".into()),
    };
    commit(&storage, |tx| {
      tx.set_model_version(ModelRole::Embedding, &spec).unwrap();
    });

    let got = storage.get_model_version(ModelRole::Embedding).unwrap().unwrap();
    assert_eq!(got.repo_id, "BAAI/bge-small-zh-v1.5");
    assert_eq!(got.checksum.as_deref(), Some("abc123"));
  }

  #[test]
  fn test_vector_search() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "content");
    let chunk = make_chunk("c0", "doc1.txt", "text", 0, 4);

    let base = vec![0.0_f32; 512];
    let mut vectors: Vec<Vec<f32>> = Vec::new();
    let mut ids: Vec<String> = Vec::new();
    let mut chunks = vec![chunk];
    for i in 0..10 {
      let mut v = base.clone();
      v[i] = 1.0;
      vectors.push(v);
      ids.push(format!("c{i}"));
      let ch = make_chunk(&format!("c{i}"), "doc1.txt", "text", i, i + 1);
      chunks.push(ch);
    }
    commit(&storage, |tx| {
      tx.add_document(&doc).unwrap();
      tx.add_chunks(&chunks).unwrap();
      tx.add_chunk_documents(&ids, "doc1.txt").unwrap();
      tx.add_vectors(&ids, &vectors).unwrap();
    });

    let mut query = vec![0.0_f32; 512];
    query[3] = 1.0;
    let hits = storage.search_vectors(&query, 3).unwrap();
    assert_eq!(hits.len(), 3);
    assert_eq!(hits[0].0, "c3");
    assert!(hits[0].1 > hits[1].1);
  }

  #[test]
  fn test_text_search() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "content");
    let chunks = [
      ("c1", "分布式 共识 算法 解决 多个 节点 达成 一致 的 问题"),
      ("c2", "Raft 是 一种 易于 理解 的 共识 算法"),
      ("c3", "今天 天气 不错"),
    ];
    let chunk_objs: Vec<Chunk> =
      chunks.iter().map(|(id, text)| make_chunk(id, "doc1.txt", text, 0, text.len())).collect();
    let ids: Vec<String> = chunks.iter().map(|(id, _)| id.to_string()).collect();
    let texts: Vec<String> = chunks.iter().map(|(_, text)| text.to_string()).collect();
    commit(&storage, |tx| {
      tx.add_document(&doc).unwrap();
      tx.add_chunks(&chunk_objs).unwrap();
      tx.add_chunk_documents(&ids, "doc1.txt").unwrap();
      tx.add_fts_chunks(&ids, &texts).unwrap();
    });

    let hits = storage.search_text("共识 算法", 10).unwrap();
    assert_eq!(hits.len(), 2);
    let ids: Vec<&str> = hits.iter().map(|(id, _)| id.as_str()).collect();
    assert!(ids.contains(&"c1"));
    assert!(ids.contains(&"c2"));
    assert!(!ids.contains(&"c3"));
  }

  #[test]
  fn test_transaction_commit() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "content");
    let chunk = make_chunk("c1", "doc1.txt", "hello", 0, 5);
    let tokenized = "hello".to_string();
    let embedding = vec![0.1_f32; 512];

    {
      let mut tx = storage.begin_tx().unwrap();
      tx.add_document(&doc).unwrap();
      tx.add_chunks(std::slice::from_ref(&chunk)).unwrap();
      tx.add_chunk_documents(&["c1".to_string()], "doc1.txt").unwrap();
      tx.add_vectors(&["c1".to_string()], std::slice::from_ref(&embedding)).unwrap();
      tx.add_fts_chunks(&["c1".to_string()], std::slice::from_ref(&tokenized)).unwrap();
      tx.commit().unwrap();
    }

    assert!(storage.get_document("doc1.txt").unwrap().is_some());
    assert_eq!(storage.get_chunks(&["c1".to_string()]).unwrap().len(), 1);
    let hits = storage.search_vectors(&embedding, 1).unwrap();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].0, "c1");
    assert_eq!(storage.search_text("hello", 10).unwrap().len(), 1);
  }

  #[test]
  fn test_transaction_rollback_on_drop() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "content");

    {
      let mut tx = storage.begin_tx().unwrap();
      tx.add_document(&doc).unwrap();
    }

    assert!(
      storage.get_document("doc1.txt").unwrap().is_none(),
      "doc must not persist without commit"
    );
  }

  #[test]
  fn test_transaction_commit_after_failure() {
    let storage = SqliteStorage::open_in_memory().unwrap();
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "content");
    let chunk = make_chunk("c1", "doc1.txt", "hello", 0, 5);

    let result = {
      let mut tx = storage.begin_tx().unwrap();
      tx.add_document(&doc).unwrap();
      tx.add_chunks(&[chunk]).unwrap();
      tx.add_vectors(&["c1".to_string(), "c2".to_string()], &[vec![0.0_f32; 512]]).unwrap_err();
      Err::<(), _>(StoreError::Sqlite("forced".into()))
    };
    assert!(result.is_err());

    assert!(
      storage.get_document("doc1.txt").unwrap().is_none(),
      "partial writes must be rolled back"
    );
    assert!(storage.get_chunks(&["c1".to_string()]).unwrap().is_empty());
  }

  #[test]
  fn test_concurrent_reads() {
    let storage = Arc::new(SqliteStorage::open_in_memory().unwrap());
    storage.init(512).unwrap();

    let doc = make_doc("doc1.txt", "concurrent read test");
    let chunk = make_chunk("c1", "doc1.txt", "hello world", 0, 11);
    commit(&storage, |tx| {
      tx.add_document(&doc).unwrap();
      tx.add_chunks(&[chunk]).unwrap();
      tx.add_chunk_documents(&["c1".to_string()], "doc1.txt").unwrap();
      tx.add_vectors(&["c1".to_string()], &[vec![0.1_f32; 512]]).unwrap();
      tx.add_fts_chunks(&["c1".to_string()], &["hello world".to_string()]).unwrap();
    });

    let handles: Vec<_> = (0..8)
      .map(|_| {
        let s = storage.clone();
        std::thread::spawn(move || {
          assert!(s.get_document("doc1.txt").unwrap().is_some());
          assert!(!s.get_chunks(&["c1".to_string()]).unwrap().is_empty());
          assert!(!s.search_vectors(&vec![0.1_f32; 512], 10).unwrap().is_empty());
          assert!(!s.search_text("hello", 10).unwrap().is_empty());
          assert_eq!(s.count_chunks().unwrap(), 1);
        })
      })
      .collect();

    for h in handles {
      h.join().unwrap();
    }
  }

  #[test]
  fn test_concurrent_reads_and_writes() {
    let storage = Arc::new(SqliteStorage::open_in_memory().unwrap());
    storage.init(512).unwrap();

    for i in 0..5 {
      let doc = make_doc(&format!("doc{i}.txt"), &format!("content {i}"));
      let chunk = make_chunk(&format!("c{i}"), &format!("doc{i}.txt"), &format!("text {i}"), 0, 6);
      commit(&storage, |tx| {
        tx.add_document(&doc).unwrap();
        tx.add_chunks(&[chunk]).unwrap();
        tx.add_chunk_documents(&[format!("c{i}")], &format!("doc{i}.txt")).unwrap();
      });
    }

    let reader = storage.clone();
    let read_handle = std::thread::spawn(move || {
      for _ in 0..50 {
        let docs = reader.list_documents().unwrap();
        assert!(docs.len() >= 5);
        let _ = reader.count_chunks().unwrap();
      }
    });

    let writer = storage.clone();
    let write_handle = std::thread::spawn(move || {
      for i in 0..5 {
        let doc = make_doc(&format!("extra{i}.txt"), &format!("extra {i}"));
        let chunk = make_chunk(
          &format!("extra_c{i}"),
          &format!("extra{i}.txt"),
          &format!("extra {i}"),
          0,
          7,
        );
        commit(&writer, |tx| {
          tx.add_document(&doc).unwrap();
          tx.add_chunks(&[chunk]).unwrap();
          tx.add_chunk_documents(&[format!("extra_c{i}")], &format!("extra{i}.txt")).unwrap();
        });
      }
    });

    read_handle.join().unwrap();
    write_handle.join().unwrap();

    let final_count = storage.list_documents().unwrap().len();
    assert_eq!(final_count, 10);
  }
}