Elffuss BraidHub

kikocis/continue public

1f089284a191 · 13.9 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 { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
7import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
8import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
9
10import { LLMError } from "../llm/index.js";
11import { getRootCause } from "../util/errors.js";
12import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
13import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
14import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
15import { LanceDbIndex } from "./LanceDbIndex.js";
16import { getComputeDeleteAddRemove } from "./refreshIndex.js";
17import {
18 CodebaseIndex,
19 IndexResultType,
20 PathAndCacheKey,
21 RefreshIndexResults,
22} from "./types.js";
23import { walkDirAsync } from "./walkDir.js";
24
25export class PauseToken {
26 constructor(private _paused: boolean) {}
27
28 set paused(value: boolean) {
29 this._paused = value;
30 }
31
32 get paused(): boolean {
33 return this._paused;
34 }
35}
36
37export class CodebaseIndexer {
38 /**
39 * We batch for two reasons:
40 * - To limit memory usage for indexes that perform computations locally, e.g. FTS
41 * - To make as few requests as possible to the embeddings providers
42 */
43 filesPerBatch = 500;
44
45 // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
46 // e.g. a `SQLITE_BUSY` error.
47 errorsRegexesToClearIndexesOn = [
48 /Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/,
49 /SQLITE_CONSTRAINT/,
50 /SQLITE_ERROR/,
51 /SQLITE_CORRUPT/,
52 /SQLITE_IOERR/,
53 /SQLITE_FULL/,
54 ];
55
56 constructor(
57 private readonly configHandler: ConfigHandler,
58 protected readonly ide: IDE,
59 private readonly pauseToken: PauseToken,
60 private readonly continueServerClient: IContinueServerClient,
61 ) {}
62
63 async clearIndexes() {
64 const sqliteFilepath = getIndexSqlitePath();
65 const lanceDbFolder = getLanceDbPath();
66
67 try {
68 await fs.unlink(sqliteFilepath);
69 } catch (error) {
70 console.error(`Error deleting ${sqliteFilepath} folder: ${error}`);
71 }
72
73 try {
74 await fs.rm(lanceDbFolder, { recursive: true, force: true });
75 } catch (error) {
76 console.error(`Error deleting ${lanceDbFolder}: ${error}`);
77 }
78 }
79
80 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
81 const { config } = await this.configHandler.loadConfig();
82 if (!config) {
83 return [];
84 }
85
86 const embeddingsModel = config.selectedModelByRole.embed;
87 if (!embeddingsModel) {
88 return [];
89 }
90
91 const indexes: CodebaseIndex[] = [
92 new ChunkCodebaseIndex(
93 this.ide.readFile.bind(this.ide),
94 this.continueServerClient,
95 embeddingsModel.maxEmbeddingChunkSize,
96 ), // Chunking must come first
97 ];
98
99 const lanceDbIndex = await LanceDbIndex.create(
100 embeddingsModel,
101 this.ide.readFile.bind(this.ide),
102 );
103
104 if (lanceDbIndex) {
105 indexes.push(lanceDbIndex);
106 }
107
108 indexes.push(
109 new FullTextSearchCodebaseIndex(),
110 new CodeSnippetsCodebaseIndex(this.ide),
111 );
112
113 return indexes;
114 }
115
116 private totalIndexOps(results: RefreshIndexResults): number {
117 return (
118 results.compute.length +
119 results.del.length +
120 results.addTag.length +
121 results.removeTag.length
122 );
123 }
124
125 private singleFileIndexOps(
126 results: RefreshIndexResults,
127 lastUpdated: PathAndCacheKey[],
128 filePath: string,
129 ): [RefreshIndexResults, PathAndCacheKey[]] {
130 const filterFn = (item: PathAndCacheKey) => item.path === filePath;
131 const compute = results.compute.filter(filterFn);
132 const del = results.del.filter(filterFn);
133 const addTag = results.addTag.filter(filterFn);
134 const removeTag = results.removeTag.filter(filterFn);
135 const newResults = {
136 compute,
137 del,
138 addTag,
139 removeTag,
140 };
141 const newLastUpdated = lastUpdated.filter(filterFn);
142 return [newResults, newLastUpdated];
143 }
144
145 public async refreshFile(
146 file: string,
147 workspaceDirs: string[],
148 ): Promise<void> {
149 if (this.pauseToken.paused) {
150 // NOTE: by returning here, there is a chance that while paused a file is modified and
151 // then after unpausing the file is not reindexed
152 return;
153 }
154 const { foundInDir } = findUriInDirs(file, workspaceDirs);
155 if (!foundInDir) {
156 return;
157 }
158 const branch = await this.ide.getBranch(foundInDir);
159 const repoName = await this.ide.getRepoName(foundInDir);
160 const indexesToBuild = await this.getIndexesToBuild();
161 const stats = await this.ide.getFileStats([file]);
162 const filePath = Object.keys(stats)[0];
163 for (const index of indexesToBuild) {
164 const tag = {
165 directory: foundInDir,
166 branch,
167 artifactId: index.artifactId,
168 };
169 const [fullResults, fullLastUpdated, markComplete] =
170 await getComputeDeleteAddRemove(
171 tag,
172 { ...stats },
173 (filepath) => this.ide.readFile(filepath),
174 repoName,
175 );
176
177 const [results, lastUpdated] = this.singleFileIndexOps(
178 fullResults,
179 fullLastUpdated,
180 filePath,
181 );
182 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
183 if (this.totalIndexOps(results) + lastUpdated.length === 0) {
184 continue;
185 }
186
187 for await (const _ of index.update(
188 tag,
189 results,
190 markComplete,
191 repoName,
192 )) {
193 }
194 }
195 }
196
197 async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
198 let progress = 0;
199 if (files.length === 0) {
200 yield {
201 progress: 1,
202 desc: "Indexing Complete",
203 status: "done",
204 };
205 }
206
207 const workspaceDirs = await this.ide.getWorkspaceDirs();
208
209 const progressPer = 1 / files.length;
210 try {
211 for (const file of files) {
212 yield {
213 progress,
214 desc: `Indexing file ${file}...`,
215 status: "indexing",
216 };
217 await this.refreshFile(file, workspaceDirs);
218
219 progress += progressPer;
220
221 if (this.pauseToken.paused) {
222 yield* this.yieldUpdateAndPause();
223 }
224 }
225
226 yield {
227 progress: 1,
228 desc: "Indexing Complete",
229 status: "done",
230 };
231 } catch (err) {
232 yield this.handleErrorAndGetProgressUpdate(err);
233 }
234 }
235
236 async *refreshDirs(
237 dirs: string[],
238 abortSignal: AbortSignal,
239 ): AsyncGenerator<IndexingProgressUpdate> {
240 let progress = 0;
241
242 if (dirs.length === 0) {
243 yield {
244 progress: 1,
245 desc: "Nothing to index",
246 status: "done",
247 };
248 return;
249 }
250
251 const { config } = await this.configHandler.loadConfig();
252 if (config?.disableIndexing) {
253 yield {
254 progress,
255 desc: "Indexing is disabled in config.json",
256 status: "disabled",
257 };
258 return;
259 } else {
260 yield {
261 progress,
262 desc: "Starting indexing",
263 status: "loading",
264 };
265 }
266
267 // Wait until Git Extension has loaded to report progress
268 // so we don't appear stuck at 0% while waiting
269 await this.ide.getRepoName(dirs[0]);
270
271 yield {
272 progress,
273 desc: "Starting indexing...",
274 status: "loading",
275 };
276 const beginTime = Date.now();
277
278 for (const directory of dirs) {
279 const dirBasename = getUriPathBasename(directory);
280 yield {
281 progress,
282 desc: `Discovering files in ${dirBasename}...`,
283 status: "indexing",
284 };
285 const directoryFiles = [];
286 for await (const p of walkDirAsync(directory, this.ide, {
287 source: "codebase indexing: refresh dirs",
288 })) {
289 directoryFiles.push(p);
290 if (abortSignal.aborted) {
291 yield {
292 progress: 0,
293 desc: "Indexing cancelled",
294 status: "cancelled",
295 };
296 return;
297 }
298 if (this.pauseToken.paused) {
299 yield* this.yieldUpdateAndPause();
300 }
301 }
302
303 const branch = await this.ide.getBranch(directory);
304 const repoName = await this.ide.getRepoName(directory);
305 let nextLogThreshold = 0;
306
307 try {
308 for await (const updateDesc of this.indexFiles(
309 directory,
310 directoryFiles,
311 branch,
312 repoName,
313 )) {
314 // Handle pausing in this loop because it's the only one really taking time
315 if (abortSignal.aborted) {
316 yield {
317 progress: 0,
318 desc: "Indexing cancelled",
319 status: "cancelled",
320 };
321 return;
322 }
323 if (this.pauseToken.paused) {
324 yield* this.yieldUpdateAndPause();
325 }
326 yield updateDesc;
327 if (updateDesc.progress >= nextLogThreshold) {
328 // log progress every 2.5%
329 nextLogThreshold += 0.025;
330 this.logProgress(
331 beginTime,
332 Math.floor(directoryFiles.length * updateDesc.progress),
333 updateDesc.progress,
334 );
335 }
336 }
337 } catch (err) {
338 yield this.handleErrorAndGetProgressUpdate(err);
339 return;
340 }
341 }
342 yield {
343 progress: 1,
344 desc: "Indexing Complete",
345 status: "done",
346 };
347 this.logProgress(beginTime, 0, 1);
348 }
349
350 private handleErrorAndGetProgressUpdate(
351 err: unknown,
352 ): IndexingProgressUpdate {
353 console.log("error when indexing: ", err);
354 if (err instanceof Error) {
355 const cause = getRootCause(err);
356 if (cause instanceof LLMError) {
357 throw cause;
358 }
359 return this.errorToProgressUpdate(err);
360 }
361 return {
362 progress: 0,
363 desc: `Indexing failed: ${err}`,
364 status: "failed",
365 debugInfo: extractMinimalStackTraceInfo((err as any)?.stack),
366 };
367 }
368
369 private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
370 const cause = getRootCause(err);
371 let errMsg: string = `${cause}`;
372 let shouldClearIndexes = false;
373
374 // Check if any of the error regexes match
375 for (const regexStr of this.errorsRegexesToClearIndexesOn) {
376 const regex = new RegExp(regexStr);
377 const match = err.message.match(regex);
378
379 if (match !== null) {
380 shouldClearIndexes = true;
381 break;
382 }
383 }
384
385 return {
386 progress: 0,
387 desc: errMsg,
388 status: "failed",
389 shouldClearIndexes,
390 debugInfo: extractMinimalStackTraceInfo(err.stack),
391 };
392 }
393
394 private logProgress(
395 beginTime: number,
396 completedFileCount: number,
397 progress: number,
398 ) {
399 const timeTaken = Date.now() - beginTime;
400 const seconds = Math.round(timeTaken / 1000);
401 const progressPercentage = (progress * 100).toFixed(1);
402 const filesPerSec = (completedFileCount / seconds).toFixed(2);
403 // console.debug(
404 // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
405 // );
406 }
407
408 private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {
409 yield {
410 progress: 0,
411 desc: "Indexing Paused",
412 status: "paused",
413 };
414 while (this.pauseToken.paused) {
415 await new Promise((resolve) => setTimeout(resolve, 100));
416 }
417 }
418
419 /*
420 * Enables the indexing operation to be completed in batches, this is important in large
421 * repositories where indexing can quickly use up all the memory available
422 */
423 private *batchRefreshIndexResults(
424 results: RefreshIndexResults,
425 ): Generator<RefreshIndexResults> {
426 let curPos = 0;
427 while (
428 curPos < results.compute.length ||
429 curPos < results.del.length ||
430 curPos < results.addTag.length ||
431 curPos < results.removeTag.length
432 ) {
433 yield {
434 compute: results.compute.slice(curPos, curPos + this.filesPerBatch),
435 del: results.del.slice(curPos, curPos + this.filesPerBatch),
436 addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch),
437 removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch),
438 };
439 curPos += this.filesPerBatch;
440 }
441 }
442
443 private async *indexFiles(
444 directory: string,
445 files: string[],
446 branch: string,
447 repoName: string | undefined,
448 ): AsyncGenerator<IndexingProgressUpdate> {
449 const stats = await this.ide.getFileStats(files);
450 const indexesToBuild = await this.getIndexesToBuild();
451 let completedIndexCount = 0;
452 let progress = 0;
453 for (const codebaseIndex of indexesToBuild) {
454 const tag: IndexTag = {
455 directory,
456 branch,
457 artifactId: codebaseIndex.artifactId,
458 };
459 yield {
460 progress: progress,
461 desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
462 status: "indexing",
463 };
464 const [results, lastUpdated, markComplete] =
465 await getComputeDeleteAddRemove(
466 tag,
467 { ...stats },
468 (filepath) => this.ide.readFile(filepath),
469 repoName,
470 );
471 const totalOps = this.totalIndexOps(results);
472 let completedOps = 0;
473
474 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
475 if (totalOps > 0) {
476 for (const subResult of this.batchRefreshIndexResults(results)) {
477 for await (const { desc } of codebaseIndex.update(
478 tag,
479 subResult,
480 markComplete,
481 repoName,
482 )) {
483 yield {
484 progress: progress,
485 desc,
486 status: "indexing",
487 };
488 }
489 completedOps +=
490 subResult.compute.length +
491 subResult.del.length +
492 subResult.addTag.length +
493 subResult.removeTag.length;
494 progress =
495 (completedIndexCount + completedOps / totalOps) *
496 (1 / indexesToBuild.length);
497 }
498 }
499
500 await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
501 completedIndexCount += 1;
502 }
503 }
504}