Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(windows): clean stale RocksDB LOCK files on startup (#798)

REMRepo8e257449b6db
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 8a4ec618d..47bf3cb8c 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -236,6 +236,15 @@ class OpenVikingService:
acquire_data_dir_lock(self._config.storage.workspace)
+ # Clean up stale RocksDB LOCK files left by crashed processes.
+ # On Windows, these persist after process death and block PersistStore
+ # from opening (see https://github.com/volcengine/OpenViking/issues/650).
+ from openviking.storage.vectordb.utils.stale_lock import (
+ clean_stale_rocksdb_locks,
+ )
+
+ clean_stale_rocksdb_locks(self._config.storage.workspace)
+
if self._vikingdb_manager is None:
self._init_storage(
self._config.storage,
diff --git a/openviking/storage/vectordb/utils/stale_lock.py b/openviking/storage/vectordb/utils/stale_lock.py
new file mode 100644
index 000000000..2b4c61082
--- /dev/null
+++ b/openviking/storage/vectordb/utils/stale_lock.py
@@ -0,0 +1,92 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Stale RocksDB LOCK file cleanup for Windows.
+
+On Windows, RocksDB LOCK files can persist after a process crash because
+Windows does not always release file handles immediately after process
+termination. This causes subsequent ``PersistStore`` opens to fail with:
+
+ IO error: <path>/LOCK: The process cannot access the file because it
+ is being used by another process.
+
+The strategy is simple: attempt ``os.remove()`` on each LOCK file.
+- If the file is held by a live process, ``PermissionError`` is raised and
+ we leave it alone.
+- If the file is stale (no process holds it), the remove succeeds and the
+ next ``PersistStore`` open will recreate it cleanly.
+
+This is safe on all platforms but only necessary on Windows.
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+import sys
+
+from openviking_cli.utils import get_logger
+
+logger = get_logger(__name__)
+
+# RocksDB creates a LOCK file inside the store directory.
+# The standard layout is: <data_dir>/vectordb/<collection>/store/LOCK
+# but we also check <data_dir>/vectordb/*/LOCK for non-standard layouts.
+_LOCK_GLOB_PATTERNS = [
+ os.path.join("**", "store", "LOCK"),
+ os.path.join("**", "LOCK"),
+]
+
+
+def clean_stale_rocksdb_locks(data_dir: str) -> int:
+ """Remove stale RocksDB LOCK files under *data_dir*.
+
+ Scans for LOCK files matching known PersistStore paths and attempts to
+ remove each one. Files held by a live process raise ``PermissionError``
+ and are skipped.
+
+ Args:
+ data_dir: Root data directory (the path passed to
+ ``LocalCollectionAdapter`` or ``VectorDBBackendConfig.path``).
+
+ Returns:
+ Number of stale LOCK files successfully removed.
+ """
+ if sys.platform != "win32":
+ # On POSIX systems, RocksDB uses flock() which is automatically
+ # released when the process dies. No cleanup needed.
+ return 0
+
+ removed = 0
+ seen: set[str] = set()
+
+ for pattern in _LOCK_GLOB_PATTERNS:
+ full_pattern = os.path.join(data_dir, pattern)
+ for lock_path in glob.glob(full_pattern, recursive=True):
+ # Normalize to avoid processing the same file twice from
+ # overlapping glob patterns.
+ normalized = os.path.normcase(os.path.abspath(lock_path))
+ if normalized in seen:
+ continue
+ seen.add(normalized)
+
+ try:
+ os.remove(lock_path)
+ removed += 1
+ logger.info("Removed stale RocksDB LOCK: %s", lock_path)
+ except PermissionError:
+ # File is held by a live process — leave it alone.
+ logger.debug(
+ "RocksDB LOCK is held by a live process, skipping: %s",
+ lock_path,
+ )
+ except OSError as exc:
+ logger.warning(
+ "Could not remove RocksDB LOCK %s: %s", lock_path, exc
+ )
+
+ if removed:
+ logger.info(
+ "Cleaned %d stale RocksDB LOCK file(s) under %s", removed, data_dir
+ )
+
+ return removed
diff --git a/tests/storage/test_stale_lock.py b/tests/storage/test_stale_lock.py
new file mode 100644
index 000000000..4c3ef6013
--- /dev/null
+++ b/tests/storage/test_stale_lock.py
@@ -0,0 +1,87 @@
+"""Tests for stale RocksDB LOCK file cleanup."""
+
+import os
+import sys
+import tempfile
+
+import pytest
+
+from openviking.storage.vectordb.utils.stale_lock import clean_stale_rocksdb_locks
+
+
+class TestStaleLockCleanup:
+ """Tests for clean_stale_rocksdb_locks()."""
+
+ def _create_lock_file(self, base_dir: str, *path_parts: str) -> str:
+ """Helper to create a LOCK file at the given path under base_dir."""
+ lock_dir = os.path.join(base_dir, *path_parts[:-1])
+ os.makedirs(lock_dir, exist_ok=True)
+ lock_path = os.path.join(lock_dir, path_parts[-1])
+ with open(lock_path, "w") as f:
+ f.write("")
+ return lock_path
+
+ @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
+ def test_removes_stale_lock_in_standard_layout(self):
+ """Stale LOCK at vectordb/<collection>/store/LOCK is removed."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lock_path = self._create_lock_file(
+ tmpdir, "vectordb", "context", "store", "LOCK"
+ )
+ assert os.path.exists(lock_path)
+
+ removed = clean_stale_rocksdb_locks(tmpdir)
+
+ assert removed == 1
+ assert not os.path.exists(lock_path)
+
+ @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
+ def test_removes_multiple_collection_locks(self):
+ """Handles multiple collections with stale LOCKs."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lock1 = self._create_lock_file(
+ tmpdir, "vectordb", "context", "store", "LOCK"
+ )
+ lock2 = self._create_lock_file(
+ tmpdir, "vectordb", "memories", "store", "LOCK"
+ )
+
+ removed = clean_stale_rocksdb_locks(tmpdir)
+
+ assert removed == 2
+ assert not os.path.exists(lock1)
+ assert not os.path.exists(lock2)
+
+ @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
+ def test_no_error_on_empty_directory(self):
+ """No crash when data_dir has no LOCK files."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ removed = clean_stale_rocksdb_locks(tmpdir)
+ assert removed == 0
+
+ @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
+ def test_no_error_on_nonexistent_directory(self):
+ """No crash when data_dir does not exist."""
+ removed = clean_stale_rocksdb_locks("/tmp/does_not_exist_ov_test")
+ assert removed == 0
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only: no-op expected")
+ def test_noop_on_posix(self):
+ """On POSIX systems, the function is a no-op (flock handles cleanup)."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ self._create_lock_file(
+ tmpdir, "vectordb", "context", "store", "LOCK"
+ )
+ removed = clean_stale_rocksdb_locks(tmpdir)
+ assert removed == 0
+
+ @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
+ def test_deduplicates_overlapping_patterns(self):
+ """Same LOCK file matched by multiple glob patterns is only counted once."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ # This LOCK matches both **/store/LOCK and **/LOCK patterns
+ self._create_lock_file(
+ tmpdir, "vectordb", "context", "store", "LOCK"
+ )
+ removed = clean_stale_rocksdb_locks(tmpdir)
+ assert removed == 1