Elffuss BraidHub

kikocis/continue public

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