semantic_index.rs

  1mod chunking;
  2mod embedding;
  3mod embedding_index;
  4mod indexing;
  5mod project_index;
  6mod project_index_debug_view;
  7mod summary_backlog;
  8mod summary_index;
  9mod worktree_index;
 10
 11use anyhow::{Context as _, Result};
 12use collections::HashMap;
 13use fs::Fs;
 14use gpui::{App, AppContext as _, AsyncApp, BorrowAppContext, Context, Entity, Global, WeakEntity};
 15use language::LineEnding;
 16use project::{Project, Worktree};
 17use std::{
 18    cmp::Ordering,
 19    path::{Path, PathBuf},
 20    sync::Arc,
 21};
 22use util::ResultExt as _;
 23use workspace::Workspace;
 24
 25pub use embedding::*;
 26pub use project_index::{LoadedSearchResult, ProjectIndex, SearchResult, Status};
 27pub use project_index_debug_view::ProjectIndexDebugView;
 28pub use summary_index::FileSummary;
 29
 30pub struct SemanticDb {
 31    embedding_provider: Arc<dyn EmbeddingProvider>,
 32    db_connection: Option<heed::Env>,
 33    project_indices: HashMap<WeakEntity<Project>, Entity<ProjectIndex>>,
 34}
 35
 36impl Global for SemanticDb {}
 37
 38impl SemanticDb {
 39    pub async fn new(
 40        db_path: PathBuf,
 41        embedding_provider: Arc<dyn EmbeddingProvider>,
 42        cx: &mut AsyncApp,
 43    ) -> Result<Self> {
 44        let db_connection = cx
 45            .background_executor()
 46            .spawn(async move {
 47                std::fs::create_dir_all(&db_path)?;
 48                unsafe {
 49                    heed::EnvOpenOptions::new()
 50                        .map_size(1024 * 1024 * 1024)
 51                        .max_dbs(3000)
 52                        .open(db_path)
 53                }
 54            })
 55            .await
 56            .context("opening database connection")?;
 57
 58        cx.update(|cx| {
 59            cx.observe_new(
 60                |workspace: &mut Workspace, _window, cx: &mut Context<Workspace>| {
 61                    let project = workspace.project().clone();
 62
 63                    if cx.has_global::<SemanticDb>() {
 64                        cx.update_global::<SemanticDb, _>(|this, cx| {
 65                            this.create_project_index(project, cx);
 66                        })
 67                    } else {
 68                        log::info!("No SemanticDb, skipping project index")
 69                    }
 70                },
 71            )
 72            .detach();
 73        })
 74        .ok();
 75
 76        Ok(SemanticDb {
 77            db_connection: Some(db_connection),
 78            embedding_provider,
 79            project_indices: HashMap::default(),
 80        })
 81    }
 82
 83    pub async fn load_results(
 84        mut results: Vec<SearchResult>,
 85        fs: &Arc<dyn Fs>,
 86        cx: &AsyncApp,
 87    ) -> Result<Vec<LoadedSearchResult>> {
 88        let mut max_scores_by_path = HashMap::<_, (f32, usize)>::default();
 89        for result in &results {
 90            let (score, query_index) = max_scores_by_path
 91                .entry((result.worktree.clone(), result.path.clone()))
 92                .or_default();
 93            if result.score > *score {
 94                *score = result.score;
 95                *query_index = result.query_index;
 96            }
 97        }
 98
 99        results.sort_by(|a, b| {
100            let max_score_a = max_scores_by_path[&(a.worktree.clone(), a.path.clone())].0;
101            let max_score_b = max_scores_by_path[&(b.worktree.clone(), b.path.clone())].0;
102            max_score_b
103                .partial_cmp(&max_score_a)
104                .unwrap_or(Ordering::Equal)
105                .then_with(|| a.worktree.entity_id().cmp(&b.worktree.entity_id()))
106                .then_with(|| a.path.cmp(&b.path))
107                .then_with(|| a.range.start.cmp(&b.range.start))
108        });
109
110        let mut last_loaded_file: Option<(Entity<Worktree>, Arc<Path>, PathBuf, String)> = None;
111        let mut loaded_results = Vec::<LoadedSearchResult>::new();
112        for result in results {
113            let full_path;
114            let file_content;
115            if let Some(last_loaded_file) =
116                last_loaded_file
117                    .as_ref()
118                    .filter(|(last_worktree, last_path, _, _)| {
119                        last_worktree == &result.worktree && last_path == &result.path
120                    })
121            {
122                full_path = last_loaded_file.2.clone();
123                file_content = &last_loaded_file.3;
124            } else {
125                let output = result.worktree.read_with(cx, |worktree, _cx| {
126                    let entry_abs_path = worktree.abs_path().join(&result.path);
127                    let mut entry_full_path = PathBuf::from(worktree.root_name());
128                    entry_full_path.push(&result.path);
129                    let file_content = async {
130                        let entry_abs_path = entry_abs_path;
131                        fs.load(&entry_abs_path).await
132                    };
133                    (entry_full_path, file_content)
134                })?;
135                full_path = output.0;
136                let Some(content) = output.1.await.log_err() else {
137                    continue;
138                };
139                last_loaded_file = Some((
140                    result.worktree.clone(),
141                    result.path.clone(),
142                    full_path.clone(),
143                    content,
144                ));
145                file_content = &last_loaded_file.as_ref().unwrap().3;
146            };
147
148            let query_index = max_scores_by_path[&(result.worktree.clone(), result.path.clone())].1;
149
150            let mut range_start = result.range.start.min(file_content.len());
151            let mut range_end = result.range.end.min(file_content.len());
152            while !file_content.is_char_boundary(range_start) {
153                range_start += 1;
154            }
155            while !file_content.is_char_boundary(range_end) {
156                range_end += 1;
157            }
158
159            let start_row = file_content[0..range_start].matches('\n').count() as u32;
160            let mut end_row = file_content[0..range_end].matches('\n').count() as u32;
161            let start_line_byte_offset = file_content[0..range_start]
162                .rfind('\n')
163                .map(|pos| pos + 1)
164                .unwrap_or_default();
165            let mut end_line_byte_offset = range_end;
166            if file_content[..end_line_byte_offset].ends_with('\n') {
167                end_row -= 1;
168            } else {
169                end_line_byte_offset = file_content[range_end..]
170                    .find('\n')
171                    .map(|pos| range_end + pos + 1)
172                    .unwrap_or_else(|| file_content.len());
173            }
174            let mut excerpt_content =
175                file_content[start_line_byte_offset..end_line_byte_offset].to_string();
176            LineEnding::normalize(&mut excerpt_content);
177
178            if let Some(prev_result) = loaded_results.last_mut() {
179                if prev_result.full_path == full_path {
180                    if *prev_result.row_range.end() + 1 == start_row {
181                        prev_result.row_range = *prev_result.row_range.start()..=end_row;
182                        prev_result.excerpt_content.push_str(&excerpt_content);
183                        continue;
184                    }
185                }
186            }
187
188            loaded_results.push(LoadedSearchResult {
189                path: result.path,
190                full_path,
191                excerpt_content,
192                row_range: start_row..=end_row,
193                query_index,
194            });
195        }
196
197        for result in &mut loaded_results {
198            while result.excerpt_content.ends_with("\n\n") {
199                result.excerpt_content.pop();
200                result.row_range =
201                    *result.row_range.start()..=result.row_range.end().saturating_sub(1)
202            }
203        }
204
205        Ok(loaded_results)
206    }
207
208    pub fn project_index(
209        &mut self,
210        project: Entity<Project>,
211        _cx: &mut App,
212    ) -> Option<Entity<ProjectIndex>> {
213        self.project_indices.get(&project.downgrade()).cloned()
214    }
215
216    pub fn remaining_summaries(
217        &self,
218        project: &WeakEntity<Project>,
219        cx: &mut App,
220    ) -> Option<usize> {
221        self.project_indices.get(project).map(|project_index| {
222            project_index.update(cx, |project_index, cx| {
223                project_index.remaining_summaries(cx)
224            })
225        })
226    }
227
228    pub fn create_project_index(
229        &mut self,
230        project: Entity<Project>,
231        cx: &mut App,
232    ) -> Entity<ProjectIndex> {
233        let project_index = cx.new(|cx| {
234            ProjectIndex::new(
235                project.clone(),
236                self.db_connection.clone().unwrap(),
237                self.embedding_provider.clone(),
238                cx,
239            )
240        });
241
242        let project_weak = project.downgrade();
243        self.project_indices
244            .insert(project_weak.clone(), project_index.clone());
245
246        cx.observe_release(&project, move |_, cx| {
247            if cx.has_global::<SemanticDb>() {
248                cx.update_global::<SemanticDb, _>(|this, _| {
249                    this.project_indices.remove(&project_weak);
250                })
251            }
252        })
253        .detach();
254
255        project_index
256    }
257}
258
259impl Drop for SemanticDb {
260    fn drop(&mut self) {
261        self.db_connection.take().unwrap().prepare_for_closing();
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use anyhow::anyhow;
269    use chunking::Chunk;
270    use embedding_index::{ChunkedFile, EmbeddingIndex};
271    use feature_flags::FeatureFlagAppExt;
272    use fs::FakeFs;
273    use futures::{future::BoxFuture, FutureExt};
274    use gpui::TestAppContext;
275    use indexing::IndexingEntrySet;
276    use language::language_settings::AllLanguageSettings;
277    use project::{Project, ProjectEntryId};
278    use serde_json::json;
279    use settings::SettingsStore;
280    use smol::channel;
281    use std::{future, path::Path, sync::Arc};
282
283    fn init_test(cx: &mut TestAppContext) {
284        env_logger::try_init().ok();
285
286        cx.update(|cx| {
287            let store = SettingsStore::test(cx);
288            cx.set_global(store);
289            language::init(cx);
290            cx.update_flags(false, vec![]);
291            Project::init_settings(cx);
292            SettingsStore::update(cx, |store, cx| {
293                store.update_user_settings::<AllLanguageSettings>(cx, |_| {});
294            });
295        });
296    }
297
298    pub struct TestEmbeddingProvider {
299        batch_size: usize,
300        compute_embedding: Box<dyn Fn(&str) -> Result<Embedding> + Send + Sync>,
301    }
302
303    impl TestEmbeddingProvider {
304        pub fn new(
305            batch_size: usize,
306            compute_embedding: impl 'static + Fn(&str) -> Result<Embedding> + Send + Sync,
307        ) -> Self {
308            Self {
309                batch_size,
310                compute_embedding: Box::new(compute_embedding),
311            }
312        }
313    }
314
315    impl EmbeddingProvider for TestEmbeddingProvider {
316        fn embed<'a>(
317            &'a self,
318            texts: &'a [TextToEmbed<'a>],
319        ) -> BoxFuture<'a, Result<Vec<Embedding>>> {
320            let embeddings = texts
321                .iter()
322                .map(|to_embed| (self.compute_embedding)(to_embed.text))
323                .collect();
324            future::ready(embeddings).boxed()
325        }
326
327        fn batch_size(&self) -> usize {
328            self.batch_size
329        }
330    }
331
332    #[gpui::test]
333    async fn test_search(cx: &mut TestAppContext) {
334        cx.executor().allow_parking();
335
336        init_test(cx);
337
338        cx.update(|cx| {
339            // This functionality is staff-flagged.
340            cx.update_flags(true, vec![]);
341        });
342
343        let temp_dir = tempfile::tempdir().unwrap();
344
345        let mut semantic_index = SemanticDb::new(
346            temp_dir.path().into(),
347            Arc::new(TestEmbeddingProvider::new(16, |text| {
348                let mut embedding = vec![0f32; 2];
349                // if the text contains garbage, give it a 1 in the first dimension
350                if text.contains("garbage in") {
351                    embedding[0] = 0.9;
352                } else {
353                    embedding[0] = -0.9;
354                }
355
356                if text.contains("garbage out") {
357                    embedding[1] = 0.9;
358                } else {
359                    embedding[1] = -0.9;
360                }
361
362                Ok(Embedding::new(embedding))
363            })),
364            &mut cx.to_async(),
365        )
366        .await
367        .unwrap();
368
369        let fs = FakeFs::new(cx.executor());
370        let project_path = Path::new("/fake_project");
371
372        fs.insert_tree(
373            project_path,
374            json!({
375                "fixture": {
376                    "main.rs": include_str!("../fixture/main.rs"),
377                    "needle.md": include_str!("../fixture/needle.md"),
378                }
379            }),
380        )
381        .await;
382
383        let project = Project::test(fs, [project_path], cx).await;
384
385        let project_index = cx.update(|cx| {
386            let language_registry = project.read(cx).languages().clone();
387            let node_runtime = project.read(cx).node_runtime().unwrap().clone();
388            languages::init(language_registry, node_runtime, cx);
389            semantic_index.create_project_index(project.clone(), cx)
390        });
391
392        cx.run_until_parked();
393        while cx
394            .update(|cx| semantic_index.remaining_summaries(&project.downgrade(), cx))
395            .unwrap()
396            > 0
397        {
398            cx.run_until_parked();
399        }
400
401        let results = cx
402            .update(|cx| {
403                let project_index = project_index.read(cx);
404                let query = "garbage in, garbage out";
405                project_index.search(vec![query.into()], 4, cx)
406            })
407            .await
408            .unwrap();
409
410        assert!(
411            results.len() > 1,
412            "should have found some results, but only found {:?}",
413            results
414        );
415
416        for result in &results {
417            println!("result: {:?}", result.path);
418            println!("score: {:?}", result.score);
419        }
420
421        // Find result that is greater than 0.5
422        let search_result = results.iter().find(|result| result.score > 0.9).unwrap();
423
424        assert_eq!(search_result.path.to_string_lossy(), "fixture/needle.md");
425
426        let content = cx
427            .update(|cx| {
428                let worktree = search_result.worktree.read(cx);
429                let entry_abs_path = worktree.abs_path().join(&search_result.path);
430                let fs = project.read(cx).fs().clone();
431                cx.background_executor()
432                    .spawn(async move { fs.load(&entry_abs_path).await.unwrap() })
433            })
434            .await;
435
436        let range = search_result.range.clone();
437        let content = content[range.clone()].to_owned();
438
439        assert!(content.contains("garbage in, garbage out"));
440    }
441
442    #[gpui::test]
443    async fn test_embed_files(cx: &mut TestAppContext) {
444        cx.executor().allow_parking();
445
446        let provider = Arc::new(TestEmbeddingProvider::new(3, |text| {
447            if text.contains('g') {
448                Err(anyhow!("cannot embed text containing a 'g' character"))
449            } else {
450                Ok(Embedding::new(
451                    ('a'..='z')
452                        .map(|char| text.chars().filter(|c| *c == char).count() as f32)
453                        .collect(),
454                ))
455            }
456        }));
457
458        let (indexing_progress_tx, _) = channel::unbounded();
459        let indexing_entries = Arc::new(IndexingEntrySet::new(indexing_progress_tx));
460
461        let (chunked_files_tx, chunked_files_rx) = channel::unbounded::<ChunkedFile>();
462        chunked_files_tx
463            .send_blocking(ChunkedFile {
464                path: Path::new("test1.md").into(),
465                mtime: None,
466                handle: indexing_entries.insert(ProjectEntryId::from_proto(0)),
467                text: "abcdefghijklmnop".to_string(),
468                chunks: [0..4, 4..8, 8..12, 12..16]
469                    .into_iter()
470                    .map(|range| Chunk {
471                        range,
472                        digest: Default::default(),
473                    })
474                    .collect(),
475            })
476            .unwrap();
477        chunked_files_tx
478            .send_blocking(ChunkedFile {
479                path: Path::new("test2.md").into(),
480                mtime: None,
481                handle: indexing_entries.insert(ProjectEntryId::from_proto(1)),
482                text: "qrstuvwxyz".to_string(),
483                chunks: [0..4, 4..8, 8..10]
484                    .into_iter()
485                    .map(|range| Chunk {
486                        range,
487                        digest: Default::default(),
488                    })
489                    .collect(),
490            })
491            .unwrap();
492        chunked_files_tx.close();
493
494        let embed_files_task =
495            cx.update(|cx| EmbeddingIndex::embed_files(provider.clone(), chunked_files_rx, cx));
496        embed_files_task.task.await.unwrap();
497
498        let embedded_files_rx = embed_files_task.files;
499        let mut embedded_files = Vec::new();
500        while let Ok((embedded_file, _)) = embedded_files_rx.recv().await {
501            embedded_files.push(embedded_file);
502        }
503
504        assert_eq!(embedded_files.len(), 1);
505        assert_eq!(embedded_files[0].path.as_ref(), Path::new("test2.md"));
506        assert_eq!(
507            embedded_files[0]
508                .chunks
509                .iter()
510                .map(|embedded_chunk| { embedded_chunk.embedding.clone() })
511                .collect::<Vec<Embedding>>(),
512            vec![
513                (provider.compute_embedding)("qrst").unwrap(),
514                (provider.compute_embedding)("uvwx").unwrap(),
515                (provider.compute_embedding)("yz").unwrap(),
516            ],
517        );
518    }
519
520    #[gpui::test]
521    async fn test_load_search_results(cx: &mut TestAppContext) {
522        init_test(cx);
523
524        let fs = FakeFs::new(cx.executor());
525        let project_path = Path::new("/fake_project");
526
527        let file1_content = "one\ntwo\nthree\nfour\nfive\n";
528        let file2_content = "aaa\nbbb\nccc\nddd\neee\n";
529
530        fs.insert_tree(
531            project_path,
532            json!({
533                "file1.txt": file1_content,
534                "file2.txt": file2_content,
535            }),
536        )
537        .await;
538
539        let fs = fs as Arc<dyn Fs>;
540        let project = Project::test(fs.clone(), [project_path], cx).await;
541        let worktree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
542
543        // chunk that is already newline-aligned
544        let search_results = vec![SearchResult {
545            worktree: worktree.clone(),
546            path: Path::new("file1.txt").into(),
547            range: 0..file1_content.find("four").unwrap(),
548            score: 0.5,
549            query_index: 0,
550        }];
551        assert_eq!(
552            SemanticDb::load_results(search_results, &fs, &cx.to_async())
553                .await
554                .unwrap(),
555            &[LoadedSearchResult {
556                path: Path::new("file1.txt").into(),
557                full_path: "fake_project/file1.txt".into(),
558                excerpt_content: "one\ntwo\nthree\n".into(),
559                row_range: 0..=2,
560                query_index: 0,
561            }]
562        );
563
564        // chunk that is *not* newline-aligned
565        let search_results = vec![SearchResult {
566            worktree: worktree.clone(),
567            path: Path::new("file1.txt").into(),
568            range: file1_content.find("two").unwrap() + 1..file1_content.find("four").unwrap() + 2,
569            score: 0.5,
570            query_index: 0,
571        }];
572        assert_eq!(
573            SemanticDb::load_results(search_results, &fs, &cx.to_async())
574                .await
575                .unwrap(),
576            &[LoadedSearchResult {
577                path: Path::new("file1.txt").into(),
578                full_path: "fake_project/file1.txt".into(),
579                excerpt_content: "two\nthree\nfour\n".into(),
580                row_range: 1..=3,
581                query_index: 0,
582            }]
583        );
584
585        // chunks that are adjacent
586
587        let search_results = vec![
588            SearchResult {
589                worktree: worktree.clone(),
590                path: Path::new("file1.txt").into(),
591                range: file1_content.find("two").unwrap()..file1_content.len(),
592                score: 0.6,
593                query_index: 0,
594            },
595            SearchResult {
596                worktree: worktree.clone(),
597                path: Path::new("file1.txt").into(),
598                range: 0..file1_content.find("two").unwrap(),
599                score: 0.5,
600                query_index: 1,
601            },
602            SearchResult {
603                worktree: worktree.clone(),
604                path: Path::new("file2.txt").into(),
605                range: 0..file2_content.len(),
606                score: 0.8,
607                query_index: 1,
608            },
609        ];
610        assert_eq!(
611            SemanticDb::load_results(search_results, &fs, &cx.to_async())
612                .await
613                .unwrap(),
614            &[
615                LoadedSearchResult {
616                    path: Path::new("file2.txt").into(),
617                    full_path: "fake_project/file2.txt".into(),
618                    excerpt_content: file2_content.into(),
619                    row_range: 0..=4,
620                    query_index: 1,
621                },
622                LoadedSearchResult {
623                    path: Path::new("file1.txt").into(),
624                    full_path: "fake_project/file1.txt".into(),
625                    excerpt_content: file1_content.into(),
626                    row_range: 0..=4,
627                    query_index: 0,
628                }
629            ]
630        );
631    }
632}