update tests

This commit is contained in:
Patrick Erichsen 2024-08-15 17:08:54 -07:00
parent 657ad97def
commit b67fbe1749
4 changed files with 78 additions and 44 deletions

View file

@ -310,8 +310,8 @@ export class LanceDbIndex implements CodebaseIndex {
await this.insertRows(sqliteDb, dbRows);
await Promise.all(
results.compute.map((result) => {
addComputedLanceDbRows(
results.compute.map(async (result) => {
await addComputedLanceDbRows(
result,
dbRows.filter(
(row) =>
@ -335,14 +335,17 @@ export class LanceDbIndex implements CodebaseIndex {
);
const cachedItems = await stmt.all();
const lanceRows: LanceDbRow[] = cachedItems.map((item) => {
return {
const lanceRows: LanceDbRow[] = cachedItems.map(
({ uuid, vector, startLine, endLine, contents }) => ({
path,
uuid,
startLine,
endLine,
contents,
cachekey: cacheKey,
uuid: item.uuid,
vector: JSON.parse(item.vector),
};
});
vector: JSON.parse(vector),
}),
);
if (lanceRows.length > 0) {
if (needToCreateLanceTable) {
@ -369,9 +372,14 @@ export class LanceDbIndex implements CodebaseIndex {
// Delete or remove tag - remove from lance table)
if (!needToCreateLanceTable) {
const toDel = [...results.removeTag, ...results.del];
if (!lanceTable) {
lanceTable = await lanceDb.openTable(lanceTableName);
}
for (const { path, cacheKey } of toDel) {
// This is where the aforementioned lowercase conversion problem shows
await lanceTable?.delete(
await lanceTable.delete(
`cachekey = '${cacheKey}' AND path = '${path}'`,
);
@ -383,6 +391,7 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
}
await markComplete(results.removeTag, IndexResultType.RemoveTag);
// Delete - also remove from sqlite cache
@ -402,6 +411,7 @@ export class LanceDbIndex implements CodebaseIndex {
}
await markComplete(results.del, IndexResultType.Delete);
yield {
progress: 1,
desc: "Completed Calculating Embeddings",
@ -423,8 +433,7 @@ export class LanceDbIndex implements CodebaseIndex {
return [];
}
const table = await db.openTable(tableName);
let query = table.search(vector);
let query = db.search(vector);
if (directory) {
// seems like lancedb is only post-filtering, so have to return a bunch of results and slice after
query = query.where(`path LIKE '${directory}%'`).limit(300);
@ -441,12 +450,8 @@ export class LanceDbIndex implements CodebaseIndex {
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const lancedb = await import("vectordb");
if (!lancedb.connect) {
throw new Error("LanceDB failed to load a native module");
}
const [vector] = await this.embeddingsProvider.embed([query]);
const db = await lancedb.connect(getLanceDbPath());
const db = await lance.connect(getLanceDbPath());
let allResults = [];
for (const tag of tags) {

View file

@ -23,8 +23,8 @@ All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./
`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex`
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
## Known problems:
## Known problems
- `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table

View file

@ -3,7 +3,6 @@ import { IndexResultType } from "../../indexing/types";
import { testIde } from "../fixtures";
import { jest } from "@jest/globals";
import {
insertMockChunks,
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
@ -20,7 +19,6 @@ describe("ChunkCodebaseIndex", () => {
let index: LanceDbIndex;
let sqliteDb: DatabaseConnection;
let lanceDb: lance.Connection;
let lanceTableName: string;
async function getAllSqliteLanceDbCache() {
return await sqliteDb.all("SELECT * FROM lance_db_cache");
@ -39,26 +37,38 @@ describe("ChunkCodebaseIndex", () => {
sqliteDb = await SqliteDb.get();
lanceDb = await lance.connect(getLanceDbPath());
lanceTableName = index.tableNameForTag(mockTag);
});
/**
* Some notes on quirks of this test:
* - Currently, it appears that there is a race condition in LanceDB that
* requires us to re-open the table connection each time we want to read
* from it. Attempting to follow these docs did not resolve the issue:
* https://lancedb.github.io/lancedb/guides/tables/#consistency
*
* - We cannot open either the 'dev' or 'main' tag tables ubtil after we
* can assume they've been created through `updateIndexAndAwaitGenerator`
*/
it("should update the index and maintain expected database state", async () => {
const mainTag = mockTag;
const mainTagTableName = index.tableNameForTag(mainTag);
const devTag = { ...mockTag, branch: "dev" };
const devTagTableName = index.tableNameForTag(devTag);
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;
await insertMockChunks();
// Compute test - inserts into both LanceDB and Sqlite
await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete);
// Note that we must wait until the first call 'compute' result has been processed.
// The current functionality of the `update` function doesn't insert into the Lance DB
// table until this point. We need to wait for this event to avoid needing to create a
// mock embedding to instantiate the table with.
const table = await lanceDb.openTable(lanceTableName);
expect(await table.countRows()).toBe(1);
await updateIndexAndAwaitGenerator(
index,
"compute",
mockMarkComplete,
mainTag,
);
let mainTagTable = await lanceDb.openTable(mainTagTableName);
expect(await mainTagTable.countRows()).toBe(1);
expect((await getAllSqliteLanceDbCache()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
@ -66,24 +76,37 @@ describe("ChunkCodebaseIndex", () => {
);
// AddTag test - only inserts into Lance DB
await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete);
expect(await table.countRows()).toBe(1);
await updateIndexAndAwaitGenerator(
index,
"addTag",
mockMarkComplete,
devTag,
);
let devTagTable = await lanceDb.openTable(devTagTableName);
expect(await devTagTable.countRows()).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.AddTag,
);
// // RemoveTag test - only removes from Lance DB
await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete);
expect(await table.countRows()).toBe(1);
// RemoveTag - only removes from Lance DB
await updateIndexAndAwaitGenerator(
index,
"removeTag",
mockMarkComplete,
devTag,
);
devTagTable = await lanceDb.openTable(devTagTableName);
expect(await devTagTable.countRows()).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.RemoveTag,
);
// Delete test - only removes from Sqlite
await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete);
// Delete test - removes from LanceDB and Sqlite
await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete, mainTag);
mainTagTable = await lanceDb.openTable(mainTagTableName);
expect(await mainTagTable.countRows()).toBe(0);
expect((await getAllSqliteLanceDbCache()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],

View file

@ -3,7 +3,11 @@ import { IContinueServerClient } from "../../continueServer/interface";
import { testIde } from "../fixtures";
import { addToTestDir, TEST_DIR } from "../testUtils/testDir";
import { IndexTag } from "../..";
import { CodebaseIndex, RefreshIndexResults } from "../../indexing/types";
import {
CodebaseIndex,
PathAndCacheKey,
RefreshIndexResults,
} from "../../indexing/types";
import { jest } from "@jest/globals";
import { tagToString } from "../../indexing/refreshIndex";
@ -12,6 +16,7 @@ export const mockPathAndCacheKey = {
path: `${TEST_DIR}/${mockFilename}`,
cacheKey: "abc123",
};
export const mockFileContents = `\
def main():
print("Hello, world!")
@ -69,12 +74,13 @@ export async function insertMockChunks() {
export async function updateIndexAndAwaitGenerator(
index: CodebaseIndex,
resultType: keyof RefreshIndexResults,
mockMarkComplete: any,
markComplete: any,
tag: IndexTag = mockTag,
) {
const computeGenerator = index.update(
mockTag,
tag,
{ ...mockResults, [resultType]: [mockPathAndCacheKey] },
mockMarkComplete,
markComplete,
"test-repo",
);