Elffuss BraidHub

kikocis/continue public

d691089ac9f7 · 17.9 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 } 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 = 500;
47 private indexingCancellationController: AbortController | undefined;
48 private codebaseIndexingState: IndexingProgressUpdate;
49 private readonly pauseToken: PauseToken;
50
51 // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
52 // e.g. a `SQLITE_BUSY` error.
53 errorsRegexesToClearIndexesOn = [
54 /Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/,
55 /SQLITE_CONSTRAINT/,
56 /SQLITE_ERROR/,
57 /SQLITE_CORRUPT/,
58 /SQLITE_IOERR/,
59 /SQLITE_FULL/,
60 ];
61
62 constructor(
63 private readonly configHandler: ConfigHandler,
64 protected readonly ide: IDE,
65 private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
66 initialPaused: boolean = false,
67 ) {
68 this.codebaseIndexingState = {
69 status: "loading",
70 desc: "loading",
71 progress: 0,
72 };
73
74 // Initialize pause token
75 this.pauseToken = new PauseToken(initialPaused);
76 }
77
78 /**
79 * Set the paused state of the indexer
80 */
81 set paused(value: boolean) {
82 this.pauseToken.paused = value;
83 }
84
85 /**
86 * Get the current paused state of the indexer
87 */
88 get paused(): boolean {
89 return this.pauseToken.paused;
90 }
91
92 async clearIndexes() {
93 const sqliteFilepath = getIndexSqlitePath();
94 const lanceDbFolder = getLanceDbPath();
95
96 try {
97 await fs.unlink(sqliteFilepath);
98 } catch (error) {
99 console.error(`Error deleting ${sqliteFilepath} folder: ${error}`);
100 }
101
102 try {
103 await fs.rm(lanceDbFolder, { recursive: true, force: true });
104 } catch (error) {
105 console.error(`Error deleting ${lanceDbFolder}: ${error}`);
106 }
107 }
108
109 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
110 const { config } = await this.configHandler.loadConfig();
111 if (!config) {
112 return [];
113 }
114
115 const embeddingsModel = config.selectedModelByRole.embed;
116 if (!embeddingsModel) {
117 return [];
118 }
119
120 const ideSettings = await this.ide.getIdeSettings();
121 if (!ideSettings) {
122 return [];
123 }
124 const continueServerClient = new ContinueServerClient(
125 ideSettings.remoteConfigServerUrl,
126 ideSettings.userToken,
127 );
128 if (!continueServerClient) {
129 return [];
130 }
131
132 const indexes: CodebaseIndex[] = [
133 new ChunkCodebaseIndex(
134 this.ide.readFile.bind(this.ide),
135 continueServerClient,
136 embeddingsModel.maxEmbeddingChunkSize,
137 ), // Chunking must come first
138 ];
139
140 const lanceDbIndex = await LanceDbIndex.create(
141 embeddingsModel,
142 this.ide.readFile.bind(this.ide),
143 );
144
145 if (lanceDbIndex) {
146 indexes.push(lanceDbIndex);
147 }
148
149 indexes.push(
150 new FullTextSearchCodebaseIndex(),
151 new CodeSnippetsCodebaseIndex(this.ide),
152 );
153
154 return indexes;
155 }
156
157 private totalIndexOps(results: RefreshIndexResults): number {
158 return (
159 results.compute.length +
160 results.del.length +
161 results.addTag.length +
162 results.removeTag.length
163 );
164 }
165
166 private singleFileIndexOps(
167 results: RefreshIndexResults,
168 lastUpdated: PathAndCacheKey[],
169 filePath: string,
170 ): [RefreshIndexResults, PathAndCacheKey[]] {
171 const filterFn = (item: PathAndCacheKey) => item.path === filePath;
172 const compute = results.compute.filter(filterFn);
173 const del = results.del.filter(filterFn);
174 const addTag = results.addTag.filter(filterFn);
175 const removeTag = results.removeTag.filter(filterFn);
176 const newResults = {
177 compute,
178 del,
179 addTag,
180 removeTag,
181 };
182 const newLastUpdated = lastUpdated.filter(filterFn);
183 return [newResults, newLastUpdated];
184 }
185
186 public async refreshFile(
187 file: string,
188 workspaceDirs: string[],
189 ): Promise<void> {
190 if (this.pauseToken.paused) {
191 // NOTE: by returning here, there is a chance that while paused a file is modified and
192 // then after unpausing the file is not reindexed
193 return;
194 }
195 const { foundInDir } = findUriInDirs(file, workspaceDirs);
196 if (!foundInDir) {
197 return;
198 }
199 const branch = await this.ide.getBranch(foundInDir);
200 const repoName = await this.ide.getRepoName(foundInDir);
201 const indexesToBuild = await this.getIndexesToBuild();
202 const stats = await this.ide.getFileStats([file]);
203 const filePath = Object.keys(stats)[0];
204 for (const index of indexesToBuild) {
205 const tag = {
206 directory: foundInDir,
207 branch,
208 artifactId: index.artifactId,
209 };
210 const [fullResults, fullLastUpdated, markComplete] =
211 await getComputeDeleteAddRemove(
212 tag,
213 { ...stats },
214 (filepath) => this.ide.readFile(filepath),
215 repoName,
216 );
217
218 const [results, lastUpdated] = this.singleFileIndexOps(
219 fullResults,
220 fullLastUpdated,
221 filePath,
222 );
223 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
224 if (this.totalIndexOps(results) + lastUpdated.length === 0) {
225 continue;
226 }
227
228 for await (const _ of index.update(
229 tag,
230 results,
231 markComplete,
232 repoName,
233 )) {
234 }
235 }
236 }
237
238 async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
239 let progress = 0;
240 if (files.length === 0) {
241 yield {
242 progress: 1,
243 desc: "Indexing Complete",
244 status: "done",
245 };
246 }
247
248 const workspaceDirs = await this.ide.getWorkspaceDirs();
249
250 const progressPer = 1 / files.length;
251 try {
252 for (const file of files) {
253 yield {
254 progress,
255 desc: `Indexing file ${file}...`,
256 status: "indexing",
257 };
258 await this.refreshFile(file, workspaceDirs);
259
260 progress += progressPer;
261
262 if (this.pauseToken.paused) {
263 yield* this.yieldUpdateAndPause();
264 }
265 }
266
267 yield {
268 progress: 1,
269 desc: "Indexing Complete",
270 status: "done",
271 };
272 } catch (err) {
273 yield this.handleErrorAndGetProgressUpdate(err);
274 }
275 }
276
277 async *refreshDirs(
278 dirs: string[],
279 abortSignal: AbortSignal,
280 ): AsyncGenerator<IndexingProgressUpdate> {
281 let progress = 0;
282
283 if (dirs.length === 0) {
284 yield {
285 progress: 1,
286 desc: "Nothing to index",
287 status: "done",
288 };
289 return;
290 }
291
292 const { config } = await this.configHandler.loadConfig();
293 if (!config) {
294 return;
295 }
296 if (config.disableIndexing) {
297 yield {
298 progress,
299 desc: "Indexing is disabled in config.json",
300 status: "disabled",
301 };
302 return;
303 } else {
304 yield {
305 progress,
306 desc: "Starting indexing",
307 status: "loading",
308 };
309 }
310
311 // Wait until Git Extension has loaded to report progress
312 // so we don't appear stuck at 0% while waiting
313 await this.ide.getRepoName(dirs[0]);
314
315 yield {
316 progress,
317 desc: "Starting indexing...",
318 status: "loading",
319 };
320 const beginTime = Date.now();
321
322 for (const directory of dirs) {
323 const dirBasename = getUriPathBasename(directory);
324 yield {
325 progress,
326 desc: `Discovering files in ${dirBasename}...`,
327 status: "indexing",
328 };
329 const directoryFiles = [];
330 for await (const p of walkDirAsync(directory, this.ide, {
331 source: "codebase indexing: refresh dirs",
332 })) {
333 directoryFiles.push(p);
334 if (abortSignal.aborted) {
335 yield {
336 progress: 0,
337 desc: "Indexing cancelled",
338 status: "cancelled",
339 };
340 return;
341 }
342 if (this.pauseToken.paused) {
343 yield* this.yieldUpdateAndPause();
344 }
345 }
346
347 const branch = await this.ide.getBranch(directory);
348 const repoName = await this.ide.getRepoName(directory);
349 let nextLogThreshold = 0;
350
351 try {
352 for await (const updateDesc of this.indexFiles(
353 directory,
354 directoryFiles,
355 branch,
356 repoName,
357 )) {
358 // Handle pausing in this loop because it's the only one really taking time
359 if (abortSignal.aborted) {
360 yield {
361 progress: 0,
362 desc: "Indexing cancelled",
363 status: "cancelled",
364 };
365 return;
366 }
367 if (this.pauseToken.paused) {
368 yield* this.yieldUpdateAndPause();
369 }
370 yield updateDesc;
371 if (updateDesc.progress >= nextLogThreshold) {
372 // log progress every 2.5%
373 nextLogThreshold += 0.025;
374 this.logProgress(
375 beginTime,
376 Math.floor(directoryFiles.length * updateDesc.progress),
377 updateDesc.progress,
378 );
379 }
380 }
381 } catch (err) {
382 yield this.handleErrorAndGetProgressUpdate(err);
383 return;
384 }
385 }
386 yield {
387 progress: 1,
388 desc: "Indexing Complete",
389 status: "done",
390 };
391 this.logProgress(beginTime, 0, 1);
392 }
393
394 private handleErrorAndGetProgressUpdate(
395 err: unknown,
396 ): IndexingProgressUpdate {
397 console.log("error when indexing: ", err);
398 if (err instanceof Error) {
399 const cause = getRootCause(err);
400 if (cause instanceof LLMError) {
401 throw cause;
402 }
403 return this.errorToProgressUpdate(err);
404 }
405 return {
406 progress: 0,
407 desc: `Indexing failed: ${err}`,
408 status: "failed",
409 debugInfo: extractMinimalStackTraceInfo((err as any)?.stack),
410 };
411 }
412
413 private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
414 const cause = getRootCause(err);
415 let errMsg: string = `${cause}`;
416 let shouldClearIndexes = false;
417
418 // Check if any of the error regexes match
419 for (const regexStr of this.errorsRegexesToClearIndexesOn) {
420 const regex = new RegExp(regexStr);
421 const match = err.message.match(regex);
422
423 if (match !== null) {
424 shouldClearIndexes = true;
425 break;
426 }
427 }
428
429 return {
430 progress: 0,
431 desc: errMsg,
432 status: "failed",
433 shouldClearIndexes,
434 debugInfo: extractMinimalStackTraceInfo(err.stack),
435 };
436 }
437
438 private logProgress(
439 beginTime: number,
440 completedFileCount: number,
441 progress: number,
442 ) {
443 const timeTaken = Date.now() - beginTime;
444 const seconds = Math.round(timeTaken / 1000);
445 const progressPercentage = (progress * 100).toFixed(1);
446 const filesPerSec = (completedFileCount / seconds).toFixed(2);
447 // console.debug(
448 // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
449 // );
450 }
451
452 private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {
453 yield {
454 progress: 0,
455 desc: "Indexing Paused",
456 status: "paused",
457 };
458 while (this.pauseToken.paused) {
459 await new Promise((resolve) => setTimeout(resolve, 100));
460 }
461 }
462
463 /*
464 * Enables the indexing operation to be completed in batches, this is important in large
465 * repositories where indexing can quickly use up all the memory available
466 */
467 private *batchRefreshIndexResults(
468 results: RefreshIndexResults,
469 ): Generator<RefreshIndexResults> {
470 let curPos = 0;
471 while (
472 curPos < results.compute.length ||
473 curPos < results.del.length ||
474 curPos < results.addTag.length ||
475 curPos < results.removeTag.length
476 ) {
477 yield {
478 compute: results.compute.slice(curPos, curPos + this.filesPerBatch),
479 del: results.del.slice(curPos, curPos + this.filesPerBatch),
480 addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch),
481 removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch),
482 };
483 curPos += this.filesPerBatch;
484 }
485 }
486
487 private async *indexFiles(
488 directory: string,
489 files: string[],
490 branch: string,
491 repoName: string | undefined,
492 ): AsyncGenerator<IndexingProgressUpdate> {
493 const stats = await this.ide.getFileStats(files);
494 const indexesToBuild = await this.getIndexesToBuild();
495 let completedIndexCount = 0;
496 let progress = 0;
497 for (const codebaseIndex of indexesToBuild) {
498 const tag: IndexTag = {
499 directory,
500 branch,
501 artifactId: codebaseIndex.artifactId,
502 };
503 yield {
504 progress: progress,
505 desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
506 status: "indexing",
507 };
508 const [results, lastUpdated, markComplete] =
509 await getComputeDeleteAddRemove(
510 tag,
511 { ...stats },
512 (filepath) => this.ide.readFile(filepath),
513 repoName,
514 );
515 const totalOps = this.totalIndexOps(results);
516 let completedOps = 0;
517
518 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
519 if (totalOps > 0) {
520 for (const subResult of this.batchRefreshIndexResults(results)) {
521 for await (const { desc } of codebaseIndex.update(
522 tag,
523 subResult,
524 markComplete,
525 repoName,
526 )) {
527 yield {
528 progress: progress,
529 desc,
530 status: "indexing",
531 };
532 }
533 completedOps +=
534 subResult.compute.length +
535 subResult.del.length +
536 subResult.addTag.length +
537 subResult.removeTag.length;
538 progress =
539 (completedIndexCount + completedOps / totalOps) *
540 (1 / indexesToBuild.length);
541 }
542 }
543
544 await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
545 completedIndexCount += 1;
546 }
547 }
548
549 // New methods using messenger directly
550
551 private updateProgress(update: IndexingProgressUpdate) {
552 this.codebaseIndexingState = update;
553 if (this.messenger) {
554 void this.messenger.request("indexProgress", update);
555 }
556 }
557
558 private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
559 console.debug(
560 "Indexing failed with error: ",
561 update.desc,
562 update.debugInfo,
563 );
564 void Telemetry.capture(
565 "indexing_error",
566 {
567 error: update.desc,
568 stack: update.debugInfo,
569 },
570 false,
571 );
572 }
573
574 public async refreshCodebaseIndex(paths: string[]) {
575 if (this.indexingCancellationController) {
576 this.indexingCancellationController.abort();
577 }
578 this.indexingCancellationController = new AbortController();
579 try {
580 for await (const update of this.refreshDirs(
581 paths,
582 this.indexingCancellationController.signal,
583 )) {
584 this.updateProgress(update);
585
586 if (update.status === "failed") {
587 await this.sendIndexingErrorTelemetry(update);
588 }
589 }
590 } catch (e: any) {
591 console.log(`Failed refreshing codebase index directories: ${e}`);
592 await this.handleIndexingError(e);
593 }
594
595 // Directly refresh submenu items
596 if (this.messenger) {
597 this.messenger.send("refreshSubmenuItems", {
598 providers: "all",
599 });
600 }
601 this.indexingCancellationController = undefined;
602 }
603
604 public async refreshCodebaseIndexFiles(files: string[]) {
605 // Can be cancelled by codebase index but not vice versa
606 if (
607 this.indexingCancellationController &&
608 !this.indexingCancellationController.signal.aborted
609 ) {
610 return;
611 }
612 this.indexingCancellationController = new AbortController();
613 try {
614 for await (const update of this.refreshFiles(files)) {
615 this.updateProgress(update);
616
617 if (update.status === "failed") {
618 await this.sendIndexingErrorTelemetry(update);
619 }
620 }
621 } catch (e: any) {
622 console.log(`Failed refreshing codebase index files: ${e}`);
623 await this.handleIndexingError(e);
624 }
625
626 // Directly refresh submenu items
627 if (this.messenger) {
628 this.messenger.send("refreshSubmenuItems", {
629 providers: "all",
630 });
631 }
632 this.indexingCancellationController = undefined;
633 }
634
635 public async handleIndexingError(e: any) {
636 if (e instanceof LLMError && this.messenger) {
637 // Need to report this specific error to the IDE for special handling
638 void this.messenger.request("reportError", e);
639 }
640
641 // broadcast indexing error
642 const updateToSend: IndexingProgressUpdate = {
643 progress: 0,
644 status: "failed",
645 desc: e.message,
646 };
647
648 this.updateProgress(updateToSend);
649 void this.sendIndexingErrorTelemetry(updateToSend);
650 }
651
652 public get currentIndexingState(): IndexingProgressUpdate {
653 return this.codebaseIndexingState;
654 }
655}