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 if prev_result.full_path == full_path {
179 if *prev_result.row_range.end() + 1 == start_row {
180 prev_result.row_range = *prev_result.row_range.start()..=end_row;
181 prev_result.excerpt_content.push_str(&excerpt_content);
182 continue;
183 }
184 }
185 }
186
187 loaded_results.push(LoadedSearchResult {
188 path: result.path,
189 full_path,
190 excerpt_content,
191 row_range: start_row..=end_row,
192 query_index,
193 });
194 }
195
196 for result in &mut loaded_results {
197 while result.excerpt_content.ends_with("\n\n") {
198 result.excerpt_content.pop();
199 result.row_range =
200 *result.row_range.start()..=result.row_range.end().saturating_sub(1)
201 }
202 }
203
204 Ok(loaded_results)
205 }
206
207 pub fn project_index(
208 &mut self,
209 project: Entity<Project>,
210 _cx: &mut App,
211 ) -> Option<Entity<ProjectIndex>> {
212 self.project_indices.get(&project.downgrade()).cloned()
213 }
214
215 pub fn remaining_summaries(
216 &self,
217 project: &WeakEntity<Project>,
218 cx: &mut App,
219 ) -> Option<usize> {
220 self.project_indices.get(project).map(|project_index| {
221 project_index.update(cx, |project_index, cx| {
222 project_index.remaining_summaries(cx)
223 })
224 })
225 }
226
227 pub fn create_project_index(
228 &mut self,
229 project: Entity<Project>,
230 cx: &mut App,
231 ) -> Entity<ProjectIndex> {
232 let project_index = cx.new(|cx| {
233 ProjectIndex::new(
234 project.clone(),
235 self.db_connection.clone().unwrap(),
236 self.embedding_provider.clone(),
237 cx,
238 )
239 });
240
241 let project_weak = project.downgrade();
242 self.project_indices
243 .insert(project_weak.clone(), project_index.clone());
244
245 cx.observe_release(&project, move |_, cx| {
246 if cx.has_global::<SemanticDb>() {
247 cx.update_global::<SemanticDb, _>(|this, _| {
248 this.project_indices.remove(&project_weak);
249 })
250 }
251 })
252 .detach();
253
254 project_index
255 }
256}
257
258impl Drop for SemanticDb {
259 fn drop(&mut self) {
260 self.db_connection.take().unwrap().prepare_for_closing();
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267 use chunking::Chunk;
268 use embedding_index::{ChunkedFile, EmbeddingIndex};
269 use feature_flags::FeatureFlagAppExt;
270 use fs::FakeFs;
271 use futures::{FutureExt, future::BoxFuture};
272 use gpui::TestAppContext;
273 use indexing::IndexingEntrySet;
274 use language::language_settings::AllLanguageSettings;
275 use project::{Project, ProjectEntryId};
276 use serde_json::json;
277 use settings::SettingsStore;
278 use smol::channel;
279 use std::{future, path::Path, sync::Arc};
280 use util::path;
281
282 fn init_test(cx: &mut TestAppContext) {
283 zlog::init_test();
284
285 cx.update(|cx| {
286 let store = SettingsStore::test(cx);
287 cx.set_global(store);
288 language::init(cx);
289 cx.update_flags(false, vec![]);
290 Project::init_settings(cx);
291 SettingsStore::update(cx, |store, cx| {
292 store.update_user_settings::<AllLanguageSettings>(cx, |_| {});
293 });
294 });
295 }
296
297 pub struct TestEmbeddingProvider {
298 batch_size: usize,
299 compute_embedding: Box<dyn Fn(&str) -> Result<Embedding> + Send + Sync>,
300 }
301
302 impl TestEmbeddingProvider {
303 pub fn new(
304 batch_size: usize,
305 compute_embedding: impl 'static + Fn(&str) -> Result<Embedding> + Send + Sync,
306 ) -> Self {
307 Self {
308 batch_size,
309 compute_embedding: Box::new(compute_embedding),
310 }
311 }
312 }
313
314 impl EmbeddingProvider for TestEmbeddingProvider {
315 fn embed<'a>(
316 &'a self,
317 texts: &'a [TextToEmbed<'a>],
318 ) -> BoxFuture<'a, Result<Vec<Embedding>>> {
319 let embeddings = texts
320 .iter()
321 .map(|to_embed| (self.compute_embedding)(to_embed.text))
322 .collect();
323 future::ready(embeddings).boxed()
324 }
325
326 fn batch_size(&self) -> usize {
327 self.batch_size
328 }
329 }
330
331 #[gpui::test]
332 async fn test_search(cx: &mut TestAppContext) {
333 cx.executor().allow_parking();
334
335 init_test(cx);
336
337 cx.update(|cx| {
338 // This functionality is staff-flagged.
339 cx.update_flags(true, vec![]);
340 });
341
342 let temp_dir = tempfile::tempdir().unwrap();
343
344 let mut semantic_index = SemanticDb::new(
345 temp_dir.path().into(),
346 Arc::new(TestEmbeddingProvider::new(16, |text| {
347 let mut embedding = vec![0f32; 2];
348 // if the text contains garbage, give it a 1 in the first dimension
349 if text.contains("garbage in") {
350 embedding[0] = 0.9;
351 } else {
352 embedding[0] = -0.9;
353 }
354
355 if text.contains("garbage out") {
356 embedding[1] = 0.9;
357 } else {
358 embedding[1] = -0.9;
359 }
360
361 Ok(Embedding::new(embedding))
362 })),
363 &mut cx.to_async(),
364 )
365 .await
366 .unwrap();
367
368 let fs = FakeFs::new(cx.executor());
369 let project_path = Path::new("/fake_project");
370
371 fs.insert_tree(
372 project_path,
373 json!({
374 "fixture": {
375 "main.rs": include_str!("../fixture/main.rs"),
376 "needle.md": include_str!("../fixture/needle.md"),
377 }
378 }),
379 )
380 .await;
381
382 let project = Project::test(fs, [project_path], cx).await;
383
384 let project_index = cx.update(|cx| {
385 let language_registry = project.read(cx).languages().clone();
386 let node_runtime = project.read(cx).node_runtime().unwrap().clone();
387 languages::init(language_registry, node_runtime, cx);
388 semantic_index.create_project_index(project.clone(), cx)
389 });
390
391 cx.run_until_parked();
392 while cx
393 .update(|cx| semantic_index.remaining_summaries(&project.downgrade(), cx))
394 .unwrap()
395 > 0
396 {
397 cx.run_until_parked();
398 }
399
400 let results = cx
401 .update(|cx| {
402 let project_index = project_index.read(cx);
403 let query = "garbage in, garbage out";
404 project_index.search(vec![query.into()], 4, cx)
405 })
406 .await
407 .unwrap();
408
409 assert!(
410 results.len() > 1,
411 "should have found some results, but only found {:?}",
412 results
413 );
414
415 for result in &results {
416 println!("result: {:?}", result.path);
417 println!("score: {:?}", result.score);
418 }
419
420 // Find result that is greater than 0.5
421 let search_result = results.iter().find(|result| result.score > 0.9).unwrap();
422
423 assert_eq!(
424 search_result.path.to_string_lossy(),
425 path!("fixture/needle.md")
426 );
427
428 let content = cx
429 .update(|cx| {
430 let worktree = search_result.worktree.read(cx);
431 let entry_abs_path = worktree.abs_path().join(&search_result.path);
432 let fs = project.read(cx).fs().clone();
433 cx.background_spawn(async move { fs.load(&entry_abs_path).await.unwrap() })
434 })
435 .await;
436
437 let range = search_result.range.clone();
438 let content = content[range.clone()].to_owned();
439
440 assert!(content.contains("garbage in, garbage out"));
441 }
442
443 #[gpui::test]
444 async fn test_embed_files(cx: &mut TestAppContext) {
445 cx.executor().allow_parking();
446
447 let provider = Arc::new(TestEmbeddingProvider::new(3, |text| {
448 anyhow::ensure!(
449 !text.contains('g'),
450 "cannot embed text containing a 'g' character"
451 );
452 Ok(Embedding::new(
453 ('a'..='z')
454 .map(|char| text.chars().filter(|c| *c == char).count() as f32)
455 .collect(),
456 ))
457 }));
458
459 let (indexing_progress_tx, _) = channel::unbounded();
460 let indexing_entries = Arc::new(IndexingEntrySet::new(indexing_progress_tx));
461
462 let (chunked_files_tx, chunked_files_rx) = channel::unbounded::<ChunkedFile>();
463 chunked_files_tx
464 .send_blocking(ChunkedFile {
465 path: Path::new("test1.md").into(),
466 mtime: None,
467 handle: indexing_entries.insert(ProjectEntryId::from_proto(0)),
468 text: "abcdefghijklmnop".to_string(),
469 chunks: [0..4, 4..8, 8..12, 12..16]
470 .into_iter()
471 .map(|range| Chunk {
472 range,
473 digest: Default::default(),
474 })
475 .collect(),
476 })
477 .unwrap();
478 chunked_files_tx
479 .send_blocking(ChunkedFile {
480 path: Path::new("test2.md").into(),
481 mtime: None,
482 handle: indexing_entries.insert(ProjectEntryId::from_proto(1)),
483 text: "qrstuvwxyz".to_string(),
484 chunks: [0..4, 4..8, 8..10]
485 .into_iter()
486 .map(|range| Chunk {
487 range,
488 digest: Default::default(),
489 })
490 .collect(),
491 })
492 .unwrap();
493 chunked_files_tx.close();
494
495 let embed_files_task =
496 cx.update(|cx| EmbeddingIndex::embed_files(provider.clone(), chunked_files_rx, cx));
497 embed_files_task.task.await.unwrap();
498
499 let embedded_files_rx = embed_files_task.files;
500 let mut embedded_files = Vec::new();
501 while let Ok((embedded_file, _)) = embedded_files_rx.recv().await {
502 embedded_files.push(embedded_file);
503 }
504
505 assert_eq!(embedded_files.len(), 1);
506 assert_eq!(embedded_files[0].path.as_ref(), Path::new("test2.md"));
507 assert_eq!(
508 embedded_files[0]
509 .chunks
510 .iter()
511 .map(|embedded_chunk| { embedded_chunk.embedding.clone() })
512 .collect::<Vec<Embedding>>(),
513 vec![
514 (provider.compute_embedding)("qrst").unwrap(),
515 (provider.compute_embedding)("uvwx").unwrap(),
516 (provider.compute_embedding)("yz").unwrap(),
517 ],
518 );
519 }
520
521 #[gpui::test]
522 async fn test_load_search_results(cx: &mut TestAppContext) {
523 init_test(cx);
524
525 let fs = FakeFs::new(cx.executor());
526 let project_path = Path::new("/fake_project");
527
528 let file1_content = "one\ntwo\nthree\nfour\nfive\n";
529 let file2_content = "aaa\nbbb\nccc\nddd\neee\n";
530
531 fs.insert_tree(
532 project_path,
533 json!({
534 "file1.txt": file1_content,
535 "file2.txt": file2_content,
536 }),
537 )
538 .await;
539
540 let fs = fs as Arc<dyn Fs>;
541 let project = Project::test(fs.clone(), [project_path], cx).await;
542 let worktree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
543
544 // chunk that is already newline-aligned
545 let search_results = vec![SearchResult {
546 worktree: worktree.clone(),
547 path: Path::new("file1.txt").into(),
548 range: 0..file1_content.find("four").unwrap(),
549 score: 0.5,
550 query_index: 0,
551 }];
552 assert_eq!(
553 SemanticDb::load_results(search_results, &fs, &cx.to_async())
554 .await
555 .unwrap(),
556 &[LoadedSearchResult {
557 path: Path::new("file1.txt").into(),
558 full_path: "fake_project/file1.txt".into(),
559 excerpt_content: "one\ntwo\nthree\n".into(),
560 row_range: 0..=2,
561 query_index: 0,
562 }]
563 );
564
565 // chunk that is *not* newline-aligned
566 let search_results = vec![SearchResult {
567 worktree: worktree.clone(),
568 path: Path::new("file1.txt").into(),
569 range: file1_content.find("two").unwrap() + 1..file1_content.find("four").unwrap() + 2,
570 score: 0.5,
571 query_index: 0,
572 }];
573 assert_eq!(
574 SemanticDb::load_results(search_results, &fs, &cx.to_async())
575 .await
576 .unwrap(),
577 &[LoadedSearchResult {
578 path: Path::new("file1.txt").into(),
579 full_path: "fake_project/file1.txt".into(),
580 excerpt_content: "two\nthree\nfour\n".into(),
581 row_range: 1..=3,
582 query_index: 0,
583 }]
584 );
585
586 // chunks that are adjacent
587
588 let search_results = vec![
589 SearchResult {
590 worktree: worktree.clone(),
591 path: Path::new("file1.txt").into(),
592 range: file1_content.find("two").unwrap()..file1_content.len(),
593 score: 0.6,
594 query_index: 0,
595 },
596 SearchResult {
597 worktree: worktree.clone(),
598 path: Path::new("file1.txt").into(),
599 range: 0..file1_content.find("two").unwrap(),
600 score: 0.5,
601 query_index: 1,
602 },
603 SearchResult {
604 worktree: worktree.clone(),
605 path: Path::new("file2.txt").into(),
606 range: 0..file2_content.len(),
607 score: 0.8,
608 query_index: 1,
609 },
610 ];
611 assert_eq!(
612 SemanticDb::load_results(search_results, &fs, &cx.to_async())
613 .await
614 .unwrap(),
615 &[
616 LoadedSearchResult {
617 path: Path::new("file2.txt").into(),
618 full_path: "fake_project/file2.txt".into(),
619 excerpt_content: file2_content.into(),
620 row_range: 0..=4,
621 query_index: 1,
622 },
623 LoadedSearchResult {
624 path: Path::new("file1.txt").into(),
625 full_path: "fake_project/file1.txt".into(),
626 excerpt_content: file1_content.into(),
627 row_range: 0..=4,
628 query_index: 0,
629 }
630 ]
631 );
632 }
633}