Elffuss BraidHub

kikocis/continue public

main · 15.1 KiBRawPermalink
1import { RunResult } from "sqlite3";
2import { v4 as uuidv4 } from "uuid";
3
4import { isSupportedLanceDbCpuTargetForLinux } from "../config/util";
5import {
6 BranchAndDir,
7 Chunk,
8 ILLM,
9 IndexTag,
10 IndexingProgressUpdate,
11} from "../index";
12import { getLanceDbPath, migrate } from "../util/paths";
13import { getUriPathBasename } from "../util/uri";
14
15import { basicChunker } from "./chunk/basic.js";
16import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
17import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
18import {
19 CodebaseIndex,
20 IndexResultType,
21 MarkCompleteCallback,
22 PathAndCacheKey,
23 RefreshIndexResults,
24} from "./types";
25
26import type * as LanceType from "vectordb";
27import { tagToString } from "./utils";
28
29interface LanceDbRow {
30 uuid: string;
31 path: string;
32 cachekey: string;
33 vector: number[];
34 [key: string]: any;
35}
36
37type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] };
38
39type ChunkMap = Map<string, ItemWithChunks>;
40
41export class LanceDbIndex implements CodebaseIndex {
42 private static lance: typeof LanceType | null = null;
43
44 relativeExpectedTime: number = 13;
45 get artifactId(): string {
46 return `vectordb::${this.embeddingsProvider?.embeddingId}`;
47 }
48
49 /**
50 * Factory method for creating LanceDbIndex instances.
51 *
52 * We dynamically import LanceDB only when supported to avoid native module loading errors
53 * on incompatible platforms. LanceDB has CPU-specific native dependencies that can crash
54 * the application if loaded on unsupported architectures.
55 *
56 * See isSupportedLanceDbCpuTargetForLinux() for platform compatibility details.
57 */
58 static async create(
59 embeddingsProvider: ILLM,
60 readFile: (filepath: string) => Promise<string>,
61 ): Promise<LanceDbIndex | null> {
62 if (!isSupportedLanceDbCpuTargetForLinux()) {
63 return null;
64 }
65
66 try {
67 this.lance = await import("vectordb");
68 return new LanceDbIndex(embeddingsProvider, readFile);
69 } catch (err) {
70 console.error("Failed to load LanceDB:", err);
71 return null;
72 }
73 }
74
75 private constructor(
76 private readonly embeddingsProvider: ILLM,
77 private readonly readFile: (filepath: string) => Promise<string>,
78 ) {
79 if (!LanceDbIndex.lance) {
80 throw new Error("LanceDB not initialized");
81 }
82 }
83
84 tableNameForTag(tag: IndexTag) {
85 return tagToString(tag).replace(/[^\w-_.]/g, "");
86 }
87
88 private async createSqliteCacheTable(db: DatabaseConnection) {
89 await db.exec(`CREATE TABLE IF NOT EXISTS lance_db_cache (
90 uuid TEXT PRIMARY KEY,
91 cacheKey TEXT NOT NULL,
92 path TEXT NOT NULL,
93 artifact_id TEXT NOT NULL,
94 vector TEXT NOT NULL,
95 startLine INTEGER NOT NULL,
96 endLine INTEGER NOT NULL,
97 contents TEXT NOT NULL
98 )`);
99
100 await new Promise((resolve) => {
101 void migrate(
102 "lancedb_sqlite_artifact_id_column",
103 async () => {
104 try {
105 const pragma = await db.all("PRAGMA table_info(lance_db_cache)");
106
107 const hasArtifactIdCol = pragma.some(
108 (pragma) => pragma.name === "artifact_id",
109 );
110
111 if (!hasArtifactIdCol) {
112 await db.exec(
113 "ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'",
114 );
115 }
116 } finally {
117 resolve(undefined);
118 }
119 },
120 () => resolve(undefined),
121 );
122 });
123 }
124
125 private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {
126 const chunkMap = await this.collectChunks(items);
127 const allChunks = Array.from(chunkMap.values()).flatMap(
128 ({ chunks }) => chunks,
129 );
130 const embeddings = await this.getEmbeddings(allChunks);
131
132 for (let i = embeddings.length - 1; i >= 0; i--) {
133 if (embeddings[i] === undefined) {
134 const chunk = allChunks[i];
135 const chunks = chunkMap.get(chunk.filepath)?.chunks;
136 if (chunks) {
137 const index = chunks.findIndex((c) => c === chunk);
138 if (index !== -1) {
139 chunks.splice(index, 1);
140 }
141 }
142
143 embeddings.splice(i, 1);
144 }
145 }
146
147 return this.createLanceDbRows(chunkMap, embeddings);
148 }
149
150 private async collectChunks(items: PathAndCacheKey[]): Promise<ChunkMap> {
151 const chunkMap: ChunkMap = new Map();
152
153 for (const item of items) {
154 try {
155 const content = await this.readFile(item.path);
156
157 if (!shouldChunk(item.path, content)) {
158 continue;
159 }
160
161 const chunks = await this.getChunks(item, content);
162 chunkMap.set(item.path, { item, chunks });
163 } catch (err) {
164 console.log(`LanceDBIndex, skipping ${item.path}: ${err}`);
165 }
166 }
167
168 return chunkMap;
169 }
170
171 private async getChunks(
172 item: PathAndCacheKey,
173 content: string,
174 ): Promise<Chunk[]> {
175 if (!this.embeddingsProvider) {
176 return [];
177 }
178 const chunks: Chunk[] = [];
179
180 const chunkParams = {
181 filepath: item.path,
182 contents: content,
183 maxChunkSize: this.embeddingsProvider.maxEmbeddingChunkSize,
184 digest: item.cacheKey,
185 };
186
187 for await (const chunk of chunkDocument(chunkParams)) {
188 if (chunk.content.length === 0) {
189 throw new Error("did not chunk properly");
190 }
191
192 chunks.push(chunk);
193 }
194
195 return chunks;
196 }
197
198 private async getEmbeddings(chunks: Chunk[]): Promise<number[][]> {
199 if (!this.embeddingsProvider) {
200 return [];
201 }
202 try {
203 return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
204 } catch (err) {
205 throw new Error(
206 `Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.embeddingId}: ${err}`,
207 { cause: err },
208 );
209 }
210 }
211
212 private createLanceDbRows(
213 chunkMap: ChunkMap,
214 embeddings: number[][],
215 ): LanceDbRow[] {
216 const results: LanceDbRow[] = [];
217 let embeddingIndex = 0;
218
219 for (const [path, { item, chunks }] of chunkMap) {
220 for (const chunk of chunks) {
221 results.push({
222 path,
223 cachekey: item.cacheKey,
224 uuid: uuidv4(),
225 vector: embeddings[embeddingIndex],
226 startLine: chunk.startLine,
227 endLine: chunk.endLine,
228 contents: chunk.content,
229 });
230 embeddingIndex++;
231 }
232 }
233
234 return results;
235 }
236
237 /**
238 * Due to a bug in indexing, some indexes have vectors
239 * without the surrounding []. These would fail to parse
240 * but this allows such existing indexes to function properly
241 */
242 private parseVector(vector: string): number[] {
243 try {
244 return JSON.parse(vector);
245 } catch (err) {
246 try {
247 return JSON.parse(`[${vector}]`);
248 } catch (err2) {
249 throw new Error(`Failed to parse vector: ${vector}`, { cause: err2 });
250 }
251 }
252 }
253
254 async *update(
255 tag: IndexTag,
256 results: RefreshIndexResults,
257 markComplete: MarkCompleteCallback,
258 repoName: string | undefined,
259 ): AsyncGenerator<IndexingProgressUpdate> {
260 const lance = LanceDbIndex.lance!;
261 const sqliteDb = await SqliteDb.get();
262 await this.createSqliteCacheTable(sqliteDb);
263
264 const lanceTableName = this.tableNameForTag(tag);
265 const lanceDb = await lance.connect(getLanceDbPath());
266 const existingLanceTables = await lanceDb.tableNames();
267
268 let lanceTable: LanceType.Table<number[]> | undefined = undefined;
269 let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName);
270
271 const addComputedLanceDbRows = async (
272 pathAndCacheKeys: PathAndCacheKey[],
273 computedRows: LanceDbRow[],
274 ) => {
275 if (lanceTable) {
276 if (computedRows.length > 0) {
277 await lanceTable.add(computedRows);
278 }
279 } else if (existingLanceTables.includes(lanceTableName)) {
280 lanceTable = await lanceDb.openTable(lanceTableName);
281 needToCreateLanceTable = false;
282 if (computedRows.length > 0) {
283 await lanceTable.add(computedRows);
284 }
285 } else if (computedRows.length > 0) {
286 lanceTable = await lanceDb.createTable(lanceTableName, computedRows);
287 needToCreateLanceTable = false;
288 }
289
290 await markComplete(pathAndCacheKeys, IndexResultType.Compute);
291 };
292
293 yield {
294 progress: 0,
295 desc: `Computing embeddings for ${
296 results.compute.length
297 } ${this.formatListPlurality("file", results.compute.length)}`,
298 status: "indexing",
299 };
300
301 const dbRows = await this.computeRows(results.compute);
302 await this.insertRows(sqliteDb, dbRows);
303 await addComputedLanceDbRows(results.compute, dbRows);
304 let accumulatedProgress = 0;
305
306 for (const { path, cacheKey } of results.addTag) {
307 const stmt = await sqliteDb.prepare(
308 "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?",
309 cacheKey,
310 this.artifactId,
311 );
312 const cachedItems = await stmt.all();
313
314 const lanceRows: LanceDbRow[] = [];
315 for (const item of cachedItems) {
316 try {
317 const vector = this.parseVector(item.vector);
318 const { uuid, startLine, endLine, contents } = item;
319
320 lanceRows.push({
321 path,
322 uuid,
323 startLine,
324 endLine,
325 contents,
326 cachekey: cacheKey,
327 vector,
328 });
329 } catch (err) {
330 console.warn(
331 `LanceDBIndex, skipping ${item.path} due to invalid vector JSON:\n${item.vector}\n\nError: ${err}`,
332 );
333 }
334 }
335
336 if (lanceRows.length > 0) {
337 if (needToCreateLanceTable) {
338 lanceTable = await lanceDb.createTable(lanceTableName, lanceRows);
339 needToCreateLanceTable = false;
340 } else if (!lanceTable) {
341 lanceTable = await lanceDb.openTable(lanceTableName);
342 needToCreateLanceTable = false;
343 await lanceTable.add(lanceRows);
344 } else {
345 await lanceTable?.add(lanceRows);
346 }
347 }
348
349 await markComplete([{ path, cacheKey }], IndexResultType.AddTag);
350 accumulatedProgress += 1 / results.addTag.length / 3;
351 yield {
352 progress: accumulatedProgress,
353 desc: `Indexing ${getUriPathBasename(path)}`,
354 status: "indexing",
355 };
356 }
357
358 if (!needToCreateLanceTable) {
359 const toDel = [...results.removeTag, ...results.del];
360
361 if (!lanceTable) {
362 lanceTable = await lanceDb.openTable(lanceTableName);
363 }
364
365 for (const { path, cacheKey } of toDel) {
366 await lanceTable.delete(
367 `cachekey = '${cacheKey}' AND path = '${path}'`,
368 );
369
370 accumulatedProgress += 1 / toDel.length / 3;
371 yield {
372 progress: accumulatedProgress,
373 desc: `Stashing ${getUriPathBasename(path)}`,
374 status: "indexing",
375 };
376 }
377 }
378
379 await markComplete(results.removeTag, IndexResultType.RemoveTag);
380
381 for (const { path, cacheKey } of results.del) {
382 await sqliteDb.run(
383 "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
384 cacheKey,
385 path,
386 this.artifactId,
387 );
388 accumulatedProgress += 1 / results.del.length / 3;
389 yield {
390 progress: accumulatedProgress,
391 desc: `Removing ${getUriPathBasename(path)}`,
392 status: "indexing",
393 };
394 }
395
396 await markComplete(results.del, IndexResultType.Delete);
397
398 yield {
399 progress: 1,
400 desc: "Completed Calculating Embeddings",
401 status: "done",
402 };
403 }
404
405 private async _retrieveForTag(
406 tag: IndexTag,
407 n: number,
408 directory: string | undefined,
409 vector: number[],
410 db: any,
411 ): Promise<LanceDbRow[]> {
412 const tableName = this.tableNameForTag(tag);
413 const tableNames = await db.tableNames();
414 if (!tableNames.includes(tableName)) {
415 console.warn("Table not found in LanceDB", tableName);
416 return [];
417 }
418
419 const table = await db.openTable(tableName);
420 let query = table.search(vector);
421 if (directory) {
422 query = query.where(`path LIKE '${directory}%'`).limit(300);
423 } else {
424 query = query.limit(n);
425 }
426 const results = await query.execute();
427 return results.slice(0, n) as any;
428 }
429
430 async retrieve(
431 query: string,
432 n: number,
433 tags: BranchAndDir[],
434 filterDirectory: string | undefined,
435 ): Promise<Chunk[]> {
436 const lance = LanceDbIndex.lance!;
437 if (!this.embeddingsProvider) {
438 return [];
439 }
440
441 // Use just the first chunk of the user query in case it is too long
442 const chunks = [];
443 for await (const chunk of basicChunker(
444 query,
445 this.embeddingsProvider.maxEmbeddingChunkSize,
446 )) {
447 chunks.push(chunk);
448 }
449 let vector = null;
450 try {
451 [vector] = await this.embeddingsProvider.embed(
452 chunks.map((c) => c.content),
453 );
454 } catch (err) {
455 // If we fail to chunk, we just use what was happening before.
456 [vector] = await this.embeddingsProvider.embed([query]);
457 }
458
459 const db = await lance.connect(getLanceDbPath());
460
461 let allResults = [];
462 for (const tag of tags) {
463 const results = await this._retrieveForTag(
464 { ...tag, artifactId: this.artifactId },
465 n,
466 filterDirectory,
467 vector,
468 db,
469 );
470 allResults.push(...results);
471 }
472
473 allResults = allResults
474 .sort((a, b) => a._distance - b._distance)
475 .slice(0, n);
476
477 const sqliteDb = await SqliteDb.get();
478 const data = await sqliteDb.all(
479 `SELECT * FROM lance_db_cache WHERE uuid in (${allResults
480 .map((r) => `'${r.uuid}'`)
481 .join(",")})`,
482 );
483
484 return data.map((d) => {
485 return {
486 digest: d.cacheKey,
487 filepath: d.path,
488 startLine: d.startLine,
489 endLine: d.endLine,
490 index: 0,
491 content: d.contents,
492 };
493 });
494 }
495
496 private async insertRows(
497 db: DatabaseConnection,
498 rows: LanceDbRow[],
499 ): Promise<void> {
500 return new Promise<void>((resolve, reject) => {
501 db.db.serialize(() => {
502 db.db.exec("BEGIN", (err: Error | null) => {
503 if (err) {
504 reject(new Error("error creating transaction", { cause: err }));
505 }
506 });
507
508 const sql =
509 "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
510 rows.map((r) => {
511 db.db.run(
512 sql,
513 [
514 r.uuid,
515 r.cachekey,
516 r.path,
517 this.artifactId,
518 JSON.stringify(r.vector),
519 r.startLine,
520 r.endLine,
521 r.contents,
522 ],
523 (result: RunResult, err: Error) => {
524 if (err) {
525 reject(
526 new Error("error inserting into lance_db_cache table", {
527 cause: err,
528 }),
529 );
530 }
531 },
532 );
533 });
534 db.db.exec("COMMIT", (err: Error | null) => {
535 if (err) {
536 reject(
537 new Error(
538 "error while committing insert into lance_db_rows transaction",
539 { cause: err },
540 ),
541 );
542 } else {
543 resolve();
544 }
545 });
546 });
547 });
548 }
549
550 private formatListPlurality(word: string, length: number): string {
551 return length <= 1 ? word : `${word}s`;
552 }
553}