Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 14.4 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 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 async *update(
238 tag: IndexTag,
239 results: RefreshIndexResults,
240 markComplete: MarkCompleteCallback,
241 repoName: string | undefined,
242 ): AsyncGenerator<IndexingProgressUpdate> {
243 const lance = LanceDbIndex.lance!;
244 const sqliteDb = await SqliteDb.get();
245 await this.createSqliteCacheTable(sqliteDb);
246
247 const lanceTableName = this.tableNameForTag(tag);
248 const lanceDb = await lance.connect(getLanceDbPath());
249 const existingLanceTables = await lanceDb.tableNames();
250
251 let lanceTable: LanceType.Table<number[]> | undefined = undefined;
252 let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName);
253
254 const addComputedLanceDbRows = async (
255 pathAndCacheKeys: PathAndCacheKey[],
256 computedRows: LanceDbRow[],
257 ) => {
258 if (lanceTable) {
259 if (computedRows.length > 0) {
260 await lanceTable.add(computedRows);
261 }
262 } else if (existingLanceTables.includes(lanceTableName)) {
263 lanceTable = await lanceDb.openTable(lanceTableName);
264 needToCreateLanceTable = false;
265 if (computedRows.length > 0) {
266 await lanceTable.add(computedRows);
267 }
268 } else if (computedRows.length > 0) {
269 lanceTable = await lanceDb.createTable(lanceTableName, computedRows);
270 needToCreateLanceTable = false;
271 }
272
273 await markComplete(pathAndCacheKeys, IndexResultType.Compute);
274 };
275
276 yield {
277 progress: 0,
278 desc: `Computing embeddings for ${
279 results.compute.length
280 } ${this.formatListPlurality("file", results.compute.length)}`,
281 status: "indexing",
282 };
283
284 const dbRows = await this.computeRows(results.compute);
285 await this.insertRows(sqliteDb, dbRows);
286 await addComputedLanceDbRows(results.compute, dbRows);
287 let accumulatedProgress = 0;
288
289 for (const { path, cacheKey } of results.addTag) {
290 const stmt = await sqliteDb.prepare(
291 "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?",
292 cacheKey,
293 this.artifactId,
294 );
295 const cachedItems = await stmt.all();
296
297 const lanceRows: LanceDbRow[] = cachedItems.map(
298 ({ uuid, vector, startLine, endLine, contents }) => ({
299 path,
300 uuid,
301 startLine,
302 endLine,
303 contents,
304 cachekey: cacheKey,
305 vector: JSON.parse(vector),
306 }),
307 );
308
309 if (lanceRows.length > 0) {
310 if (needToCreateLanceTable) {
311 lanceTable = await lanceDb.createTable(lanceTableName, lanceRows);
312 needToCreateLanceTable = false;
313 } else if (!lanceTable) {
314 lanceTable = await lanceDb.openTable(lanceTableName);
315 needToCreateLanceTable = false;
316 await lanceTable.add(lanceRows);
317 } else {
318 await lanceTable?.add(lanceRows);
319 }
320 }
321
322 await markComplete([{ path, cacheKey }], IndexResultType.AddTag);
323 accumulatedProgress += 1 / results.addTag.length / 3;
324 yield {
325 progress: accumulatedProgress,
326 desc: `Indexing ${getUriPathBasename(path)}`,
327 status: "indexing",
328 };
329 }
330
331 if (!needToCreateLanceTable) {
332 const toDel = [...results.removeTag, ...results.del];
333
334 if (!lanceTable) {
335 lanceTable = await lanceDb.openTable(lanceTableName);
336 }
337
338 for (const { path, cacheKey } of toDel) {
339 await lanceTable.delete(
340 `cachekey = '${cacheKey}' AND path = '${path}'`,
341 );
342
343 accumulatedProgress += 1 / toDel.length / 3;
344 yield {
345 progress: accumulatedProgress,
346 desc: `Stashing ${getUriPathBasename(path)}`,
347 status: "indexing",
348 };
349 }
350 }
351
352 await markComplete(results.removeTag, IndexResultType.RemoveTag);
353
354 for (const { path, cacheKey } of results.del) {
355 await sqliteDb.run(
356 "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
357 cacheKey,
358 path,
359 this.artifactId,
360 );
361 accumulatedProgress += 1 / results.del.length / 3;
362 yield {
363 progress: accumulatedProgress,
364 desc: `Removing ${getUriPathBasename(path)}`,
365 status: "indexing",
366 };
367 }
368
369 await markComplete(results.del, IndexResultType.Delete);
370
371 yield {
372 progress: 1,
373 desc: "Completed Calculating Embeddings",
374 status: "done",
375 };
376 }
377
378 private async _retrieveForTag(
379 tag: IndexTag,
380 n: number,
381 directory: string | undefined,
382 vector: number[],
383 db: any,
384 ): Promise<LanceDbRow[]> {
385 const tableName = this.tableNameForTag(tag);
386 const tableNames = await db.tableNames();
387 if (!tableNames.includes(tableName)) {
388 console.warn("Table not found in LanceDB", tableName);
389 return [];
390 }
391
392 const table = await db.openTable(tableName);
393 let query = table.search(vector);
394 if (directory) {
395 query = query.where(`path LIKE '${directory}%'`).limit(300);
396 } else {
397 query = query.limit(n);
398 }
399 const results = await query.execute();
400 return results.slice(0, n) as any;
401 }
402
403 async retrieve(
404 query: string,
405 n: number,
406 tags: BranchAndDir[],
407 filterDirectory: string | undefined,
408 ): Promise<Chunk[]> {
409 const lance = LanceDbIndex.lance!;
410 if (!this.embeddingsProvider) {
411 return [];
412 }
413
414 // Use just the first chunk of the user query in case it is too long
415 const chunks = [];
416 for await (const chunk of basicChunker(
417 query,
418 this.embeddingsProvider.maxEmbeddingChunkSize,
419 )) {
420 chunks.push(chunk);
421 }
422 let vector = null;
423 try {
424 [vector] = await this.embeddingsProvider.embed(
425 chunks.map((c) => c.content),
426 );
427 } catch (err) {
428 // If we fail to chunk, we just use what was happening before.
429 [vector] = await this.embeddingsProvider.embed([query]);
430 }
431
432 const db = await lance.connect(getLanceDbPath());
433
434 let allResults = [];
435 for (const tag of tags) {
436 const results = await this._retrieveForTag(
437 { ...tag, artifactId: this.artifactId },
438 n,
439 filterDirectory,
440 vector,
441 db,
442 );
443 allResults.push(...results);
444 }
445
446 allResults = allResults
447 .sort((a, b) => a._distance - b._distance)
448 .slice(0, n);
449
450 const sqliteDb = await SqliteDb.get();
451 const data = await sqliteDb.all(
452 `SELECT * FROM lance_db_cache WHERE uuid in (${allResults
453 .map((r) => `'${r.uuid}'`)
454 .join(",")})`,
455 );
456
457 return data.map((d) => {
458 return {
459 digest: d.cacheKey,
460 filepath: d.path,
461 startLine: d.startLine,
462 endLine: d.endLine,
463 index: 0,
464 content: d.contents,
465 };
466 });
467 }
468
469 private async insertRows(
470 db: DatabaseConnection,
471 rows: LanceDbRow[],
472 ): Promise<void> {
473 return new Promise<void>((resolve, reject) => {
474 db.db.serialize(() => {
475 db.db.exec("BEGIN", (err: Error | null) => {
476 if (err) {
477 reject(new Error("error creating transaction", { cause: err }));
478 }
479 });
480
481 const sql =
482 "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
483 rows.map((r) => {
484 db.db.run(
485 sql,
486 [
487 r.uuid,
488 r.cachekey,
489 r.path,
490 this.artifactId,
491 JSON.stringify(r.vector),
492 r.startLine,
493 r.endLine,
494 r.contents,
495 ],
496 (result: RunResult, err: Error) => {
497 if (err) {
498 reject(
499 new Error("error inserting into lance_db_cache table", {
500 cause: err,
501 }),
502 );
503 }
504 },
505 );
506 });
507 db.db.exec("COMMIT", (err: Error | null) => {
508 if (err) {
509 reject(
510 new Error(
511 "error while committing insert into lance_db_rows transaction",
512 { cause: err },
513 ),
514 );
515 } else {
516 resolve();
517 }
518 });
519 });
520 });
521 }
522
523 private formatListPlurality(word: string, length: number): string {
524 return length <= 1 ? word : `${word}s`;
525 }
526}