-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathschema.rs
More file actions
1656 lines (1412 loc) · 62.5 KB
/
schema.rs
File metadata and controls
1656 lines (1412 loc) · 62.5 KB
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
// SPDX-License-Identifier: MIT OR Apache-2.0
use anyhow::Result;
use arrow::array::Array;
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;
use futures::{stream, StreamExt, TryStreamExt};
use lancedb::connection::Connection;
use lancedb::index::{scalar::BTreeIndexBuilder, scalar::FtsIndexBuilder, Index as LanceIndex};
use lancedb::query::{ExecutableQuery, QueryBase};
use lancedb::table::OptimizeAction;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
/// Outcome of a single table optimization operation.
pub enum OptimizeOutcome {
/// Table was successfully optimized (all operations completed)
Optimized,
/// Table was skipped (e.g., too few rows to benefit)
Skipped,
/// Optimization was attempted but one or more operations failed
PartialFailure,
}
pub struct SchemaManager {
connection: Connection,
}
impl SchemaManager {
pub fn new(connection: Connection) -> Self {
Self { connection }
}
pub async fn create_all_tables(&self) -> Result<()> {
let table_names = self.connection.table_names().execute().await?;
if !table_names.iter().any(|n| n == "functions") {
self.create_functions_table().await?;
}
if !table_names.iter().any(|n| n == "types") {
self.create_types_table().await?;
}
if !table_names.iter().any(|n| n == "vectors") {
self.create_vectors_table().await?;
}
if !table_names.iter().any(|n| n == "processed_files") {
self.create_processed_files_table().await?;
}
if !table_names.iter().any(|n| n == "symbol_filename") {
self.create_symbol_filename_table().await?;
}
if !table_names.iter().any(|n| n == "git_commits") {
self.create_git_commits_table().await?;
}
if !table_names.iter().any(|n| n == "commit_vectors") {
self.create_commit_vectors_table().await?;
}
if !table_names.iter().any(|n| n == "lore") {
self.create_lore_table().await?;
} else {
self.migrate_lore_table().await?;
}
if !table_names.iter().any(|n| n == "lore_indexed_commits") {
self.create_lore_indexed_commits_table().await?;
}
if !table_names.iter().any(|n| n == "lore_vectors") {
self.create_lore_vectors_table().await?;
}
if !table_names.iter().any(|n| n == "indexed_branches") {
self.create_indexed_branches_table().await?;
}
// Check and create content shard tables (content_0 through content_15)
self.create_content_shard_tables().await?;
Ok(())
}
pub async fn create_functions_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("name", DataType::Utf8, false),
Field::new("file_path", DataType::Utf8, false),
Field::new("git_file_hash", DataType::Utf8, false), // Git hash of file content as hex string
Field::new("line_start", DataType::Int64, false),
Field::new("line_end", DataType::Int64, false),
Field::new("return_type", DataType::Utf8, false),
Field::new("parameters", DataType::Utf8, false),
Field::new("body_hash", DataType::Utf8, true), // Blake3 hash referencing content table as hex string (nullable for empty bodies)
Field::new("calls", DataType::Utf8, true), // JSON array of function names called by this function
Field::new("types", DataType::Utf8, true), // JSON array of type names used by this function
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("functions", vec![empty_batch])
.execute()
.await?;
Ok(())
}
pub async fn create_types_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("name", DataType::Utf8, false),
Field::new("file_path", DataType::Utf8, false),
Field::new("git_file_hash", DataType::Utf8, false), // Git hash of file content as hex string
Field::new("line", DataType::Int64, false),
Field::new("kind", DataType::Utf8, false),
Field::new("size", DataType::Int64, true),
Field::new("fields", DataType::Utf8, false),
Field::new("definition_hash", DataType::Utf8, true), // Blake3 hash referencing content table as hex string (nullable for empty definitions)
Field::new("types", DataType::Utf8, true), // JSON array of type names referenced by this type
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("types", vec![empty_batch])
.execute()
.await?;
Ok(())
}
async fn create_vectors_table(&self) -> Result<()> {
// Create vectors table with 256 dimensions
let schema = Arc::new(Schema::new(vec![
Field::new("content_hash", DataType::Utf8, false), // Blake3 content hash as hex string
Field::new(
"vector",
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 256),
false, // Non-nullable - we only store entries that have vectors
),
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("vectors", vec![empty_batch])
.execute()
.await?;
tracing::info!("Created vectors table with 256 dimensions");
Ok(())
}
async fn create_commit_vectors_table(&self) -> Result<()> {
// Create commit_vectors table with 256 dimensions
let schema = Arc::new(Schema::new(vec![
Field::new("git_commit_sha", DataType::Utf8, false), // Git commit SHA
Field::new(
"vector",
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 256),
false, // Non-nullable - we only store entries that have vectors
),
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("commit_vectors", vec![empty_batch])
.execute()
.await?;
tracing::info!("Created commit_vectors table with 256 dimensions");
Ok(())
}
async fn create_lore_vectors_table(&self) -> Result<()> {
// Create lore_vectors table with 256 dimensions, indexed by message_id
let schema = Arc::new(Schema::new(vec![
Field::new("message_id", DataType::Utf8, false), // Email message-id
Field::new(
"vector",
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 256),
false, // Non-nullable - we only store entries that have vectors
),
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("lore_vectors", vec![empty_batch])
.execute()
.await?;
tracing::info!("Created lore_vectors table with 256 dimensions");
Ok(())
}
async fn create_processed_files_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("file", DataType::Utf8, false), // File path
Field::new("git_sha", DataType::Utf8, true), // Current git head SHA as hex string (nullable)
Field::new("git_file_sha", DataType::Utf8, false), // SHA of specific file content as hex string
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("processed_files", vec![empty_batch])
.execute()
.await?;
Ok(())
}
async fn create_symbol_filename_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("symbol", DataType::Utf8, false), // Symbol name (function, macro, type, or typedef)
Field::new("filename", DataType::Utf8, false), // File path where symbol is defined
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("symbol_filename", vec![empty_batch])
.execute()
.await?;
Ok(())
}
async fn create_git_commits_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("git_sha", DataType::Utf8, false), // Commit SHA
Field::new("parent_sha", DataType::Utf8, false), // Parent commit SHAs (JSON array)
Field::new("author", DataType::Utf8, false), // Author name and email
Field::new("subject", DataType::Utf8, false), // Single line commit title
Field::new("message", DataType::Utf8, false), // Full commit message
Field::new("tags", DataType::Utf8, false), // JSON object of tags
Field::new("diff", DataType::Utf8, false), // Full unified diff
Field::new("symbols", DataType::Utf8, false), // JSON array of changed symbols
Field::new("files", DataType::Utf8, false), // JSON array of changed files
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("git_commits", vec![empty_batch])
.execute()
.await?;
Ok(())
}
async fn create_lore_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("git_commit_sha", DataType::Utf8, false), // Git commit SHA containing this email
Field::new("from", DataType::Utf8, false), // From header in the email
Field::new("date", DataType::Utf8, false), // Date field (RFC 2822 format)
Field::new("date_timestamp", DataType::Int64, false), // Unix timestamp for efficient date filtering
Field::new("message_id", DataType::Utf8, false), // Message-ID header
Field::new("in_reply_to", DataType::Utf8, true), // In-Reply-To header (nullable)
Field::new("subject", DataType::Utf8, false), // Subject line
Field::new("references", DataType::Utf8, true), // Full list of references (nullable)
Field::new("recipients", DataType::Utf8, false), // Full list of cc/to recipients
Field::new("body", DataType::Utf8, false), // Email body (everything after first blank line)
Field::new("symbols", DataType::Utf8, false), // JSON array of symbols referenced in email
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("lore", vec![empty_batch])
.execute()
.await?;
tracing::info!("Created lore table for email archive indexing");
Ok(())
}
/// Migrate an existing lore table to the current schema.
async fn migrate_lore_table(&self) -> Result<()> {
let table = self.connection.open_table("lore").execute().await?;
let schema = table.schema().await?;
// Drop the "headers" column if it exists; individual header
// fields are stored in their own columns and reconstructed
// on demand for MBOX output.
if schema.column_with_name("headers").is_some() {
tracing::info!("Migrating lore table: dropping 'headers' column");
table.drop_columns(&["headers"]).await?;
// drop_columns() is a schema-only operation; old data
// fragments still carry the headers bytes on disk.
// Compact to rewrite fragments without the column,
// then prune to delete the stale files.
tracing::info!("Compacting lore table to reclaim space");
match Self::optimize_single_table(&self.connection, "lore").await? {
OptimizeOutcome::Optimized => {
tracing::info!("Lore table migration complete");
}
OptimizeOutcome::Skipped => {
tracing::info!("Lore table compaction skipped (preserving FTS indices)");
}
OptimizeOutcome::PartialFailure => {
tracing::warn!("Lore table compaction partially failed");
}
}
}
// Add the date_timestamp column if missing. Databases created
// before this column was introduced have a 10-column schema;
// merge_insert of 11-column batches silently fails, causing
// new emails to be skipped while their commit SHAs are still
// recorded as indexed.
if schema.column_with_name("date_timestamp").is_none() {
tracing::info!("Migrating lore table: adding 'date_timestamp' column");
table
.add_columns(
lancedb::table::NewColumnTransform::SqlExpressions(vec![(
"date_timestamp".into(),
"CAST(0 AS BIGINT)".into(),
)]),
None,
)
.await?;
// Purge lore_indexed_commits so that previously-skipped
// emails are re-examined on the next --lore refresh.
self.reconcile_lore_indexed_commits().await?;
}
Ok(())
}
/// Remove entries from lore_indexed_commits whose git_commit_sha
/// does not appear in the lore table. This recovers from the
/// schema-mismatch bug where SHAs were recorded as indexed but the
/// corresponding emails were never stored.
async fn reconcile_lore_indexed_commits(&self) -> Result<()> {
let lore = self.connection.open_table("lore").execute().await?;
let idx = self
.connection
.open_table("lore_indexed_commits")
.execute()
.await?;
// Collect the set of SHAs actually present in the lore table.
let lore_stream = lore
.query()
.select(lancedb::query::Select::Columns(vec![
"git_commit_sha".to_string()
]))
.execute()
.await?;
let lore_batches: Vec<_> = lore_stream.try_collect().await?;
let mut lore_shas = std::collections::HashSet::new();
for batch in &lore_batches {
if let Some(col) = batch.column_by_name("git_commit_sha") {
if let Some(arr) = col.as_any().downcast_ref::<arrow::array::StringArray>() {
for i in 0..arr.len() {
lore_shas.insert(arr.value(i).to_string());
}
}
}
}
// Collect SHAs from lore_indexed_commits.
let idx_stream = idx
.query()
.select(lancedb::query::Select::Columns(vec![
"git_commit_sha".to_string()
]))
.execute()
.await?;
let idx_batches: Vec<_> = idx_stream.try_collect().await?;
let mut orphaned: Vec<String> = Vec::new();
for batch in &idx_batches {
if let Some(col) = batch.column_by_name("git_commit_sha") {
if let Some(arr) = col.as_any().downcast_ref::<arrow::array::StringArray>() {
for i in 0..arr.len() {
let sha = arr.value(i);
if !lore_shas.contains(sha) {
orphaned.push(sha.to_string());
}
}
}
}
}
if orphaned.is_empty() {
tracing::info!("reconcile_lore_indexed_commits: no orphaned entries");
return Ok(());
}
tracing::info!(
"reconcile_lore_indexed_commits: removing {} orphaned entries",
orphaned.len()
);
// Delete in chunks to avoid oversized SQL predicates.
for chunk in orphaned.chunks(500) {
let placeholders: Vec<String> = chunk
.iter()
.map(|s| format!("'{}'", s.replace('\'', "''")))
.collect();
let predicate = format!("git_commit_sha IN ({})", placeholders.join(", "));
idx.delete(&predicate).await?;
}
tracing::info!("reconcile_lore_indexed_commits: done");
Ok(())
}
async fn create_lore_indexed_commits_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new(
"git_commit_sha",
DataType::Utf8,
false,
)]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("lore_indexed_commits", vec![empty_batch])
.execute()
.await?;
tracing::info!("Created lore_indexed_commits table");
Ok(())
}
async fn create_indexed_branches_table(&self) -> Result<()> {
use crate::database::branches::IndexedBranchStore;
let schema = IndexedBranchStore::get_schema();
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("indexed_branches", vec![empty_batch])
.execute()
.await?;
tracing::info!("Created indexed_branches table for multi-branch support");
Ok(())
}
async fn create_content_table(&self) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("blake3_hash", DataType::Utf8, false), // Blake3 hash of content as hex string
Field::new("content", DataType::Utf8, false), // The actual content (function body, etc.)
]));
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table("content", vec![empty_batch])
.execute()
.await?;
Ok(())
}
/// Create all 16 content shard tables (content_0 through content_15)
async fn create_content_shard_tables(&self) -> Result<()> {
let table_names = self.connection.table_names().execute().await?;
let schema = Arc::new(Schema::new(vec![
Field::new("blake3_hash", DataType::Utf8, false), // Blake3 hash of content as hex string
Field::new("content", DataType::Utf8, false), // The actual content (function body, etc.)
]));
// Create each shard table if it doesn't exist
for shard in 0..16u8 {
let table_name = format!("content_{shard}");
if !table_names.iter().any(|n| n == &table_name) {
let empty_batch = RecordBatch::new_empty(schema.clone());
self.connection
.create_table(&table_name, vec![empty_batch])
.execute()
.await?;
tracing::info!("Created content shard table: {}", table_name);
}
}
Ok(())
}
pub async fn create_scalar_indices(&self) -> Result<()> {
let table_names = self.connection.table_names().execute().await?;
// Check if database already has data (skip index creation if it does - likely already indexed)
// This significantly speeds up startup time from 12+ seconds to milliseconds
// Check both functions and lore tables
if let Ok(table) = self.connection.open_table("functions").execute().await {
if let Ok(count) = table.count_rows(None).await {
if count > 100 {
tracing::debug!(
"Skipping index creation - functions table has {} rows (likely already indexed)",
count
);
return Ok(());
}
}
}
if let Ok(table) = self.connection.open_table("lore").execute().await {
if let Ok(count) = table.count_rows(None).await {
if count > 100 {
tracing::debug!(
"Skipping index creation - lore table has {} rows (likely already indexed)",
count
);
return Ok(());
}
}
}
tracing::info!("Creating database indices (first time or small database)...");
// Create indices for functions table
if table_names.iter().any(|n| n == "functions") {
let table = self.connection.open_table("functions").execute().await?;
// Index on name for exact matches
self.try_create_index(&table, &["name"], "BTree index on functions.name")
.await;
// Index on git_file_hash for content-based lookups
self.try_create_index(
&table,
&["git_file_hash"],
"BTree index on functions.git_file_hash",
)
.await;
// Index on file_path for file-based queries
self.try_create_index(&table, &["file_path"], "BTree index on functions.file_path")
.await;
// Index on body_hash for content reference lookups
self.try_create_index(&table, &["body_hash"], "BTree index on functions.body_hash")
.await;
// Index on line_start for line-based queries and sorting
self.try_create_index(
&table,
&["line_start"],
"BTree index on functions.line_start",
)
.await;
// Index on line_end for range-based queries
self.try_create_index(&table, &["line_end"], "BTree index on functions.line_end")
.await;
// Composite index for duplicate checking with content hash
self.try_create_index(
&table,
&["name", "git_file_hash"],
"Composite index on functions.(name,git_file_hash)",
)
.await;
}
// Create indices for types table
if table_names.iter().any(|n| n == "types") {
let table = self.connection.open_table("types").execute().await?;
// Index on name
self.try_create_index(&table, &["name"], "BTree index on types.name")
.await;
// Index on git_file_hash for content-based lookups
self.try_create_index(
&table,
&["git_file_hash"],
"BTree index on types.git_file_hash",
)
.await;
// Index on kind
self.try_create_index(&table, &["kind"], "BTree index on types.kind")
.await;
// Index on file_path for file-based queries
self.try_create_index(&table, &["file_path"], "BTree index on types.file_path")
.await;
// Index on definition_hash for content reference lookups
self.try_create_index(
&table,
&["definition_hash"],
"BTree index on types.definition_hash",
)
.await;
// Composite index for duplicate checking with content hash
self.try_create_index(
&table,
&["name", "kind", "git_file_hash"],
"Composite index on types.(name,kind,git_file_hash)",
)
.await;
}
// Create indices for vectors table
if table_names.iter().any(|n| n == "vectors") {
let table = self.connection.open_table("vectors").execute().await?;
// Primary index on content_hash for fast lookups
self.try_create_index(
&table,
&["content_hash"],
"BTree index on vectors.content_hash",
)
.await;
}
// Create indices for commit_vectors table
if table_names.iter().any(|n| n == "commit_vectors") {
let table = self
.connection
.open_table("commit_vectors")
.execute()
.await?;
// Primary index on git_commit_sha for fast lookups
self.try_create_index(
&table,
&["git_commit_sha"],
"BTree index on commit_vectors.git_commit_sha",
)
.await;
}
// Create indices for lore_vectors table
if table_names.iter().any(|n| n == "lore_vectors") {
let table = self.connection.open_table("lore_vectors").execute().await?;
// Primary index on message_id for fast lookups
self.try_create_index(
&table,
&["message_id"],
"BTree index on lore_vectors.message_id",
)
.await;
}
// Create indices for lore table
if table_names.iter().any(|n| n == "lore") {
let table = self.connection.open_table("lore").execute().await?;
// Index on message_id for fast lookups and joins
self.try_create_index(&table, &["message_id"], "BTree index on lore.message_id")
.await;
// Index on from field for email sender queries
self.try_create_index(&table, &["from"], "BTree index on lore.from")
.await;
// Index on subject for subject-based searches
self.try_create_index(&table, &["subject"], "BTree index on lore.subject")
.await;
// Index on git_commit_sha for commit-based lookups
self.try_create_index(
&table,
&["git_commit_sha"],
"BTree index on lore.git_commit_sha",
)
.await;
// Index on date for chronological queries
self.try_create_index(&table, &["date"], "BTree index on lore.date")
.await;
// Index on in_reply_to for threading queries
self.try_create_index(&table, &["in_reply_to"], "BTree index on lore.in_reply_to")
.await;
// Index on references for threading
self.try_create_index(&table, &["references"], "BTree index on lore.references")
.await;
// Note: FTS indices for lore table are created separately after data is inserted
// via create_lore_fts_indices() - see process_lore_commits_pipeline completion
// BTree indices on body, recipients, and symbols removed - FTS indices used instead
}
// Create indices for processed_files table
if table_names.iter().any(|n| n == "processed_files") {
let table = self
.connection
.open_table("processed_files")
.execute()
.await?;
// Index on file for file-based lookups
self.try_create_index(&table, &["file"], "BTree index on processed_files.file")
.await;
// Index on git_sha for git commit-based lookups
self.try_create_index(
&table,
&["git_sha"],
"BTree index on processed_files.git_sha",
)
.await;
// Index on git_file_sha for file content-based lookups
self.try_create_index(
&table,
&["git_file_sha"],
"BTree index on processed_files.git_file_sha",
)
.await;
// Composite index for efficient file + git_sha lookups
self.try_create_index(
&table,
&["file", "git_sha"],
"Composite index on processed_files.(file,git_sha)",
)
.await;
}
// Create indices for symbol_filename table
if table_names.iter().any(|n| n == "symbol_filename") {
let table = self
.connection
.open_table("symbol_filename")
.execute()
.await?;
// Index on symbol for symbol name-based lookups
self.try_create_index(&table, &["symbol"], "BTree index on symbol_filename.symbol")
.await;
// Index on filename for file-based lookups
self.try_create_index(
&table,
&["filename"],
"BTree index on symbol_filename.filename",
)
.await;
// Composite index on (symbol, filename) for fast deduplication
self.try_create_index(
&table,
&["symbol", "filename"],
"Composite index on symbol_filename.(symbol,filename)",
)
.await;
}
// Create indices for git_commits table
if table_names.iter().any(|n| n == "git_commits") {
let table = self.connection.open_table("git_commits").execute().await?;
// Index on git_sha for commit lookups
self.try_create_index(&table, &["git_sha"], "BTree index on git_commits.git_sha")
.await;
// Index on parent_sha for parent commit lookups
self.try_create_index(
&table,
&["parent_sha"],
"BTree index on git_commits.parent_sha",
)
.await;
// Index on author for author-based queries
self.try_create_index(&table, &["author"], "BTree index on git_commits.author")
.await;
// Index on subject for subject searches
self.try_create_index(&table, &["subject"], "BTree index on git_commits.subject")
.await;
}
// Create indices for lore table
if table_names.iter().any(|n| n == "lore") {
let table = self.connection.open_table("lore").execute().await?;
// Index on git_commit_sha for commit-based queries
self.try_create_index(
&table,
&["git_commit_sha"],
"BTree index on lore.git_commit_sha",
)
.await;
// Index on message_id for unique message lookups
self.try_create_index(&table, &["message_id"], "BTree index on lore.message_id")
.await;
// Index on from for sender-based queries
self.try_create_index(&table, &["from"], "BTree index on lore.from")
.await;
// Index on date for date-based queries and sorting
self.try_create_index(&table, &["date"], "BTree index on lore.date")
.await;
// Index on in_reply_to for threading
self.try_create_index(&table, &["in_reply_to"], "BTree index on lore.in_reply_to")
.await;
// Index on subject for subject searches
self.try_create_index(&table, &["subject"], "BTree index on lore.subject")
.await;
// Index on references for threading
self.try_create_index(&table, &["references"], "BTree index on lore.references")
.await;
// Note: BTree indices on body, recipients, and symbols removed - FTS used instead
}
// Create indices for indexed_branches table
if table_names.iter().any(|n| n == "indexed_branches") {
let table = self
.connection
.open_table("indexed_branches")
.execute()
.await?;
// Primary index on branch_name for fast branch lookups
self.try_create_index(
&table,
&["branch_name"],
"BTree index on indexed_branches.branch_name",
)
.await;
// Index on tip_commit for finding branches at specific commits
self.try_create_index(
&table,
&["tip_commit"],
"BTree index on indexed_branches.tip_commit",
)
.await;
// Index on remote for remote-based queries
self.try_create_index(
&table,
&["remote"],
"BTree index on indexed_branches.remote",
)
.await;
}
// Create indices for all content shard tables
for shard in 0..16u8 {
let table_name = format!("content_{shard}");
if table_names.iter().any(|n| n == &table_name) {
let table = self.connection.open_table(&table_name).execute().await?;
// Primary index on blake3_hash for deduplication and fast lookups
self.try_create_index(
&table,
&["blake3_hash"],
&format!("BTree index on {table_name}.blake3_hash"),
)
.await;
}
}
Ok(())
}
async fn try_create_index(
&self,
table: &lancedb::table::Table,
columns: &[&str],
description: &str,
) {
match table
.create_index(columns, LanceIndex::BTree(BTreeIndexBuilder::default()))
.execute()
.await
{
Ok(_) => tracing::info!("Created {}", description),
Err(e) => tracing::debug!("{} may already exist: {}", description, e),
}
}
/// Drop and rebuild all FTS indices for the lore table from scratch.
///
/// Intended for schema migrations and --clear rebuilds where the
/// table structure has changed. Normal incremental indexing should
/// use ensure_lore_fts_indices() + optimize_lore_fts_indices().
pub async fn create_lore_fts_indices(&self) -> Result<()> {
let table = self.connection.open_table("lore").execute().await?;
// Drop existing FTS indices before recreating them.
// drop_index() removes the logical reference but leaves the
// old directory under _indices/ as orphaned data; a prune
// pass below reclaims that space.
use lancedb::index::IndexType;
let indices: Vec<lancedb::index::IndexConfig> =
(table.list_indices().await).unwrap_or_default();
let mut dropped = false;
for idx in &indices {
if idx.index_type == IndexType::FTS {
tracing::info!("Dropping stale FTS index: {}", idx.name);
if let Err(e) = table.drop_index(&idx.name).await {
tracing::warn!("Failed to drop FTS index {}: {}", idx.name, e);
}
dropped = true;
}
}
Self::create_all_fts_indices(&table).await?;
// Prune orphaned index data left behind by drop_index().
if dropped {
tracing::info!("Pruning orphaned index data from lore table...");
if let Err(e) = table
.optimize(OptimizeAction::Prune {
older_than: Some(
lancedb::table::Duration::try_seconds(0).expect("valid duration"),
),
delete_unverified: Some(true),
error_if_tagged_old_versions: Some(false),
})
.await
{
tracing::warn!("Failed to prune lore table after FTS rebuild: {}", e);
}
}
Ok(())
}
/// Create FTS indices only if they do not already exist.
///
/// After the first full build, subsequent indexing runs call this
/// to ensure the indices are present, then optimize_lore_fts_indices()
/// to merge newly-inserted rows into the existing indices.
pub async fn ensure_lore_fts_indices(&self) -> Result<()> {
use lancedb::index::IndexType;
let table = self.connection.open_table("lore").execute().await?;
let indices: Vec<lancedb::index::IndexConfig> =
(table.list_indices().await).unwrap_or_default();
let fts_count = indices
.iter()
.filter(|idx| idx.index_type == IndexType::FTS)
.count();
// All 5 FTS indices present — nothing to do.
if fts_count >= 5 {
tracing::info!(
"Lore FTS indices already present ({} indices), skipping creation",
fts_count
);
return Ok(());
}
if fts_count > 0 {
tracing::info!(
"Only {} of 5 FTS indices present, rebuilding all",
fts_count
);
// Drop the partial set so create_index does not collide.
for idx in &indices {
if idx.index_type == IndexType::FTS {
let _ = table.drop_index(&idx.name).await;
}
}
} else {
tracing::info!("No FTS indices found, creating initial set");
}
Self::create_all_fts_indices(&table).await
}
/// Merge newly-inserted rows into existing lore FTS indices.
///
/// LanceDB's native FTS engine serves unindexed rows via a
/// brute-force fallback at query time, so queries remain correct
/// even before this call. Running optimize merges those rows
/// into the inverted index structure, eliminating the scan cost.
pub async fn optimize_lore_fts_indices(&self) -> Result<()> {
// Guard against running on a table with a large _indices/
// backlog. lance/index/append.rs opens every delta fragment
// for a column before merging any, so peak memory scales
// linearly with the number of fragments per column. On
// memory-constrained systems a backlog in the thousands
// drives semcode-index into swap and gets it OOM-killed.
// Query correctness is preserved regardless: unindexed rows
// still fall back to a brute-force scan.