Indexing tests (#1979)

* fix missing insertion into lancedb index

* successfully running codebaseindex test

* await

* fix typo

* clean up indexing tests

* expectPlan
This commit is contained in:
Nate Sesti 2024-08-09 12:54:53 -07:00 • committed by GitHub
parent d2cfce9e64
commit 7582aa8240
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 338 additions and 221 deletions

3
core/.gitignore vendored
View file

@ -3,4 +3,5 @@ target
**/.DS_Store
npm-debug.log*
.env
.continue-test
.continue-test
testDir

View file

@ -587,7 +587,9 @@ async function loadFullConfigNode(
// Try config.ts first
const configJsPath = getConfigJsPath();
const module = await import(configJsPath);
delete require.cache[require.resolve(configJsPath)];
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPath)];
}
if (!module.modifyConfig) {
throw new Error("config.ts does not export a modifyConfig function.");
}
@ -604,7 +606,9 @@ async function loadFullConfigNode(
ideSettings.remoteConfigServerUrl,
);
const module = await import(configJsPathForRemote);
delete require.cache[require.resolve(configJsPathForRemote)];
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPathForRemote)];
}
if (!module.modifyConfig) {
throw new Error("config.ts does not export a modifyConfig function.");
}

View file

@ -1,10 +1,10 @@
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import {
CodebaseIndex,
@ -28,12 +28,12 @@ export class PauseToken {
export class CodebaseIndexer {
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
protected readonly ide: IDE,
private readonly pauseToken: PauseToken,
private readonly continueServerClient: IContinueServerClient,
) {}
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const indexes = [

View file

@ -1,4 +1,5 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
@ -20,7 +21,6 @@ import {
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { RunResult } from "sqlite3";
// LanceDB converts to lowercase, so names must all be lowercase
interface LanceDbRow {
@ -269,7 +269,15 @@ export class LanceDbIndex implements CodebaseIndex {
console.log(results.compute);
const dbRows = await this.computeRows(results.compute);
this.insertRows(sqlite, dbRows);
await this.insertRows(sqlite, dbRows);
await Promise.all(
results.compute.map((item) => {
addComputedLanceDbRows(
item,
dbRows.filter((row) => row.path === item.path),
);
}),
);
await markComplete(results.compute, IndexResultType.Compute);
let accumulatedProgress = 0;

View file

@ -0,0 +1,69 @@
import type { IndexTag, IndexingProgressUpdate } from "../index.js";
import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types.js";
/**
* This is a CodebaseIndex used for testing which files get indexed.
* It maintains a SQLite database of all file/tag pairs
*/
export class TestCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 0.1;
artifactId = "__test__";
private static async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS test_index (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
branch TEXT NOT NULL,
directory TEXT NOT NULL
)`);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await TestCodebaseIndex._createTables(db);
for (const item of [...results.compute, ...results.addTag]) {
await db.run(
`INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`,
[item.path, tag.branch, tag.directory],
);
}
for (const item of [...results.del, ...results.removeTag]) {
await db.run(
`DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`,
[item.path, tag.branch, tag.directory],
);
}
markComplete(results.compute, IndexResultType.Compute);
markComplete(results.addTag, IndexResultType.AddTag);
markComplete(results.del, IndexResultType.Delete);
markComplete(results.removeTag, IndexResultType.RemoveTag);
}
async getIndexedFilesForTags(tags: IndexTag[]): Promise<string[]> {
const db = await SqliteDb.get();
await TestCodebaseIndex._createTables(db);
const rows = await db.all(
`SELECT path FROM test_index WHERE (branch, directory) IN (VALUES ${tags
.map(() => "(?, ?)")
.join(", ")})`,
tags.flatMap((tag) => [tag.branch, tag.directory]),
);
return rows.map((row: any) => row.path);
}
}

View file

@ -50,22 +50,24 @@ export async function* chunkDocument({
contents,
maxChunkSize,
)) {
chunkPromises.push(new Promise(async (resolve) => {
if (await countTokensAsync(chunkWithoutId.content) > maxChunkSize) {
console.debug(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
chunkPromises.push(
new Promise(async (resolve) => {
if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
console.debug(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
filepath,
countTokens(chunkWithoutId.content),
);
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index,
filepath,
countTokens(chunkWithoutId.content),
);
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index,
filepath,
});
}));
});
}),
);
index++;
}
for await (const chunk of chunkPromises) {

View file

@ -232,7 +232,7 @@ export async function* codeChunker(
const parser = await getParserForFile(filepath);
if (parser === undefined) {
console.warn(`Failed to load parser for file ${filepath}: `);
console.debug(`Failed to load parser for file ${filepath}: `);
return;
}

View file

@ -1,5 +1,9 @@
import fs from "fs";
import path from "path";
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
}
}

View file

@ -1,17 +1,17 @@
import {
SageMakerRuntimeClient,
InvokeEndpointWithResponseStreamCommand
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient
} from "@aws-sdk/client-sagemaker-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
const jinja = require("jinja-js");
// @ts-ignore
import jinja from "jinja-js";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
ModelProvider
} from "../../index.js";
import { BaseLLM } from "../index.js";

View file

@ -1,178 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { LanceDbIndex } from "../../indexing/LanceDbIndex.js";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import FileSystemIde from "../../util/filesystem.js";
import {
getIndexFolderPath,
getIndexSqlitePath,
getLanceDbPath,
} from "../../util/paths.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir.js";
import { jest } from "@jest/globals";
jest.useFakeTimers();
const TEST_TS = `\
function main() {
console.log("Hello, world!");
}
class Foo {
constructor(public bar: string) {}
}
`;
const TEST_PY = `\
def main():
print("Hello, world!")
class Foo:
def __init__(self, bar: str):
self.bar = bar
`;
const TEST_RS = `\
fn main() {
println!("Hello, world!");
}
struct Foo {
bar: String,
}
`;
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe.skip("CodebaseIndexer", () => {
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async (text) => {},
undefined as any, // TODO
);
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
const codebaseIndexer = new CodebaseIndexer(
configHandler,
ide,
pauseToken,
continueServerClient,
);
const lancedbIndex = new LanceDbIndex(
new TransformersJsEmbeddingsProvider(),
ide.readFile.bind(ide),
continueServerClient,
);
beforeAll(async () => {
setUpTestDir();
});
afterAll(async () => {
tearDownTestDir();
});
test("should index test folder without problem", async () => {
addToTestDir([
["test.ts", TEST_TS],
["py/main.py", TEST_PY],
]);
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
expect(updates.length).toBeGreaterThan(0);
});
test("should have created index folder with all necessary files", async () => {
expect(fs.existsSync(getIndexFolderPath())).toBe(true);
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
expect(fs.existsSync(getLanceDbPath())).toBe(true);
});
test("should be able to query lancedb index", async () => {
const chunks = await lancedbIndex.retrieve(
"What is the main function doing?",
10,
await ide.getTags(lancedbIndex.artifactId),
undefined,
);
expect(chunks.length).toBe(2);
// Check that the main function from both files is returned
expect(chunks.some((chunk) => chunk.filepath.endsWith("test.ts"))).toBe(
true,
);
expect(chunks.some((chunk) => chunk.filepath.endsWith("main.py"))).toBe(
true,
);
});
test("should successfully re-index after adding a file", async () => {
addToTestDir([["main.rs", TEST_RS]]);
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
expect(updates.length).toBeGreaterThan(0);
// Check that the new file was indexed
const chunks = await lancedbIndex.retrieve(
"What is the main function doing?",
3,
await ide.getTags(lancedbIndex.artifactId),
undefined,
);
expect(chunks.length).toBe(3);
expect(chunks.some((chunk) => chunk.filepath.endsWith("main.rs"))).toBe(
true,
);
});
test("should successfully re-index after deleting a file", async () => {
fs.rmSync(path.join(TEST_DIR, "main.rs"));
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
expect(updates.length).toBeGreaterThan(0);
// Check that the deleted file was removed from the index
const chunks = await lancedbIndex.retrieve(
"What is the main function doing?",
10,
await ide.getTags(lancedbIndex.artifactId),
undefined,
);
expect(chunks.length).toBe(2);
expect(chunks.every((chunk) => !chunk.filepath.endsWith("main.rs"))).toBe(
true,
);
});
});

View file

@ -0,0 +1,192 @@
import { jest } from "@jest/globals";
import fs from "node:fs";
import path from "node:path";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js";
import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js";
import { CodebaseIndex } from "../../indexing/types.js";
import { walkDir } from "../../indexing/walkDir.js";
import FileSystemIde from "../../util/filesystem.js";
import { getIndexSqlitePath } from "../../util/paths.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir.js";
jest.useFakeTimers();
const TEST_TS = `\
function main() {
console.log("Hello, world!");
}
class Foo {
constructor(public bar: string) {}
}
`;
const TEST_PY = `\
def main():
print("Hello, world!")
class Foo:
def __init__(self, bar: str):
self.bar = bar
`;
const TEST_RS = `\
fn main() {
println!("Hello, world!");
}
struct Foo {
bar: String,
}
`;
// A subclass of CodebaseIndexer that adds a new CodebaseIndex
class TestCodebaseIndexer extends CodebaseIndexer {
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
return [new TestCodebaseIndex()];
}
}
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined)),
);
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
const codebaseIndexer = new TestCodebaseIndexer(
configHandler,
ide,
pauseToken,
continueServerClient,
);
const testIndex = new TestCodebaseIndex();
beforeAll(async () => {
tearDownTestDir();
setUpTestDir();
});
afterAll(async () => {
tearDownTestDir();
});
async function refreshIndex() {
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
return updates;
}
async function getAllIndexedFiles() {
const files = await testIndex.getIndexedFilesForTags(
await ide.getTags(testIndex.artifactId),
);
return files;
}
async function getIndexPlan() {
const workspaceFiles = await walkDir(TEST_DIR, ide);
const [tag] = await ide.getTags(testIndex.artifactId);
const stats = await ide.getLastModified(workspaceFiles);
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => ide.readFile(filepath),
undefined,
);
return results;
}
async function expectPlan(
compute: number,
addTag: number,
removeTag: number,
del: number,
) {
const results = await getIndexPlan();
expect(results.compute).toHaveLength(compute);
expect(results.addTag).toHaveLength(addTag);
expect(results.removeTag).toHaveLength(removeTag);
expect(results.del).toHaveLength(del);
}
test("should index test folder without problem", async () => {
addToTestDir([
["test.ts", TEST_TS],
["py/main.py", TEST_PY],
]);
await expectPlan(2, 0, 0, 0);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
});
test("should have created index folder with all necessary files", async () => {
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
});
test("should have indexed all of the files", async () => {
const indexed = await getAllIndexedFiles();
expect(indexed.length).toBe(2);
expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
});
test("should successfully re-index after adding a file", async () => {
addToTestDir([["main.rs", TEST_RS]]);
await expectPlan(1, 0, 0, 0);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
// Check that the new file was indexed
const files = await getAllIndexedFiles();
expect(files.length).toBe(3);
expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
});
test("should successfully re-index after deleting a file", async () => {
fs.rmSync(path.join(TEST_DIR, "main.rs"));
await expectPlan(0, 0, 0, 1);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
// Check that the deleted file was removed from the index
const files = await getAllIndexedFiles();
expect(files.length).toBe(2);
expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
});
test("shouldn't index any files when nothing changed", async () => {
await expectPlan(0, 0, 0, 0);
});
});

View file

@ -11,17 +11,22 @@ export function setUpTestDir() {
}
export function tearDownTestDir() {
fs.rmSync(TEST_DIR, { recursive: true });
if (fs.existsSync(TEST_DIR)) {
fs.rmSync(TEST_DIR, { recursive: true });
}
}
export function addToTestDir(paths: (string | string[])[]) {
for (const p of paths) {
const filepath = path.join(TEST_DIR, Array.isArray(p) ? p[0] : p);
fs.mkdirSync(path.dirname(filepath), { recursive: true });
if (Array.isArray(p)) {
fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]);
fs.writeFileSync(filepath, p[1]);
} else if (p.endsWith("/")) {
fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true });
fs.mkdirSync(filepath, { recursive: true });
} else {
fs.writeFileSync(path.join(TEST_DIR, p), "");
fs.writeFileSync(filepath, "");
}
}
}

View file

@ -45,12 +45,17 @@ class FileSystemIde implements IDE {
async getGitHubAuthToken(): Promise<string | undefined> {
return undefined;
}
getLastModified(files: string[]): Promise<{ [path: string]: number }> {
return new Promise((resolve) => {
resolve({
[files[0]]: 1234567890,
});
});
async getLastModified(files: string[]): Promise<{ [path: string]: number }> {
const result: { [path: string]: number } = {};
for (const file of files) {
try {
const stats = fs.statSync(file);
result[file] = stats.mtimeMs;
} catch (error) {
console.error(`Error getting last modified time for ${file}:`, error);
}
}
return result;
}
getGitRootPath(dir: string): Promise<string | undefined> {
return Promise.resolve(dir);
@ -78,8 +83,13 @@ class FileSystemIde implements IDE {
return Promise.resolve(undefined);
}
getTags(artifactId: string): Promise<IndexTag[]> {
return Promise.resolve([]);
async getTags(artifactId: string): Promise<IndexTag[]> {
const directory =(await this.getWorkspaceDirs())[0]
return [{
artifactId,
branch: await this.getBranch(directory),
directory
}]
}
getIdeInfo(): Promise<IdeInfo> {

View file

@ -92,7 +92,7 @@ export async function getParserForFile(filepath: string) {
return parser;
} catch (e) {
console.error("Unable to load language for file", filepath, e);
console.debug("Unable to load language for file", filepath, e);
return undefined;
}
}
@ -120,7 +120,7 @@ export async function getLanguageForFile(
}
return language;
} catch (e) {
console.error("Unable to load language for file", filepath, e);
console.debug("Unable to load language for file", filepath, e);
return undefined;
}
}