Elffuss BraidHub

kikocis/continue public

c7baac6d06d1 · 14.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 { 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) {
253 return;
254 }
255 if (config.disableIndexing) {
256 yield {
257 progress,
258 desc: "Indexing is disabled in config.json",
259 status: "disabled",
260 };
261 return;
262 } else {
263 yield {
264 progress,
265 desc: "Starting indexing",
266 status: "loading",
267 };
268 }
269
270 // Wait until Git Extension has loaded to report progress
271 // so we don't appear stuck at 0% while waiting
272 await this.ide.getRepoName(dirs[0]);
273
274 yield {
275 progress,
276 desc: "Starting indexing...",
277 status: "loading",
278 };
279 const beginTime = Date.now();
280
281 for (const directory of dirs) {
282 const dirBasename = getUriPathBasename(directory);
283 yield {
284 progress,
285 desc: `Discovering files in ${dirBasename}...`,
286 status: "indexing",
287 };
288 const directoryFiles = [];
289 for await (const p of walkDirAsync(directory, this.ide, {
290 source: "codebase indexing: refresh dirs",
291 })) {
292 directoryFiles.push(p);
293 if (abortSignal.aborted) {
294 yield {
295 progress: 0,
296 desc: "Indexing cancelled",
297 status: "cancelled",
298 };
299 return;
300 }
301 if (this.pauseToken.paused) {
302 yield* this.yieldUpdateAndPause();
303 }
304 }
305
306 const branch = await this.ide.getBranch(directory);
307 const repoName = await this.ide.getRepoName(directory);
308 let nextLogThreshold = 0;
309
310 try {
311 for await (const updateDesc of this.indexFiles(
312 directory,
313 directoryFiles,
314 branch,
315 repoName,
316 )) {
317 // Handle pausing in this loop because it's the only one really taking time
318 if (abortSignal.aborted) {
319 yield {
320 progress: 0,
321 desc: "Indexing cancelled",
322 status: "cancelled",
323 };
324 return;
325 }
326 if (this.pauseToken.paused) {
327 yield* this.yieldUpdateAndPause();
328 }
329 yield updateDesc;
330 if (updateDesc.progress >= nextLogThreshold) {
331 // log progress every 2.5%
332 nextLogThreshold += 0.025;
333 this.logProgress(
334 beginTime,
335 Math.floor(directoryFiles.length * updateDesc.progress),
336 updateDesc.progress,
337 );
338 }
339 }
340 } catch (err) {
341 yield this.handleErrorAndGetProgressUpdate(err);
342 return;
343 }
344 }
345 yield {
346 progress: 1,
347 desc: "Indexing Complete",
348 status: "done",
349 };
350 this.logProgress(beginTime, 0, 1);
351 }
352
353 private handleErrorAndGetProgressUpdate(
354 err: unknown,
355 ): IndexingProgressUpdate {
356 console.log("error when indexing: ", err);
357 if (err instanceof Error) {
358 const cause = getRootCause(err);
359 if (cause instanceof LLMError) {
360 throw cause;
361 }
362 return this.errorToProgressUpdate(err);
363 }
364 return {
365 progress: 0,
366 desc: `Indexing failed: ${err}`,
367 status: "failed",
368 debugInfo: extractMinimalStackTraceInfo((err as any)?.stack),
369 };
370 }
371
372 private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
373 const cause = getRootCause(err);
374 let errMsg: string = `${cause}`;
375 let shouldClearIndexes = false;
376
377 // Check if any of the error regexes match
378 for (const regexStr of this.errorsRegexesToClearIndexesOn) {
379 const regex = new RegExp(regexStr);
380 const match = err.message.match(regex);
381
382 if (match !== null) {
383 shouldClearIndexes = true;
384 break;
385 }
386 }
387
388 return {
389 progress: 0,
390 desc: errMsg,
391 status: "failed",
392 shouldClearIndexes,
393 debugInfo: extractMinimalStackTraceInfo(err.stack),
394 };
395 }
396
397 private logProgress(
398 beginTime: number,
399 completedFileCount: number,
400 progress: number,
401 ) {
402 const timeTaken = Date.now() - beginTime;
403 const seconds = Math.round(timeTaken / 1000);
404 const progressPercentage = (progress * 100).toFixed(1);
405 const filesPerSec = (completedFileCount / seconds).toFixed(2);
406 // console.debug(
407 // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
408 // );
409 }
410
411 private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {
412 yield {
413 progress: 0,
414 desc: "Indexing Paused",
415 status: "paused",
416 };
417 while (this.pauseToken.paused) {
418 await new Promise((resolve) => setTimeout(resolve, 100));
419 }
420 }
421
422 /*
423 * Enables the indexing operation to be completed in batches, this is important in large
424 * repositories where indexing can quickly use up all the memory available
425 */
426 private *batchRefreshIndexResults(
427 results: RefreshIndexResults,
428 ): Generator<RefreshIndexResults> {
429 let curPos = 0;
430 while (
431 curPos < results.compute.length ||
432 curPos < results.del.length ||
433 curPos < results.addTag.length ||
434 curPos < results.removeTag.length
435 ) {
436 yield {
437 compute: results.compute.slice(curPos, curPos + this.filesPerBatch),
438 del: results.del.slice(curPos, curPos + this.filesPerBatch),
439 addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch),
440 removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch),
441 };
442 curPos += this.filesPerBatch;
443 }
444 }
445
446 private async *indexFiles(
447 directory: string,
448 files: string[],
449 branch: string,
450 repoName: string | undefined,
451 ): AsyncGenerator<IndexingProgressUpdate> {
452 const stats = await this.ide.getFileStats(files);
453 const indexesToBuild = await this.getIndexesToBuild();
454 let completedIndexCount = 0;
455 let progress = 0;
456 for (const codebaseIndex of indexesToBuild) {
457 const tag: IndexTag = {
458 directory,
459 branch,
460 artifactId: codebaseIndex.artifactId,
461 };
462 yield {
463 progress: progress,
464 desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
465 status: "indexing",
466 };
467 const [results, lastUpdated, markComplete] =
468 await getComputeDeleteAddRemove(
469 tag,
470 { ...stats },
471 (filepath) => this.ide.readFile(filepath),
472 repoName,
473 );
474 const totalOps = this.totalIndexOps(results);
475 let completedOps = 0;
476
477 // Don't update if nothing to update. Some of the indices might do unnecessary setup work
478 if (totalOps > 0) {
479 for (const subResult of this.batchRefreshIndexResults(results)) {
480 for await (const { desc } of codebaseIndex.update(
481 tag,
482 subResult,
483 markComplete,
484 repoName,
485 )) {
486 yield {
487 progress: progress,
488 desc,
489 status: "indexing",
490 };
491 }
492 completedOps +=
493 subResult.compute.length +
494 subResult.del.length +
495 subResult.addTag.length +
496 subResult.removeTag.length;
497 progress =
498 (completedIndexCount + completedOps / totalOps) *
499 (1 / indexesToBuild.length);
500 }
501 }
502
503 await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
504 completedIndexCount += 1;
505 }
506 }
507}