Merge pull request #6554 from uinstinct/indexing-lock

feat: lock indexing until completion
This commit is contained in:
Dallin Romney 2025-07-11 00:07:41 -07:00 • committed by GitHub
commit cc154d30d1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 99 additions and 8 deletions

View file

@ -11,7 +11,6 @@ import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
@ -202,11 +201,6 @@ export class Core {
dataLogger.ideSettingsPromise = ideSettingsPromise;
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings

1
core/index.d.ts vendored
View file

@ -50,6 +50,7 @@ export interface IndexingProgressUpdate {
shouldClearIndexes?: boolean;
status:
| "loading"
| "waiting"
| "indexing"
| "done"
| "failed"

View file

@ -16,7 +16,7 @@ import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
@ -643,11 +643,47 @@ export class CodebaseIndexer {
);
}
/**
* We want to prevent sqlite concurrent write errors
* when there are 2 indexing happening from different windows.
* We want the other window to wait until the first window's indexing finishes.
* Incase the first window closes before indexing is finished,
* we want to unlock the IndexLock by checking the last timestamp.
*/
private async *waitForDBIndex(): AsyncGenerator<IndexingProgressUpdate> {
let foundLock = await IndexLock.isLocked();
while (foundLock?.locked) {
if ((Date.now() - foundLock.timestamp) / 1000 > 10) {
console.log(`${foundLock.dirs} is not being indexed... unlocking`);
await IndexLock.unlock();
break;
}
console.log(`indexing ${foundLock.dirs}`);
yield {
progress: 0,
desc: "",
status: "waiting",
};
await new Promise((resolve) => setTimeout(resolve, 1000));
foundLock = await IndexLock.isLocked();
}
}
public async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
for await (const update of this.waitForDBIndex()) {
this.updateProgress(update);
}
await IndexLock.lock(paths.join(", ")); // acquire the index lock to prevent multiple windows to begin indexing
const indexLockTimestampUpdateInterval = setInterval(
() => void IndexLock.updateTimestamp(),
5_000,
);
try {
for await (const update of this.refreshDirs(
paths,
@ -664,6 +700,9 @@ export class CodebaseIndexer {
await this.handleIndexingError(e);
}
clearInterval(indexLockTimestampUpdateInterval); // interval will also be cleared when window closes before indexing is finished
await IndexLock.unlock();
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", {

View file

@ -45,6 +45,16 @@ export class SqliteDb {
artifactId STRING NOT NULL
)`,
);
await db.exec(
`CREATE TABLE IF NOT EXISTS indexing_lock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
locked BOOLEAN NOT NULL,
timestamp INTEGER NOT NULL,
dirs STRING NOT NULL
)`,
);
// Delete duplicate rows from tag_catalog
await db.exec(`
DELETE FROM tag_catalog
@ -532,3 +542,47 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string {
export function truncateSqliteLikePattern(input: string, safety: number = 100) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
}
export class IndexLock {
private static getLockTableName() {
return "indexing_lock";
}
static async isLocked(): Promise<
{ locked: boolean; dirs: string; timestamp: number } | undefined | undefined
> {
const db = await SqliteDb.get();
const row = (await db.get(
`SELECT locked, dirs, timestamp FROM ${IndexLock.getLockTableName()} WHERE locked = ?`,
true,
)) as { locked: boolean; dirs: string; timestamp: number } | undefined;
return row;
}
static async lock(dirs: string) {
const db = await SqliteDb.get();
await db.run(
`INSERT INTO ${IndexLock.getLockTableName()} (locked, timestamp, dirs) VALUES (?, ?, ?)`,
true,
Date.now(),
dirs,
);
}
static async updateTimestamp() {
const db = await SqliteDb.get();
await db.run(
`UPDATE ${IndexLock.getLockTableName()} SET timestamp = ? where locked = ?`,
Date.now(),
true,
);
}
static async unlock() {
const db = await SqliteDb.get();
await db.run(
`DELETE FROM ${IndexLock.getLockTableName()} WHERE locked = ?`,
true,
);
}
}

View file

@ -111,7 +111,7 @@ function IndexingProgress() {
<div className="mt-4 flex flex-col">
<div className="mb-0 flex justify-between text-sm">
<IndexingProgressTitleText update={update} />
{update.status !== "loading" && (
{!["loading", "waiting"].includes(update.status) && (
<IndexingProgressIndicator update={update} />
)}
</div>

View file

@ -13,6 +13,7 @@ export interface IndexingProgressIndicatorProps {
const STATUS_TO_ICON: Record<IndexingProgressUpdate["status"], any> = {
disabled: null,
loading: null,
waiting: null,
indexing: ArrowPathIcon,
paused: PauseCircleIcon,
done: CheckCircleIcon,

View file

@ -11,6 +11,7 @@ const STATUS_TO_SUBTITLE_TEXT: Record<
> = {
done: "Click to re-index",
loading: "",
waiting: "",
indexing: "Click to pause",
paused: "Click to resume",
failed: "Click to retry",

View file

@ -8,6 +8,7 @@ export interface IndexingProgressTitleTextProps {
const STATUS_TO_TEXT: Record<IndexingProgressUpdate["status"], string> = {
done: "Indexing complete",
loading: "Initializing",
waiting: "Indexing other workspace",
indexing: "Indexing in-progress",
paused: "Indexing paused",
failed: "Indexing failed",