Elffuss BraidHub

kikocis/continue public

eaabf65a9f8d · 22.2 KiBRawPermalink
1import * as fs from "fs/promises";
2
3import { ConfigHandler } from "../config/ConfigHandler.js";
4import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
5import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
6import type { IMessenger } from "../protocol/messenger";
7import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
8import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
9import { Telemetry } from "../util/posthog.js";
10import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
11
12import { ContinueServerClient } from "../continueServer/stubs/client";
13import { LLMError } from "../llm/index.js";
14import { getRootCause } from "../util/errors.js";
15import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
16import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
17import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
18import { LanceDbIndex } from "./LanceDbIndex.js";
19import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
20import {
21 CodebaseIndex,
22 IndexResultType,
23 PathAndCacheKey,
24 RefreshIndexResults,
25} from "./types.js";
26import { walkDirAsync } from "./walkDir.js";
27
28export class PauseToken {
29 constructor(private _paused: boolean) {}
30
31 set paused(value: boolean) {
32 this._paused = value;
33 }
34
35 get paused(): boolean {
36 return this._paused;
37 }
38}
39
40export class CodebaseIndexer {
41 /**
42 * We batch for two reasons:
43 * - To limit memory usage for indexes that perform computations locally, e.g. FTS
44 * - To make as few requests as possible to the embeddings providers
45 */
46 filesPerBatch = 200;
47 private indexingCancellationController: AbortController | undefined;
48 private codebaseIndexingState: IndexingProgressUpdate;
49 private readonly pauseToken: PauseToken;
50
51 private getUserFriendlyIndexName(artifactId: string): string {
52 if (artifactId === FullTextSearchCodebaseIndex.artifactId)
53 return "Full text search";
54 if (artifactId === CodeSnippetsCodebaseIndex.artifactId)
55 return "Code snippets";
56 if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking";
57 if (artifactId.startsWith("vectordb")) return "Embedding";
58 return artifactId; // fallback to original
59 }
60
61 // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
62 // e.g. a `SQLITE_BUSY` error.
63 errorsRegexesToClearIndexesOn = [
64 /Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/,
65 /SQLITE_CONSTRAINT/,
66 /SQLITE_ERROR/,
67 /SQLITE_CORRUPT/,
68 /SQLITE_IOERR/,
69 /SQLITE_FULL/,
70 ];
71
72 constructor(
73 private readonly configHandler: ConfigHandler,
74 protected readonly ide: IDE,
75 private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
76 initialPaused: boolean = false,
77 ) {
78 this.codebaseIndexingState = {
79 status: "loading",
80 desc: "loading",
81 progress: 0,
82 };
83
84 // Initialize pause token
85 this.pauseToken = new PauseToken(initialPaused);
86 }
87
88 set paused(value: boolean) {
89 this.pauseToken.paused = value;
90 }
91
92 get paused(): boolean {
93 return this.pauseToken.paused;
94 }
95
96 async clearIndexes() {
97 const sqliteFilepath = getIndexSqlitePath();
98 const lanceDbFolder = getLanceDbPath();
99
100 try {
101 await fs.unlink(sqliteFilepath);
102 } catch (error) {
103 console.error(`Error deleting ${sqliteFilepath} folder: ${error}`);
104 }
105
106 try {
107 await fs.rm(lanceDbFolder, { recursive: true, force: true });
108 } catch (error) {
109 console.error(`Error deleting ${lanceDbFolder}: ${error}`);
110 }
111 }
112
113 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
114 const { config } = await this.configHandler.loadConfig();
115 if (!config) {
116 return [];
117 }
118
119 const embeddingsModel = config.selectedModelByRole.embed;
120 if (!embeddingsModel) {
121 return [];
122 }
123
124 const ideSettings = await this.ide.getIdeSettings();
125 if (!ideSettings) {
126 return [];
127 }
128 const continueServerClient = new ContinueServerClient(
129 ideSettings.remoteConfigServerUrl,
130 ideSettings.userToken,
131 );
132 if (!continueServerClient) {
133 return [];
134 }
135
136 const indexes: CodebaseIndex[] = [
137 new ChunkCodebaseIndex(
138 this.ide.readFile.bind(this.ide),
139 continueServerClient,
140 embeddingsModel.maxEmbeddingChunkSize,
141 ), // Chunking must come first
142 ];
143
144 const lanceDbIndex = await LanceDbIndex.create(
145 embeddingsModel,
146 this.ide.readFile.bind(this.ide),
147 );
148
149 if (lanceDbIndex) {
150 indexes.push(lanceDbIndex);
151 }
152
153 indexes.push(
154 new FullTextSearchCodebaseIndex(),
155 new CodeSnippetsCodebaseIndex(this.ide),
156 );
157
158 return indexes;
159 }
160
161 private totalIndexOps(results: RefreshIndexResults): number {
162 return (
163 results.compute.length +
164 results.del.length +
165 results.addTag.length +
166 results.removeTag.length
167 );
168 }
169
170 private singleFileIndexOps(
171 results: RefreshIndexResults,
172 lastUpdated: PathAndCacheKey[],
173 filePath: string,
174 ): [RefreshIndexResults, PathAndCacheKey[]] {
175 const filterFn = (item: PathAndCacheKey) => item.path === filePath;
176 const compute = results.compute.filter(filterFn);
177 const del = results.del.filter(filterFn);
178 const addTag = results.addTag.filter(filterFn);
179 const removeTag = results.removeTag.filter(filterFn);
180 const newResults = {
181 compute,
182 del,
183 addTag,
184 removeTag,
185 };
186 const newLastUpdated = lastUpdated.filter(filterFn);
187 return [newResults, newLastUpdated];
188 }
189
190 public async refreshFile(
191 file: string,
192 workspaceDirs: string[],
193 ): Promise<void> {
194 if (this.pauseToken.paused) {
195 // NOTE: by returning here, there is a chance that while paused a file is modified and
196 // then after unpausing the file is not reindexed
197 return;
198 }
199 const { foundInDir } = findUriInDirs(file, workspaceDirs);
200 if (!foundInDir) {
201 return;
202 }
203 const branch = await this.ide.getBranch(foundInDir);
204 const repoName = await this.ide.getRepoName(foundInDir);
205 const indexesToBuild = await this.getIndexesToBuild();
206 const stats = await this.ide.getFileStats([file]);
207 const filePath = Object.keys(stats)[0];
208 for (const index of indexesToBuild) {
209 const tag = {
210 directory: foundInDir,
211 branch,
212 artifactId: index.artifactId,
213 };
214 const [fullResults, fullLastUpdated, markComplete] =
215 await getComputeDeleteAddRemove(
216 tag,
217 { ...stats },
218 (filepath) => this.ide.readFile(filepath),
219 repoName,
220 );
221
222 const [results, lastUpdated] = this.singleFileIndexOps(
223 fullResults,
224 fullLastUpdated,
225 filePath,
226 );
227 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
228 if (this.totalIndexOps(results) + lastUpdated.length === 0) {
229 continue;
230 }
231
232 for await (const _ of index.update(
233 tag,
234 results,
235 markComplete,
236 repoName,
237 )) {
238 }
239 }
240 }
241
242 private async *refreshFiles(
243 files: string[],
244 ): AsyncGenerator<IndexingProgressUpdate> {
245 let progress = 0;
246 if (files.length === 0) {
247 yield {
248 progress: 1,
249 desc: "Indexing Complete",
250 status: "done",
251 };
252 }
253
254 const workspaceDirs = await this.ide.getWorkspaceDirs();
255
256 const progressPer = 1 / files.length;
257 try {
258 for (const file of files) {
259 yield {
260 progress,
261 desc: `Indexing file ${file}...`,
262 status: "indexing",
263 };
264 await this.refreshFile(file, workspaceDirs);
265
266 progress += progressPer;
267
268 if (this.pauseToken.paused) {
269 yield* this.yieldUpdateAndPause();
270 }
271 }
272
273 yield {
274 progress: 1,
275 desc: "Indexing Complete",
276 status: "done",
277 };
278 } catch (err) {
279 yield this.handleErrorAndGetProgressUpdate(err);
280 }
281 }
282
283 async *refreshDirs(
284 dirs: string[],
285 abortSignal: AbortSignal,
286 ): AsyncGenerator<IndexingProgressUpdate> {
287 let progress = 0;
288
289 if (dirs.length === 0) {
290 yield {
291 progress: 1,
292 desc: "Nothing to index",
293 status: "done",
294 };
295 return;
296 }
297
298 const { config } = await this.configHandler.loadConfig();
299 if (!config) {
300 return;
301 }
302 if (config.disableIndexing) {
303 yield {
304 progress,
305 desc: "Indexing is disabled in config.json",
306 status: "disabled",
307 };
308 return;
309 } else {
310 yield {
311 progress,
312 desc: "Starting indexing",
313 status: "loading",
314 };
315 }
316
317 // Wait until Git Extension has loaded to report progress
318 // so we don't appear stuck at 0% while waiting
319 await this.ide.getRepoName(dirs[0]);
320
321 yield {
322 progress,
323 desc: "Starting indexing...",
324 status: "loading",
325 };
326 const beginTime = Date.now();
327 let collectedWarnings: string[] = [];
328
329 for (const directory of dirs) {
330 const dirBasename = getUriPathBasename(directory);
331 yield {
332 progress,
333 desc: `Discovering files in ${dirBasename}...`,
334 status: "indexing",
335 };
336 const directoryFiles = [];
337 for await (const p of walkDirAsync(directory, this.ide, {
338 source: "codebase indexing: refresh dirs",
339 })) {
340 directoryFiles.push(p);
341 if (abortSignal.aborted) {
342 yield {
343 progress: 0,
344 desc: "Indexing cancelled",
345 status: "cancelled",
346 };
347 return;
348 }
349 if (this.pauseToken.paused) {
350 yield* this.yieldUpdateAndPause();
351 }
352 }
353
354 const branch = await this.ide.getBranch(directory);
355 const repoName = await this.ide.getRepoName(directory);
356 let nextLogThreshold = 0;
357
358 for await (const updateDesc of this.indexFiles(
359 directory,
360 directoryFiles,
361 branch,
362 repoName,
363 )) {
364 // Handle pausing in this loop because it's the only one really taking time
365 if (abortSignal.aborted) {
366 yield {
367 progress: 0,
368 desc: "Indexing cancelled",
369 status: "cancelled",
370 };
371 return;
372 }
373 if (this.pauseToken.paused) {
374 yield* this.yieldUpdateAndPause();
375 }
376
377 // Collect warnings from indexFiles
378 if (updateDesc.warnings && updateDesc.warnings.length > 0) {
379 collectedWarnings = [...updateDesc.warnings];
380 }
381
382 yield updateDesc;
383 if (updateDesc.progress >= nextLogThreshold) {
384 // log progress every 2.5%
385 nextLogThreshold += 0.025;
386 this.logProgress(
387 beginTime,
388 Math.floor(directoryFiles.length * updateDesc.progress),
389 updateDesc.progress,
390 );
391 }
392 }
393 }
394
395 // Final completion message with preserved warnings
396 yield {
397 progress: 1,
398 desc:
399 collectedWarnings.length > 0
400 ? `Indexing completed with ${collectedWarnings.length} warning(s)`
401 : "Indexing Complete",
402 status: "done",
403 warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined,
404 };
405 this.logProgress(beginTime, 0, 1);
406 }
407
408 private handleErrorAndGetProgressUpdate(
409 err: unknown,
410 ): IndexingProgressUpdate {
411 console.log("error when indexing: ", err);
412 if (err instanceof Error) {
413 const cause = getRootCause(err);
414 if (cause instanceof LLMError) {
415 throw cause;
416 }
417 return this.errorToProgressUpdate(err);
418 }
419 return {
420 progress: 0,
421 desc: `Indexing failed: ${err}`,
422 status: "failed",
423 debugInfo: extractMinimalStackTraceInfo((err as any)?.stack),
424 };
425 }
426
427 private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
428 const cause = getRootCause(err);
429 let errMsg: string = `${cause}`;
430 let shouldClearIndexes = false;
431
432 // Check if any of the error regexes match
433 for (const regexStr of this.errorsRegexesToClearIndexesOn) {
434 const regex = new RegExp(regexStr);
435 const match = err.message.match(regex);
436
437 if (match !== null) {
438 shouldClearIndexes = true;
439 break;
440 }
441 }
442
443 return {
444 progress: 0,
445 desc: errMsg,
446 status: "failed",
447 shouldClearIndexes,
448 debugInfo: extractMinimalStackTraceInfo(err.stack),
449 };
450 }
451
452 private logProgress(
453 beginTime: number,
454 completedFileCount: number,
455 progress: number,
456 ) {
457 const timeTaken = Date.now() - beginTime;
458 const seconds = Math.round(timeTaken / 1000);
459 const progressPercentage = (progress * 100).toFixed(1);
460 const filesPerSec = (completedFileCount / seconds).toFixed(2);
461 // console.debug(
462 // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
463 // );
464 }
465
466 private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {
467 yield {
468 progress: 0,
469 desc: "Indexing Paused",
470 status: "paused",
471 };
472 while (this.pauseToken.paused) {
473 await new Promise((resolve) => setTimeout(resolve, 100));
474 }
475 }
476
477 /*
478 * Enables the indexing operation to be completed in batches, this is important in large
479 * repositories where indexing can quickly use up all the memory available
480 */
481 private *batchRefreshIndexResults(
482 results: RefreshIndexResults,
483 ): Generator<RefreshIndexResults> {
484 let curPos = 0;
485 while (
486 curPos < results.compute.length ||
487 curPos < results.del.length ||
488 curPos < results.addTag.length ||
489 curPos < results.removeTag.length
490 ) {
491 yield {
492 compute: results.compute.slice(curPos, curPos + this.filesPerBatch),
493 del: results.del.slice(curPos, curPos + this.filesPerBatch),
494 addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch),
495 removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch),
496 };
497 curPos += this.filesPerBatch;
498 }
499 }
500
501 private async *indexFiles(
502 directory: string,
503 files: string[],
504 branch: string,
505 repoName: string | undefined,
506 ): AsyncGenerator<IndexingProgressUpdate> {
507 const stats = await this.ide.getFileStats(files);
508 const indexesToBuild = await this.getIndexesToBuild();
509 let completedIndexCount = 0;
510 let progress = 0;
511 const warnings: string[] = [];
512
513 for (const codebaseIndex of indexesToBuild) {
514 const tag: IndexTag = {
515 directory,
516 branch,
517 artifactId: codebaseIndex.artifactId,
518 };
519 yield {
520 progress: progress,
521 desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
522 status: "indexing",
523 warnings: warnings.length > 0 ? [...warnings] : undefined,
524 };
525
526 try {
527 const [results, lastUpdated, markComplete] =
528 await getComputeDeleteAddRemove(
529 tag,
530 { ...stats },
531 (filepath) => this.ide.readFile(filepath),
532 repoName,
533 );
534 const totalOps = this.totalIndexOps(results);
535 let completedOps = 0;
536
537 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
538 if (totalOps > 0) {
539 for (const subResult of this.batchRefreshIndexResults(results)) {
540 try {
541 for await (const { desc } of codebaseIndex.update(
542 tag,
543 subResult,
544 markComplete,
545 repoName,
546 )) {
547 yield {
548 progress,
549 desc,
550 status: "indexing",
551 warnings: warnings.length > 0 ? [...warnings] : undefined,
552 };
553 }
554 completedOps +=
555 subResult.compute.length +
556 subResult.del.length +
557 subResult.addTag.length +
558 subResult.removeTag.length;
559 progress =
560 (completedIndexCount + completedOps / totalOps) *
561 (1 / indexesToBuild.length);
562 } catch (err) {
563 // Collect non-fatal errors as warnings and continue
564 const warningMsg =
565 err instanceof Error ? err.message : String(err);
566 const friendlyName = this.getUserFriendlyIndexName(
567 codebaseIndex.artifactId,
568 );
569 warnings.push(`${friendlyName}: ${warningMsg}`);
570 console.warn(`${friendlyName}: ${warningMsg}`, err);
571
572 // Complete this batch and continue with next
573 completedOps +=
574 subResult.compute.length +
575 subResult.del.length +
576 subResult.addTag.length +
577 subResult.removeTag.length;
578 progress =
579 (completedIndexCount + completedOps / totalOps) *
580 (1 / indexesToBuild.length);
581 }
582 }
583 }
584
585 await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
586 completedIndexCount += 1;
587 } catch (err) {
588 // Handle errors during planning phase
589 const cause = getRootCause(err as Error);
590 if (cause instanceof LLMError) {
591 // LLM errors are critical, re-throw them
592 throw cause;
593 }
594
595 // Collect planning errors as warnings and continue to next index
596 const errorMsg = err instanceof Error ? err.message : String(err);
597 const friendlyName = this.getUserFriendlyIndexName(
598 codebaseIndex.artifactId,
599 );
600 warnings.push(`${friendlyName}: ${errorMsg}`);
601 console.warn(
602 `Warning during ${codebaseIndex.artifactId} planning:`,
603 err,
604 );
605 completedIndexCount += 1;
606 progress = completedIndexCount * (1 / indexesToBuild.length);
607 }
608 }
609
610 // Final update with any collected warnings
611 if (warnings.length > 0) {
612 yield {
613 progress: 1,
614 desc: `Indexing completed with ${warnings.length} warning(s)`,
615 status: "done",
616 warnings: [...warnings],
617 };
618 }
619 }
620
621 // New methods using messenger directly
622
623 private updateProgress(update: IndexingProgressUpdate) {
624 this.codebaseIndexingState = update;
625 if (this.messenger) {
626 void this.messenger.request("indexProgress", update);
627 }
628 }
629
630 private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
631 console.debug(
632 "Indexing failed with error: ",
633 update.desc,
634 update.debugInfo,
635 );
636 void Telemetry.capture(
637 "indexing_error",
638 {
639 error: update.desc,
640 stack: update.debugInfo,
641 },
642 false,
643 );
644 }
645
646 /**
647 * We want to prevent sqlite concurrent write errors
648 * when there are 2 indexing happening from different windows.
649 * We want the other window to wait until the first window's indexing finishes.
650 * Incase the first window closes before indexing is finished,
651 * we want to unlock the IndexLock by checking the last timestamp.
652 */
653 private async *waitForDBIndex(): AsyncGenerator<IndexingProgressUpdate> {
654 let foundLock = await IndexLock.isLocked();
655 while (foundLock?.locked) {
656 if ((Date.now() - foundLock.timestamp) / 1000 > 10) {
657 console.log(`${foundLock.dirs} is not being indexed... unlocking`);
658 await IndexLock.unlock();
659 break;
660 }
661 console.log(`indexing ${foundLock.dirs}`);
662 yield {
663 progress: 0,
664 desc: "",
665 status: "waiting",
666 };
667 await new Promise((resolve) => setTimeout(resolve, 1000));
668 foundLock = await IndexLock.isLocked();
669 }
670 }
671
672 public async refreshCodebaseIndex(paths: string[]) {
673 if (this.indexingCancellationController) {
674 this.indexingCancellationController.abort();
675 }
676 this.indexingCancellationController = new AbortController();
677 for await (const update of this.waitForDBIndex()) {
678 this.updateProgress(update);
679 }
680
681 await IndexLock.lock(paths.join(", ")); // acquire the index lock to prevent multiple windows to begin indexing
682 const indexLockTimestampUpdateInterval = setInterval(
683 () => void IndexLock.updateTimestamp(),
684 5_000,
685 );
686
687 try {
688 for await (const update of this.refreshDirs(
689 paths,
690 this.indexingCancellationController.signal,
691 )) {
692 this.updateProgress(update);
693
694 if (update.status === "failed") {
695 await this.sendIndexingErrorTelemetry(update);
696 }
697 }
698 } catch (e: any) {
699 console.log(`Failed refreshing codebase index directories: ${e}`);
700 await this.handleIndexingError(e);
701 }
702
703 clearInterval(indexLockTimestampUpdateInterval); // interval will also be cleared when window closes before indexing is finished
704 await IndexLock.unlock();
705
706 // Directly refresh submenu items
707 if (this.messenger) {
708 this.messenger.send("refreshSubmenuItems", {
709 providers: "all",
710 });
711 }
712 this.indexingCancellationController = undefined;
713 }
714
715 public async refreshCodebaseIndexFiles(files: string[]) {
716 // Can be cancelled by codebase index but not vice versa
717 if (
718 this.indexingCancellationController &&
719 !this.indexingCancellationController.signal.aborted
720 ) {
721 return;
722 }
723 this.indexingCancellationController = new AbortController();
724 try {
725 for await (const update of this.refreshFiles(files)) {
726 this.updateProgress(update);
727
728 if (update.status === "failed") {
729 await this.sendIndexingErrorTelemetry(update);
730 }
731 }
732 } catch (e: any) {
733 console.log(`Failed refreshing codebase index files: ${e}`);
734 await this.handleIndexingError(e);
735 }
736
737 // Directly refresh submenu items
738 if (this.messenger) {
739 this.messenger.send("refreshSubmenuItems", {
740 providers: "all",
741 });
742 }
743 this.indexingCancellationController = undefined;
744 }
745
746 public async handleIndexingError(e: any) {
747 if (e instanceof LLMError && this.messenger) {
748 // Need to report this specific error to the IDE for special handling
749 void this.messenger.request("reportError", e);
750 }
751
752 // broadcast indexing error
753 const updateToSend: IndexingProgressUpdate = {
754 progress: 0,
755 status: "failed",
756 desc: e.message,
757 };
758
759 this.updateProgress(updateToSend);
760 void this.sendIndexingErrorTelemetry(updateToSend);
761 }
762
763 public get currentIndexingState(): IndexingProgressUpdate {
764 return this.codebaseIndexingState;
765 }
766}