Elffuss BraidHub

kikocis/continue public

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