Elffuss BraidHub

kikocis/continue public

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