Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: prune LanceDB chunk versions after indexing

nash_sue6dd70537496
diff --git a/src-tauri/src/commands/vectorstore.rs b/src-tauri/src/commands/vectorstore.rs
index 9f9d878c..6342434b 100644
--- a/src-tauri/src/commands/vectorstore.rs
+++ b/src-tauri/src/commands/vectorstore.rs
@@ -2,10 +2,13 @@ use arrow_array::{
ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, StringArray, UInt32Array,
};
use arrow_schema::{DataType, Field, Schema};
+use chrono::Duration;
use lancedb::connect;
use lancedb::query::{ExecutableQuery, QueryBase};
+use lancedb::table::{CompactionOptions, OptimizeAction};
use serde::{Deserialize, Serialize};
-use std::sync::Arc;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
use crate::panic_guard::run_guarded_async;
@@ -45,12 +48,24 @@ fn db_path(project_path: &str) -> String {
format!("{}/.llm-wiki/lancedb", project_path.replace('\\', "/"))
}
+fn vectorstore_v2_lock(project_path: &str) -> Arc<tokio::sync::RwLock<()>> {
+ let key = db_path(project_path);
+ let locks = VECTORSTORE_V2_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
+ let mut locks = locks.lock().expect("vectorstore lock map poisoned");
+ locks
+ .entry(key)
+ .or_insert_with(|| Arc::new(tokio::sync::RwLock::new(())))
+ .clone()
+}
+
/// v1 (legacy) table name. One row per page.
const TABLE_V1: &str = "wiki_vectors";
/// v2 (current) table name. One row per CHUNK — a page is typically
/// represented by multiple rows sharing the same `page_id`.
const TABLE_V2: &str = "wiki_chunks_v2";
const MAX_PAGE_ID_CHARS: usize = 256;
+static VECTORSTORE_V2_LOCKS: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::RwLock<()>>>>> =
+ OnceLock::new();
/// Validate page_id to prevent filter/path injection without rejecting
/// legitimate Unicode wiki filenames. Page ids are wiki file stems; CJK
@@ -450,6 +465,8 @@ pub async fn vector_upsert_chunks(
) -> Result<(), String> {
run_guarded_async("vector_upsert_chunks", async move {
validate_page_id_for_v2(&page_id)?;
+ let lock = vectorstore_v2_lock(&project_path);
+ let _guard = lock.write().await;
if chunks.is_empty() {
return Ok(());
@@ -519,6 +536,9 @@ pub async fn vector_search_chunks(
top_k: usize,
) -> Result<Vec<ChunkSearchResult>, String> {
run_guarded_async("vector_search_chunks", async move {
+ let lock = vectorstore_v2_lock(&project_path);
+ let _guard = lock.read().await;
+
let db = connect(&db_path(&project_path))
.execute()
.await
@@ -605,6 +625,8 @@ pub async fn vector_search_chunks(
pub async fn vector_delete_page(project_path: String, page_id: String) -> Result<(), String> {
run_guarded_async("vector_delete_page", async move {
validate_page_id_for_v2(&page_id)?;
+ let lock = vectorstore_v2_lock(&project_path);
+ let _guard = lock.write().await;
let db = connect(&db_path(&project_path))
.execute()
@@ -642,6 +664,9 @@ pub async fn vector_delete_page(project_path: String, page_id: String) -> Result
#[tauri::command]
pub async fn vector_count_chunks(project_path: String) -> Result<usize, String> {
run_guarded_async("vector_count_chunks", async move {
+ let lock = vectorstore_v2_lock(&project_path);
+ let _guard = lock.read().await;
+
let db = connect(&db_path(&project_path))
.execute()
.await
@@ -679,6 +704,9 @@ pub async fn vector_count_chunks(project_path: String) -> Result<usize, String>
#[tauri::command]
pub async fn vector_clear_chunks(project_path: String) -> Result<(), String> {
run_guarded_async("vector_clear_chunks", async move {
+ let lock = vectorstore_v2_lock(&project_path);
+ let _guard = lock.write().await;
+
let db = connect(&db_path(&project_path))
.execute()
.await
@@ -703,6 +731,64 @@ pub async fn vector_clear_chunks(project_path: String) -> Result<(), String> {
.await
}
+/// Compact the v2 chunk table and prune old LanceDB versions after bulk
+/// embedding writes. This is intentionally a separate best-effort command so
+/// an already-successful rebuild is not reported as failed if maintenance hits
+/// a platform-specific LanceDB error.
+#[tauri::command]
+pub async fn vector_optimize_chunks(project_path: String) -> Result<(), String> {
+ run_guarded_async("vector_optimize_chunks", async move {
+ let lock = vectorstore_v2_lock(&project_path);
+ let _guard = lock.write().await;
+
+ let db = connect(&db_path(&project_path))
+ .execute()
+ .await
+ .map_err(|e| format!("DB connect error: {e}"))?;
+
+ let tables = db
+ .table_names()
+ .execute()
+ .await
+ .map_err(|e| format!("List tables error: {e}"))?;
+
+ if !tables.contains(&TABLE_V2.to_string()) {
+ return Ok(());
+ }
+
+ let table = db
+ .open_table(TABLE_V2)
+ .execute()
+ .await
+ .map_err(|e| format!("Open table error: {e}"))?;
+
+ table
+ .optimize(OptimizeAction::Compact {
+ options: CompactionOptions::default(),
+ remap_options: None,
+ })
+ .await
+ .map_err(|e| format!("Compact chunks error: {e}"))?;
+
+ table
+ .optimize(OptimizeAction::Prune {
+ // Keep only versions older than the current table snapshot.
+ // We deliberately leave `delete_unverified` disabled because
+ // users may run multiple app instances against the same
+ // project, and LanceDB documents forced unverified deletion as
+ // unsafe under concurrent cross-process access.
+ older_than: Some(Duration::try_seconds(0).expect("valid duration")),
+ delete_unverified: Some(false),
+ error_if_tagged_old_versions: Some(false),
+ })
+ .await
+ .map_err(|e| format!("Prune old chunk versions error: {e}"))?;
+
+ Ok(())
+ })
+ .await
+}
+
/// Report whether the legacy per-page v1 table exists with any rows —
/// the TS layer uses this to show a one-time "re-index to v2" prompt in
/// Settings → Embedding after upgrading. Returns 0 when v1 is absent or
@@ -830,6 +916,17 @@ mod tests_v2 {
.collect()
}
+ fn chunk_table_version_count(project_path: &PathBuf) -> usize {
+ let versions_dir = project_path
+ .join(".llm-wiki")
+ .join("lancedb")
+ .join(format!("{TABLE_V2}.lance"))
+ .join("_versions");
+ std::fs::read_dir(versions_dir)
+ .map(|entries| entries.filter_map(Result::ok).count())
+ .unwrap_or(0)
+ }
+
#[test]
fn page_id_validation_allows_unicode_wiki_stems() {
let page_id = "反硝化除磷·A2O:DPAO + 50% & x(测试),v1.2";
@@ -1059,6 +1156,35 @@ mod tests_v2 {
assert_eq!(vector_count_chunks(pp.clone()).await.unwrap(), 0);
}
+ #[tokio::test]
+ async fn v2_optimize_chunks_prunes_versions_and_preserves_rows() {
+ let p = tmp_project();
+ let pp = p.to_string_lossy().to_string();
+
+ vector_optimize_chunks(pp.clone()).await.unwrap();
+
+ for i in 0..6 {
+ let page_id = format!("page-{i}");
+ vector_upsert_chunks(pp.clone(), page_id.clone(), make_chunks(&page_id, 2, 16))
+ .await
+ .unwrap();
+ }
+ assert_eq!(vector_count_chunks(pp.clone()).await.unwrap(), 12);
+ let versions_before = chunk_table_version_count(&p);
+ assert!(
+ versions_before > 1,
+ "expected multiple LanceDB versions before optimize"
+ );
+
+ vector_optimize_chunks(pp.clone()).await.unwrap();
+ let versions_after = chunk_table_version_count(&p);
+ assert!(
+ versions_after < versions_before,
+ "expected optimize to prune old versions ({versions_before} -> {versions_after})"
+ );
+ assert_eq!(vector_count_chunks(pp.clone()).await.unwrap(), 12);
+ }
+
#[tokio::test]
async fn v2_rejects_mismatched_embedding_dimensions() {
let p = tmp_project();
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 3f98b157..1791039c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -226,6 +226,7 @@ pub fn run() {
commands::vectorstore::vector_delete_page,
commands::vectorstore::vector_count_chunks,
commands::vectorstore::vector_clear_chunks,
+ commands::vectorstore::vector_optimize_chunks,
commands::vectorstore::vector_legacy_row_count,
commands::vectorstore::vector_drop_legacy,
commands::claude_cli::claude_cli_detect,
diff --git a/src/lib/embedding.test.ts b/src/lib/embedding.test.ts
index 44fc6e46..edd1304f 100644
--- a/src/lib/embedding.test.ts
+++ b/src/lib/embedding.test.ts
@@ -44,6 +44,7 @@ import {
dropLegacyVectorTable,
getEmbeddingCount,
removePageEmbedding,
+ resetEmbeddingOptimizeAccountingForTests,
type PageSearchResult,
} from "./embedding"
@@ -77,6 +78,7 @@ function genericErrorResponse(status: number, body: string): Response {
beforeEach(() => {
mockInvoke.mockReset()
mockHttpFetch.mockReset()
+ resetEmbeddingOptimizeAccountingForTests()
})
// ── searchByEmbedding — chunk→page aggregation ─────────────────────
@@ -1072,6 +1074,44 @@ describe("embedPage", () => {
expect(emb[0]).not.toBe(0.1)
})
+ it("optimizes periodically for incremental page embeddings", async () => {
+ mockHttpFetch.mockImplementation(async () => okResponse([0.1, 0.2, 0.3]))
+
+ for (let i = 0; i < 20; i++) {
+ await embedPage("/tmp/incremental", `page-${i}`, `Page ${i}`, "body text", cfg)
+ }
+
+ const commands = mockInvoke.mock.calls.map((call) => call[0])
+ expect(commands.filter((command) => command === "vector_upsert_chunks")).toHaveLength(20)
+ expect(commands.filter((command) => command === "vector_optimize_chunks")).toHaveLength(1)
+ expect(commands[commands.length - 1]).toBe("vector_optimize_chunks")
+ })
+
+ it("does not optimize before the incremental threshold is reached", async () => {
+ mockHttpFetch.mockImplementation(async () => okResponse([0.1, 0.2, 0.3]))
+
+ for (let i = 0; i < 19; i++) {
+ await embedPage("/tmp/incremental-under-threshold", `page-${i}`, `Page ${i}`, "body text", cfg)
+ }
+
+ const commands = mockInvoke.mock.calls.map((call) => call[0])
+ expect(commands.filter((command) => command === "vector_upsert_chunks")).toHaveLength(19)
+ expect(commands).not.toContain("vector_optimize_chunks")
+ })
+
+ it("tracks incremental optimization thresholds per project", async () => {
+ mockHttpFetch.mockImplementation(async () => okResponse([0.1, 0.2, 0.3]))
+
+ for (let i = 0; i < 19; i++) {
+ await embedPage("/tmp/project-a", `page-${i}`, `Page ${i}`, "body text", cfg)
+ }
+ await embedPage("/tmp/project-b", "page-b", "Page B", "body text", cfg)
+
+ const commands = mockInvoke.mock.calls.map((call) => call[0])
+ expect(commands.filter((command) => command === "vector_upsert_chunks")).toHaveLength(20)
+ expect(commands).not.toContain("vector_optimize_chunks")
+ })
+
it("keeps successful chunks even when some fail, preserving original chunk_index gaps", async () => {
// Two 1100-char paragraphs under default opts produce exactly 3
// chunks after packing + merging + overlap. Fail the middle embed
@@ -1322,6 +1362,73 @@ describe("embedAllPages", () => {
expect(mockInvoke.mock.calls.map((call) => call[0])).not.toContain("vector_clear_chunks")
})
+ it("optimizes the chunk table after ordinary batch indexing succeeds", async () => {
+ listDirectoryMock.mockResolvedValueOnce(makeTree())
+ readFileMock.mockResolvedValue("# Title\n\nBody.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+
+ await embedAllPages("/proj", cfg)
+
+ const commands = mockInvoke.mock.calls.map((call) => call[0])
+ expect(commands.filter((command) => command === "vector_upsert_chunks")).toHaveLength(2)
+ expect(commands[commands.length - 1]).toBe("vector_optimize_chunks")
+ })
+
+ it("optimizes the chunk table after a forced rebuild succeeds", async () => {
+ listDirectoryMock.mockResolvedValueOnce(makeTree())
+ readFileMock.mockResolvedValue("# Title\n\nBody.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+
+ await embedAllPages("/proj", cfg, undefined, { clearExisting: true })
+
+ const commands = mockInvoke.mock.calls.map((call) => call[0])
+ expect(commands[0]).toBe("vector_clear_chunks")
+ expect(commands.filter((command) => command === "vector_upsert_chunks")).toHaveLength(2)
+ expect(commands[commands.length - 1]).toBe("vector_optimize_chunks")
+ })
+
+ it("does not fail indexing when chunk table optimization fails", async () => {
+ listDirectoryMock.mockResolvedValueOnce(makeTree())
+ readFileMock.mockResolvedValue("# Title\n\nBody.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
+ mockInvoke.mockImplementation(async (command) => {
+ if (command === "vector_optimize_chunks") {
+ throw new Error("lancedb optimize failed")
+ }
+ return undefined
+ })
+
+ await expect(embedAllPages("/proj", cfg)).resolves.toBe(2)
+ expect(mockInvoke.mock.calls.map((call) => call[0])).toContain("vector_optimize_chunks")
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining("LanceDB chunk optimization failed"),
+ )
+ warn.mockRestore()
+ })
+
+ it("does not fail forced rebuild when chunk table optimization fails", async () => {
+ listDirectoryMock.mockResolvedValueOnce(makeTree())
+ readFileMock.mockResolvedValue("# Title\n\nBody.")
+ mockHttpFetch.mockImplementation(async () => okResponse([0.5]))
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
+ mockInvoke.mockImplementation(async (command) => {
+ if (command === "vector_optimize_chunks") {
+ throw new Error("lancedb optimize failed")
+ }
+ return undefined
+ })
+
+ await expect(embedAllPages("/proj", cfg, undefined, { clearExisting: true })).resolves.toBe(2)
+ const commands = mockInvoke.mock.calls.map((call) => call[0])
+ expect(commands[0]).toBe("vector_clear_chunks")
+ expect(commands).toContain("vector_optimize_chunks")
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining("LanceDB chunk optimization failed"),
+ )
+ warn.mockRestore()
+ })
+
it("does not clear existing chunks when forced rebuild cannot embed every page", async () => {
listDirectoryMock.mockResolvedValueOnce([
{ name: "a.md", path: "/proj/wiki/a.md", is_dir: false },
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
index 2ac26ba8..8cd55c47 100644
--- a/src/lib/embedding.ts
+++ b/src/lib/embedding.ts
@@ -59,11 +59,17 @@ function isSafeExtraHeader(name: string, value: string): boolean {
* embed.
*/
let lastEmbeddingError: string | null = null
+const INCREMENTAL_OPTIMIZE_PAGE_THRESHOLD = 20
+const incrementalOptimizeCounts = new Map<string, number>()
export function getLastEmbeddingError(): string | null {
return lastEmbeddingError
}
+export function resetEmbeddingOptimizeAccountingForTests(): void {
+ incrementalOptimizeCounts.clear()
+}
+
// ── fetchEmbedding with auto-halve retry ────────────────────────────────
/**
@@ -423,6 +429,12 @@ async function vectorClearChunks(projectPath: string): Promise<void> {
})
}
+async function vectorOptimizeChunks(projectPath: string): Promise<void> {
+ await invoke("vector_optimize_chunks", {
+ projectPath: normalizePath(projectPath),
+ })
+}
+
export async function legacyVectorRowCount(projectPath: string): Promise<number> {
try {
return await invoke("vector_legacy_row_count", {
@@ -443,6 +455,27 @@ export async function clearChunkVectorTable(projectPath: string): Promise<void>
await vectorClearChunks(projectPath)
}
+async function optimizeChunkVectorTableBestEffort(projectPath: string): Promise<void> {
+ try {
+ await vectorOptimizeChunks(projectPath)
+ } catch (err) {
+ console.warn(
+ `[Embedding] LanceDB chunk optimization failed: ${err instanceof Error ? err.message : err}`,
+ )
+ }
+}
+
+async function noteIncrementalVectorWrite(projectPath: string): Promise<void> {
+ const pp = normalizePath(projectPath)
+ const count = (incrementalOptimizeCounts.get(pp) ?? 0) + 1
+ if (count < INCREMENTAL_OPTIMIZE_PAGE_THRESHOLD) {
+ incrementalOptimizeCounts.set(pp, count)
+ return
+ }
+ incrementalOptimizeCounts.set(pp, 0)
+ await optimizeChunkVectorTableBestEffort(pp)
+}
+
// ── Chunk enrichment ─────────────────────────────────────────────────────
/**
@@ -543,6 +576,7 @@ export async function embedPage(
title: string,
content: string,
cfg: EmbeddingConfig,
+ options?: { deferOptimization?: boolean },
): Promise<boolean> {
const t0 = performance.now()
const prepared = await preparePageEmbeddingRows(pageId, title, content, cfg)
@@ -557,6 +591,9 @@ export async function embedPage(
}
await vectorUpsertChunks(projectPath, pageId, prepared.page.rows)
+ if (!options?.deferOptimization) {
+ await noteIncrementalVectorWrite(projectPath)
+ }
const elapsed = Math.round(performance.now() - t0)
console.log(
`[Embedding] Indexed "${pageId}": ${prepared.page.rows.length}/${prepared.page.chunkCount} chunks (${prepared.page.failedChunks} skipped) in ${elapsed}ms`,
@@ -678,6 +715,10 @@ export async function embedAllPages(
)
}
+ if (written > 0) {
+ await optimizeChunkVectorTableBestEffort(pp)
+ }
+
return written
}
@@ -687,7 +728,7 @@ export async function embedAllPages(
try {
const content = await readFile(file.path)
const title = extractEmbeddingTitle(content, file.id)
- if (await embedPage(pp, file.id, title, content, cfg)) {
+ if (await embedPage(pp, file.id, title, content, cfg, { deferOptimization: true })) {
indexed++
}
} catch {
@@ -697,6 +738,10 @@ export async function embedAllPages(
if (onProgress) onProgress(done, mdFiles.length)
}
+ if (indexed > 0) {
+ await optimizeChunkVectorTableBestEffort(pp)
+ }
+
return indexed
}