Elffuss BraidHub

kikocis/continue public

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