From 1755280a6d417a0a35583c0b014d46ce081a32c0 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 10:03:32 -0700 Subject: [PATCH 1/7] Update LanceDbIndex.ts --- core/indexing/LanceDbIndex.ts | 122 ++++++++++++++++++---------------- 1 file changed, 65 insertions(+), 57 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 2e0054d5b..4c2954380 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -16,7 +16,6 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, - MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, } from "./types.js"; @@ -48,6 +47,8 @@ export class LanceDbIndex implements CodebaseIndex { } private async createSqliteCacheTable(db: DatabaseConnection) { + await db.exec("PRAGMA journal_mode=WAL;"); + await db.exec(`CREATE TABLE IF NOT EXISTS lance_db_cache ( uuid TEXT PRIMARY KEY, cacheKey TEXT NOT NULL, @@ -84,47 +85,6 @@ export class LanceDbIndex implements CodebaseIndex { ); } - private async packToRows(item: PathAndCacheKey): Promise { - const content = await this.readFile(item.path); - const chunks: Chunk[] = []; - const chunkParams = { - filepath: item.path, - contents: content, - maxChunkSize: this.embeddingsProvider.maxChunkSize, - digest: item.cacheKey, - }; - for await (const chunk of chunkDocument(chunkParams)) { - if (chunk.content.length === 0) { - // File did not chunk properly, let's skip it. - throw new Error("did not chunk properly"); - } - chunks.push(chunk); - if (chunks.length > 20) { - // Too many chunks to index, probably a larger file than we want to include - throw new Error("too large to index"); - } - } - const embeddings = await this.chunkListToEmbedding(chunks); - if (chunks.length !== embeddings.length) { - throw new Error( - `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, - ); - } - const results = []; - for (let i = 0; i < chunks.length; i++) { - results.push({ - path: item.path, - cachekey: item.cacheKey, - uuid: uuidv4(), - vector: embeddings[i], - startLine: chunks[i].startLine, - endLine: chunks[i].endLine, - contents: chunks[i].content, - }); - } - return results; - } - private async chunkListToEmbedding(chunks: Chunk[]): Promise { let embeddings: number[][]; try { @@ -146,22 +106,74 @@ export class LanceDbIndex implements CodebaseIndex { } private async computeRows(items: PathAndCacheKey[]): Promise { - const rowChunkPromises = items.map(this.packToRows.bind(this)); - const rowChunkLists = []; - for (let i = 0; i < items.length; i++) { + const allChunks: Chunk[] = []; + const chunkMap: Map = + new Map(); + + // First, collect all chunks + for (const item of items) { try { - rowChunkLists.push(await rowChunkPromises[i]); + const content = await this.readFile(item.path); + const chunks: Chunk[] = []; + const chunkParams = { + filepath: item.path, + contents: content, + maxChunkSize: this.embeddingsProvider.maxChunkSize, + digest: item.cacheKey, + }; + + for await (const chunk of chunkDocument(chunkParams)) { + if (chunk.content.length === 0) { + throw new Error("did not chunk properly"); + } + + chunks.push(chunk); + allChunks.push(chunk); + + if (chunks.length > 20) { + throw new Error("too large to index"); + } + } + + chunkMap.set(item.path, { item, chunks }); } catch (err) { - console.log(`LanceDBIndex, skipping ${items[i].path}: ${err}`); + console.log(`LanceDBIndex, skipping ${item.path}: ${err}`); } } - return rowChunkLists.flat(); + + // Now, get embeddings for all chunks in a single request + const embeddings = await this.chunkListToEmbedding(allChunks); + + // Associate embeddings back with their chunks and create LanceDbRows + const results: LanceDbRow[] = []; + + let embeddingIndex = 0; + + for (const [path, { item, chunks }] of chunkMap) { + for (const chunk of chunks) { + results.push({ + path, + cachekey: item.cacheKey, + uuid: uuidv4(), + vector: embeddings[embeddingIndex], + startLine: chunk.startLine, + endLine: chunk.endLine, + contents: chunk.content, + }); + embeddingIndex++; + } + } + + return results; } async *update( tag: IndexTag, results: RefreshIndexResults, - markComplete: MarkCompleteCallback, + markComplete: ( + items: PathAndCacheKey[], + resultType: IndexResultType, + ) => void, repoName: string | undefined, ): AsyncGenerator { const lancedb = await import("vectordb"); @@ -197,7 +209,7 @@ export class LanceDbIndex implements CodebaseIndex { } // Mark item complete - await markComplete([pathAndCacheKey], IndexResultType.Compute); + markComplete([pathAndCacheKey], IndexResultType.Compute); }; // Check remote cache @@ -265,12 +277,8 @@ export class LanceDbIndex implements CodebaseIndex { } ${this.formatListPlurality("file", results.compute.length)}`, status: "indexing", }; - - console.log(results.compute); - const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); - await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache @@ -305,7 +313,7 @@ export class LanceDbIndex implements CodebaseIndex { } } - await markComplete([{ path, cacheKey }], IndexResultType.AddTag); + markComplete([{ path, cacheKey }], IndexResultType.AddTag); accumulatedProgress += 1 / results.addTag.length / 3; yield { progress: accumulatedProgress, @@ -329,7 +337,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } } - await markComplete(results.removeTag, IndexResultType.RemoveTag); + markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { @@ -347,7 +355,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } - await markComplete(results.del, IndexResultType.Delete); + markComplete(results.del, IndexResultType.Delete); yield { progress: 1, desc: "Completed Calculating Embeddings", From 99d3add5f4787430a83510b8fd255a75069ed5de Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 10:03:45 -0700 Subject: [PATCH 2/7] Update LanceDbIndex.ts --- core/indexing/LanceDbIndex.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 4c2954380..6e6a3cc9e 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -47,8 +47,6 @@ export class LanceDbIndex implements CodebaseIndex { } private async createSqliteCacheTable(db: DatabaseConnection) { - await db.exec("PRAGMA journal_mode=WAL;"); - await db.exec(`CREATE TABLE IF NOT EXISTS lance_db_cache ( uuid TEXT PRIMARY KEY, cacheKey TEXT NOT NULL, From 137bc59a9e4d6a6874c0b7be9a87bb879c737433 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 10:06:48 -0700 Subject: [PATCH 3/7] Update LanceDbIndex.ts --- core/indexing/LanceDbIndex.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 6e6a3cc9e..0dbf6e5fb 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -16,6 +16,7 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, + MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, } from "./types.js"; @@ -168,10 +169,7 @@ export class LanceDbIndex implements CodebaseIndex { async *update( tag: IndexTag, results: RefreshIndexResults, - markComplete: ( - items: PathAndCacheKey[], - resultType: IndexResultType, - ) => void, + markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { const lancedb = await import("vectordb"); @@ -277,6 +275,7 @@ export class LanceDbIndex implements CodebaseIndex { }; const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); + await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache @@ -311,7 +310,7 @@ export class LanceDbIndex implements CodebaseIndex { } } - markComplete([{ path, cacheKey }], IndexResultType.AddTag); + await markComplete([{ path, cacheKey }], IndexResultType.AddTag); accumulatedProgress += 1 / results.addTag.length / 3; yield { progress: accumulatedProgress, @@ -335,7 +334,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } } - markComplete(results.removeTag, IndexResultType.RemoveTag); + await markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { @@ -353,7 +352,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } - markComplete(results.del, IndexResultType.Delete); + await markComplete(results.del, IndexResultType.Delete); yield { progress: 1, desc: "Completed Calculating Embeddings", From a77f2499e42bd135e4e1808dc719ac3c2ccbb8e7 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 11:13:06 -0700 Subject: [PATCH 4/7] handle undefined embeddings --- core/indexing/LanceDbIndex.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 0dbf6e5fb..17fcc46f7 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -143,6 +143,15 @@ export class LanceDbIndex implements CodebaseIndex { // Now, get embeddings for all chunks in a single request const embeddings = await this.chunkListToEmbedding(allChunks); + // We probably dont want to blow up all embedding here, + // maybe we just filter out the chunks alongside the undefined + // embeddings in `chunkListToEmbedding` + if (allChunks.length !== embeddings.length) { + throw new Error( + `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, + ); + } + // Associate embeddings back with their chunks and create LanceDbRows const results: LanceDbRow[] = []; @@ -205,7 +214,7 @@ export class LanceDbIndex implements CodebaseIndex { } // Mark item complete - markComplete([pathAndCacheKey], IndexResultType.Compute); + await markComplete([pathAndCacheKey], IndexResultType.Compute); }; // Check remote cache @@ -273,6 +282,9 @@ export class LanceDbIndex implements CodebaseIndex { } ${this.formatListPlurality("file", results.compute.length)}`, status: "indexing", }; + + console.log(results.compute); + const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); await markComplete(results.compute, IndexResultType.Compute); From 9f39e12d44b75bca7ff04ed6b38a7dbf2e0c516b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 13:32:31 -0700 Subject: [PATCH 5/7] break down computeRows --- .vscode/launch.json | 3 +- core/indexing/CodebaseIndexer.ts | 18 ++-- core/indexing/LanceDbIndex.ts | 128 +++++++++++++++------------- extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- 5 files changed, 82 insertions(+), 73 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 54d282cc8..bde875483 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -12,8 +12,7 @@ "cwd": "${workspaceFolder}/extensions/vscode", "args": [ // Pass a directory to manually test in - "${workspaceFolder}/manual-testing-sandbox", - "${workspaceFolder}/manual-testing-sandbox/test.js", + "${workspaceFolder}/extensions/vscode", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], "pauseForSourceMap": false, diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index efef51c72..9177aa510 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -26,6 +26,8 @@ export class PauseToken { } export class CodebaseIndexer { + batchSize = 100; + constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, @@ -266,11 +268,6 @@ export class CodebaseIndexer { } } - private getBatchSize(workspaceSize: number): number { - // at least 10 and as much as 100 (in a repository with 10000 files) - return Math.min(100, Math.max(10, Math.floor(workspaceSize / 100))); - } - /* * enables the indexing operation to be completed in small batches, this is important in large * repositories where indexing can quickly use up all the memory available @@ -280,7 +277,6 @@ export class CodebaseIndexer { workspaceSize: number, ): Generator { let curPos = 0; - const batchSize = this.getBatchSize(workspaceSize); while ( curPos < results.compute.length || curPos < results.del.length || @@ -288,12 +284,12 @@ export class CodebaseIndexer { curPos < results.removeTag.length ) { yield { - compute: results.compute.slice(curPos, curPos + batchSize), - del: results.del.slice(curPos, curPos + batchSize), - addTag: results.addTag.slice(curPos, curPos + batchSize), - removeTag: results.removeTag.slice(curPos, curPos + batchSize), + compute: results.compute.slice(curPos, curPos + this.batchSize), + del: results.del.slice(curPos, curPos + this.batchSize), + addTag: results.addTag.slice(curPos, curPos + this.batchSize), + removeTag: results.removeTag.slice(curPos, curPos + this.batchSize), }; - curPos += batchSize; + curPos += this.batchSize; } } diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 17fcc46f7..7c5aaa26d 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -31,6 +31,10 @@ interface LanceDbRow { [key: string]: any; } +type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] }; + +type ChunkMap = Map; + export class LanceDbIndex implements CodebaseIndex { relativeExpectedTime: number = 13; get artifactId(): string { @@ -84,77 +88,89 @@ export class LanceDbIndex implements CodebaseIndex { ); } - private async chunkListToEmbedding(chunks: Chunk[]): Promise { - let embeddings: number[][]; - try { - embeddings = await this.embeddingsProvider.embed( - chunks.map((c) => c.content), - ); - } catch (err) { - throw new Error( - `Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${err}`, - { cause: err }, - ); - } - if (embeddings.some((emb) => emb === undefined)) { - throw new Error( - `Empty embedding returned for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`, - ); - } - return embeddings; - } - private async computeRows(items: PathAndCacheKey[]): Promise { - const allChunks: Chunk[] = []; - const chunkMap: Map = - new Map(); + const chunkMap = await this.collectChunks(items); + const allChunks = Array.from(chunkMap.values()).flatMap( + ({ chunks }) => chunks, + ); + const embeddings = await this.getEmbeddings(allChunks); - // First, collect all chunks - for (const item of items) { - try { - const content = await this.readFile(item.path); - const chunks: Chunk[] = []; - const chunkParams = { - filepath: item.path, - contents: content, - maxChunkSize: this.embeddingsProvider.maxChunkSize, - digest: item.cacheKey, - }; + // Remove undefined embeddings and their corresponding chunks + for (let i = embeddings.length - 1; i >= 0; i--) { + if (embeddings[i] === undefined) { + const chunk = allChunks[i]; + const chunks = chunkMap.get(chunk.filepath)?.chunks; - for await (const chunk of chunkDocument(chunkParams)) { - if (chunk.content.length === 0) { - throw new Error("did not chunk properly"); - } - - chunks.push(chunk); - allChunks.push(chunk); - - if (chunks.length > 20) { - throw new Error("too large to index"); + if (chunks) { + const index = chunks.findIndex((c) => c === chunk); + if (index !== -1) { + chunks.splice(index, 1); } } + embeddings.splice(i, 1); + } + } + + return this.createLanceDbRows(chunkMap, embeddings); + } + + private async collectChunks(items: PathAndCacheKey[]): Promise { + const chunkMap: ChunkMap = new Map(); + + for (const item of items) { + try { + const content = await this.readFile(item.path); + const chunks = await this.getChunks(item, content); chunkMap.set(item.path, { item, chunks }); } catch (err) { console.log(`LanceDBIndex, skipping ${item.path}: ${err}`); } } - // Now, get embeddings for all chunks in a single request - const embeddings = await this.chunkListToEmbedding(allChunks); + return chunkMap; + } - // We probably dont want to blow up all embedding here, - // maybe we just filter out the chunks alongside the undefined - // embeddings in `chunkListToEmbedding` - if (allChunks.length !== embeddings.length) { - throw new Error( - `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, - ); + private async getChunks( + item: PathAndCacheKey, + content: string, + ): Promise { + const chunks: Chunk[] = []; + + const chunkParams = { + filepath: item.path, + contents: content, + maxChunkSize: this.embeddingsProvider.maxChunkSize, + digest: item.cacheKey, + }; + + for await (const chunk of chunkDocument(chunkParams)) { + if (chunk.content.length === 0) { + throw new Error("did not chunk properly"); + } + + chunks.push(chunk); } - // Associate embeddings back with their chunks and create LanceDbRows - const results: LanceDbRow[] = []; + return chunks; + } + private async getEmbeddings(chunks: Chunk[]): Promise { + try { + return await this.embeddingsProvider.embed(chunks.map((c) => c.content)); + } catch (err) { + throw new Error( + `Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.id}: ${err}`, + { cause: err }, + ); + } + } + + private createLanceDbRows( + chunkMap: ChunkMap, + embeddings: number[][], + ): LanceDbRow[] { + const results: LanceDbRow[] = []; let embeddingIndex = 0; for (const [path, { item, chunks }] of chunkMap) { @@ -283,8 +299,6 @@ export class LanceDbIndex implements CodebaseIndex { status: "indexing", }; - console.log(results.compute); - const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); await markComplete(results.compute, IndexResultType.Compute); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8a3b9674..a5fe4405d 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.196", + "version": "0.9.197", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.196", + "version": "0.9.197", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9d6006bcc..8cc156935 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.196", + "version": "0.9.197", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 3f62e66d96b65402f885c454f4046fb098d430bc Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 13:43:37 -0700 Subject: [PATCH 6/7] Update launch.json --- .vscode/launch.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index bde875483..54d282cc8 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -12,7 +12,8 @@ "cwd": "${workspaceFolder}/extensions/vscode", "args": [ // Pass a directory to manually test in - "${workspaceFolder}/extensions/vscode", + "${workspaceFolder}/manual-testing-sandbox", + "${workspaceFolder}/manual-testing-sandbox/test.js", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], "pauseForSourceMap": false, From 994c9c4dcf21119050496f197b2bf6b76d7a4bda Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 15:47:17 -0700 Subject: [PATCH 7/7] remove extra arg --- core/indexing/CodebaseIndexer.ts | 5 +---- extensions/vscode/package-lock.json | 1 + gui/package-lock.json | 1 + 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 3db9027e2..dfb53470d 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -334,10 +334,7 @@ export class CodebaseIndexer { results.addTag.length + results.removeTag.length; let completedOps = 0; - for (const subResult of this.batchRefreshIndexResults( - results, - workspaceFiles.length, - )) { + for (const subResult of this.batchRefreshIndexResults(results)) { for await (const { desc } of codebaseIndex.update( tag, subResult, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index a5fe4405d..6af742e21 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -130,6 +130,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", diff --git a/gui/package-lock.json b/gui/package-lock.json index 23ff1c5ac..3e67abbcc 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -123,6 +123,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0",