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_spawn(async move {
46 std::fs::create_dir_all(&db_path)?;
47 unsafe {
48 heed::EnvOpenOptions::new()
49 .map_size(1024 * 1024 * 1024)
50 .max_dbs(3000)
51 .open(db_path)
52 }
53 })
54 .await
55 .context("opening database connection")?;
56
57 cx.update(|cx| {
58 cx.observe_new(
59 |workspace: &mut Workspace, _window, cx: &mut Context<Workspace>| {
60 let project = workspace.project().clone();
61
62 if cx.has_global::<SemanticDb>() {
63 cx.update_global::<SemanticDb, _>(|this, cx| {
64 this.create_project_index(project, cx);
65 })
66 } else {
67 log::info!("No SemanticDb, skipping project index")
68 }
69 },
70 )
71 .detach();
72 })
73 .ok();
74
75 Ok(SemanticDb {
76 db_connection: Some(db_connection),
77 embedding_provider,
78 project_indices: HashMap::default(),
79 })
80 }
81
82 pub async fn load_results(
83 mut results: Vec<SearchResult>,
84 fs: &Arc<dyn Fs>,
85 cx: &AsyncApp,
86 ) -> Result<Vec<LoadedSearchResult>> {
87 let mut max_scores_by_path = HashMap::<_, (f32, usize)>::default();
88 for result in &results {
89 let (score, query_index) = max_scores_by_path
90 .entry((result.worktree.clone(), result.path.clone()))
91 .or_default();
92 if result.score > *score {
93 *score = result.score;
94 *query_index = result.query_index;
95 }
96 }
97
98 results.sort_by(|a, b| {
99 let max_score_a = max_scores_by_path[&(a.worktree.clone(), a.path.clone())].0;
100 let max_score_b = max_scores_by_path[&(b.worktree.clone(), b.path.clone())].0;
101 max_score_b
102 .partial_cmp(&max_score_a)
103 .unwrap_or(Ordering::Equal)
104 .then_with(|| a.worktree.entity_id().cmp(&b.worktree.entity_id()))
105 .then_with(|| a.path.cmp(&b.path))
106 .then_with(|| a.range.start.cmp(&b.range.start))
107 });
108
109 let mut last_loaded_file: Option<(Entity<Worktree>, Arc<Path>, PathBuf, String)> = None;
110 let mut loaded_results = Vec::<LoadedSearchResult>::new();
111 for result in results {
112 let full_path;
113 let file_content;
114 if let Some(last_loaded_file) =
115 last_loaded_file
116 .as_ref()
117 .filter(|(last_worktree, last_path, _, _)| {
118 last_worktree == &result.worktree && last_path == &result.path
119 })
120 {
121 full_path = last_loaded_file.2.clone();
122 file_content = &last_loaded_file.3;
123 } else {
124 let output = result.worktree.read_with(cx, |worktree, _cx| {
125 let entry_abs_path = worktree.abs_path().join(&result.path);
126 let mut entry_full_path = PathBuf::from(worktree.root_name());
127 entry_full_path.push(&result.path);
128 let file_content = async {
129 let entry_abs_path = entry_abs_path;
130 fs.load(&entry_abs_path).await
131 };
132 (entry_full_path, file_content)
133 })?;
134 full_path = output.0;
135 let Some(content) = output.1.await.log_err() else {
136 continue;
137 };
138 last_loaded_file = Some((
139 result.worktree.clone(),
140 result.path.clone(),
141 full_path.clone(),
142 content,
143 ));
144 file_content = &last_loaded_file.as_ref().unwrap().3;
145 };
146
147 let query_index = max_scores_by_path[&(result.worktree.clone(), result.path.clone())].1;
148
149 let mut range_start = result.range.start.min(file_content.len());
150 let mut range_end = result.range.end.min(file_content.len());
151 while !file_content.is_char_boundary(range_start) {
152 range_start += 1;
153 }
154 while !file_content.is_char_boundary(range_end) {
155 range_end += 1;
156 }
157
158 let start_row = file_content[0..range_start].matches('\n').count() as u32;
159 let mut end_row = file_content[0..range_end].matches('\n').count() as u32;
160 let start_line_byte_offset = file_content[0..range_start]
161 .rfind('\n')
162 .map(|pos| pos + 1)
163 .unwrap_or_default();
164 let mut end_line_byte_offset = range_end;
165 if file_content[..end_line_byte_offset].ends_with('\n') {
166 end_row -= 1;
167 } else {
168 end_line_byte_offset = file_content[range_end..]
169 .find('\n')
170 .map(|pos| range_end + pos + 1)
171 .unwrap_or_else(|| file_content.len());
172 }
173 let mut excerpt_content =
174 file_content[start_line_byte_offset..end_line_byte_offset].to_string();
175 LineEnding::normalize(&mut excerpt_content);
176
177 if let Some(prev_result) = loaded_results.last_mut()
178 && prev_result.full_path == full_path
179 && *prev_result.row_range.end() + 1 == start_row
180 {
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 loaded_results.push(LoadedSearchResult {
187 path: result.path,
188 full_path,
189 excerpt_content,
190 row_range: start_row..=end_row,
191 query_index,
192 });
193 }
194
195 for result in &mut loaded_results {
196 while result.excerpt_content.ends_with("\n\n") {
197 result.excerpt_content.pop();
198 result.row_range =
199 *result.row_range.start()..=result.row_range.end().saturating_sub(1)
200 }
201 }
202
203 Ok(loaded_results)
204 }
205
206 pub fn project_index(
207 &mut self,
208 project: Entity<Project>,
209 _cx: &mut App,
210 ) -> Option<Entity<ProjectIndex>> {
211 self.project_indices.get(&project.downgrade()).cloned()
212 }
213
214 pub fn remaining_summaries(
215 &self,
216 project: &WeakEntity<Project>,
217 cx: &mut App,
218 ) -> Option<usize> {
219 self.project_indices.get(project).map(|project_index| {
220 project_index.update(cx, |project_index, cx| {
221 project_index.remaining_summaries(cx)
222 })
223 })
224 }
225
226 pub fn create_project_index(
227 &mut self,
228 project: Entity<Project>,
229 cx: &mut App,
230 ) -> Entity<ProjectIndex> {
231 let project_index = cx.new(|cx| {
232 ProjectIndex::new(
233 project.clone(),
234 self.db_connection.clone().unwrap(),
235 self.embedding_provider.clone(),
236 cx,
237 )
238 });
239
240 let project_weak = project.downgrade();
241 self.project_indices
242 .insert(project_weak.clone(), project_index.clone());
243
244 cx.observe_release(&project, move |_, cx| {
245 if cx.has_global::<SemanticDb>() {
246 cx.update_global::<SemanticDb, _>(|this, _| {
247 this.project_indices.remove(&project_weak);
248 })
249 }
250 })
251 .detach();
252
253 project_index
254 }
255}
256
257impl Drop for SemanticDb {
258 fn drop(&mut self) {
259 self.db_connection.take().unwrap().prepare_for_closing();
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266 use chunking::Chunk;
267 use embedding_index::{ChunkedFile, EmbeddingIndex};
268 use feature_flags::FeatureFlagAppExt;
269 use fs::FakeFs;
270 use futures::{FutureExt, future::BoxFuture};
271 use gpui::TestAppContext;
272 use indexing::IndexingEntrySet;
273 use language::language_settings::AllLanguageSettings;
274 use project::{Project, ProjectEntryId};
275 use serde_json::json;
276 use settings::SettingsStore;
277 use smol::channel;
278 use std::{future, path::Path, sync::Arc};
279 use util::path;
280
281 fn init_test(cx: &mut TestAppContext) {
282 zlog::init_test();
283
284 cx.update(|cx| {
285 let store = SettingsStore::test(cx);
286 cx.set_global(store);
287 language::init(cx);
288 cx.update_flags(false, vec![]);
289 Project::init_settings(cx);
290 SettingsStore::update(cx, |store, cx| {
291 store.update_user_settings::<AllLanguageSettings>(cx, |_| {});
292 });
293 });
294 }
295
296 pub struct TestEmbeddingProvider {
297 batch_size: usize,
298 compute_embedding: Box<dyn Fn(&str) -> Result<Embedding> + Send + Sync>,
299 }
300
301 impl TestEmbeddingProvider {
302 pub fn new(
303 batch_size: usize,
304 compute_embedding: impl 'static + Fn(&str) -> Result<Embedding> + Send + Sync,
305 ) -> Self {
306 Self {
307 batch_size,
308 compute_embedding: Box::new(compute_embedding),
309 }
310 }
311 }
312
313 impl EmbeddingProvider for TestEmbeddingProvider {
314 fn embed<'a>(
315 &'a self,
316 texts: &'a [TextToEmbed<'a>],
317 ) -> BoxFuture<'a, Result<Vec<Embedding>>> {
318 let embeddings = texts
319 .iter()
320 .map(|to_embed| (self.compute_embedding)(to_embed.text))
321 .collect();
322 future::ready(embeddings).boxed()
323 }
324
325 fn batch_size(&self) -> usize {
326 self.batch_size
327 }
328 }
329
330 #[gpui::test]
331 async fn test_search(cx: &mut TestAppContext) {
332 cx.executor().allow_parking();
333
334 init_test(cx);
335
336 cx.update(|cx| {
337 // This functionality is staff-flagged.
338 cx.update_flags(true, vec![]);
339 });
340
341 let temp_dir = tempfile::tempdir().unwrap();
342
343 let mut semantic_index = SemanticDb::new(
344 temp_dir.path().into(),
345 Arc::new(TestEmbeddingProvider::new(16, |text| {
346 let mut embedding = vec![0f32; 2];
347 // if the text contains garbage, give it a 1 in the first dimension
348 if text.contains("garbage in") {
349 embedding[0] = 0.9;
350 } else {
351 embedding[0] = -0.9;
352 }
353
354 if text.contains("garbage out") {
355 embedding[1] = 0.9;
356 } else {
357 embedding[1] = -0.9;
358 }
359
360 Ok(Embedding::new(embedding))
361 })),
362 &mut cx.to_async(),
363 )
364 .await
365 .unwrap();
366
367 let fs = FakeFs::new(cx.executor());
368 let project_path = Path::new("/fake_project");
369
370 fs.insert_tree(
371 project_path,
372 json!({
373 "fixture": {
374 "main.rs": include_str!("../fixture/main.rs"),
375 "needle.md": include_str!("../fixture/needle.md"),
376 }
377 }),
378 )
379 .await;
380
381 let project = Project::test(fs, [project_path], cx).await;
382
383 let project_index = cx.update(|cx| {
384 let language_registry = project.read(cx).languages().clone();
385 let node_runtime = project.read(cx).node_runtime().unwrap().clone();
386 languages::init(language_registry, node_runtime, cx);
387 semantic_index.create_project_index(project.clone(), cx)
388 });
389
390 cx.run_until_parked();
391 while cx
392 .update(|cx| semantic_index.remaining_summaries(&project.downgrade(), cx))
393 .unwrap()
394 > 0
395 {
396 cx.run_until_parked();
397 }
398
399 let results = cx
400 .update(|cx| {
401 let project_index = project_index.read(cx);
402 let query = "garbage in, garbage out";
403 project_index.search(vec![query.into()], 4, cx)
404 })
405 .await
406 .unwrap();
407
408 assert!(
409 results.len() > 1,
410 "should have found some results, but only found {:?}",
411 results
412 );
413
414 for result in &results {
415 println!("result: {:?}", result.path);
416 println!("score: {:?}", result.score);
417 }
418
419 // Find result that is greater than 0.5
420 let search_result = results.iter().find(|result| result.score > 0.9).unwrap();
421
422 assert_eq!(
423 search_result.path.to_string_lossy(),
424 path!("fixture/needle.md")
425 );
426
427 let content = cx
428 .update(|cx| {
429 let worktree = search_result.worktree.read(cx);
430 let entry_abs_path = worktree.abs_path().join(&search_result.path);
431 let fs = project.read(cx).fs().clone();
432 cx.background_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].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 anyhow::ensure!(
448 !text.contains('g'),
449 "cannot embed text containing a 'g' character"
450 );
451 Ok(Embedding::new(
452 ('a'..='z')
453 .map(|char| text.chars().filter(|c| *c == char).count() as f32)
454 .collect(),
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}