Skip to content

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

fix(storage): recover stale startup locks on Windows (#1201)

Qin Haojie433406f21ad4
diff --git a/openviking/storage/vectordb/utils/stale_lock.py b/openviking/storage/vectordb/utils/stale_lock.py
index f73e97dea..9e700c28d 100644
--- a/openviking/storage/vectordb/utils/stale_lock.py
+++ b/openviking/storage/vectordb/utils/stale_lock.py
@@ -1,21 +1,23 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Stale RocksDB LOCK file cleanup for Windows.
+"""Stale RocksDB LOCK file cleanup for Windows and containerized startup.
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:
+termination. This also shows up in some Docker Desktop-on-Windows setups,
+where the container reports ``sys.platform == "linux"`` but the underlying
+storage semantics still leave stale ``LOCK`` files behind. These scenarios
+cause 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.
+Cleanup is intentionally conservative:
+- On native Windows, we attempt ``os.remove()`` directly. A live lock usually
+ raises ``PermissionError``, so we leave it alone.
+- In containers, we first probe the ``LOCK`` file with a non-blocking POSIX
+ file lock. We only remove the file if that probe succeeds, which avoids
+ unlinking a live RocksDB lock in normal Linux environments.
"""
from __future__ import annotations
@@ -35,14 +37,58 @@ _LOCK_GLOB_PATTERNS = [
os.path.join("**", "store", "LOCK"),
os.path.join("**", "LOCK"),
]
+_CONTAINER_MARKERS = ("/.dockerenv", "/run/.containerenv")
+
+
+def _is_containerized() -> bool:
+ """Best-effort detection for containerized runtimes."""
+ return any(os.path.exists(marker) for marker in _CONTAINER_MARKERS)
+
+
+def _should_clean_stale_rocksdb_locks() -> bool:
+ """Return whether startup should attempt stale LOCK cleanup."""
+ return sys.platform == "win32" or _is_containerized()
+
+
+def _can_reclaim_posix_lock(lock_path: str) -> bool:
+ """Return True when a POSIX LOCK file can be safely reclaimed.
+
+ We only use this in containerized non-Windows environments. If the
+ non-blocking probe cannot prove the lock is free, we skip cleanup.
+ """
+ try:
+ import fcntl
+ except ImportError:
+ logger.debug("fcntl unavailable, skipping RocksDB LOCK probe: %s", lock_path)
+ return False
+
+ try:
+ with open(lock_path, "r+b") as lock_file:
+ try:
+ fcntl.lockf(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ logger.debug("RocksDB LOCK is held by a live process, skipping: %s", lock_path)
+ return False
+ except OSError as exc:
+ logger.debug("Could not probe RocksDB LOCK %s: %s", lock_path, exc)
+ return False
+
+ try:
+ fcntl.lockf(lock_file.fileno(), fcntl.LOCK_UN)
+ except OSError:
+ pass
+ return True
+ except OSError as exc:
+ logger.debug("Could not open RocksDB LOCK %s for probe: %s", lock_path, exc)
+ return False
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.
+ remove each one. Live locks are skipped either by ``PermissionError`` on
+ Windows or by a failed non-blocking POSIX lock probe in containers.
Args:
data_dir: Root data directory (the path passed to
@@ -51,9 +97,7 @@ def clean_stale_rocksdb_locks(data_dir: str) -> int:
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.
+ if not _should_clean_stale_rocksdb_locks():
return 0
removed = 0
@@ -70,9 +114,14 @@ def clean_stale_rocksdb_locks(data_dir: str) -> int:
seen.add(normalized)
try:
+ if sys.platform != "win32" and not _can_reclaim_posix_lock(lock_path):
+ continue
os.remove(lock_path)
removed += 1
logger.info("Removed stale RocksDB LOCK: %s", lock_path)
+ except FileNotFoundError:
+ # Another startup path may have removed it already.
+ continue
except PermissionError:
# File is held by a live process — leave it alone.
logger.debug(
diff --git a/openviking/utils/process_lock.py b/openviking/utils/process_lock.py
index c8a92e959..77a5d7d56 100644
--- a/openviking/utils/process_lock.py
+++ b/openviking/utils/process_lock.py
@@ -43,15 +43,17 @@ def _is_pid_alive(pid: int) -> bool:
except PermissionError:
# Process exists but we can't signal it.
return True
- except OSError:
+ except (OSError, SystemError):
if sys.platform == "win32":
# On Windows, os.kill(pid, 0) raises OSError for stale or invalid
- # PIDs instead of ProcessLookupError. Common errors include:
+ # PIDs instead of ProcessLookupError. In some environments it can
+ # also bubble up as SystemError from the underlying Win32 wrapper.
+ # Common failures include:
# - WinError 87 "The parameter is incorrect"
# - WinError 11 "An attempt was made to load a program with an
# incorrect format"
- # Treat any OSError as "not alive" so stale lock files are
- # correctly reclaimed on Windows.
+ # Treat these as "not alive" so stale lock files are correctly
+ # reclaimed on Windows.
return False
raise
diff --git a/tests/storage/test_stale_lock.py b/tests/storage/test_stale_lock.py
index 4c3ef6013..5b508876a 100644
--- a/tests/storage/test_stale_lock.py
+++ b/tests/storage/test_stale_lock.py
@@ -1,87 +1,144 @@
"""Tests for stale RocksDB LOCK file cleanup."""
import os
-import sys
-import tempfile
+from pathlib import Path
-import pytest
-
-from openviking.storage.vectordb.utils.stale_lock import clean_stale_rocksdb_locks
+import openviking.storage.vectordb.utils.stale_lock as stale_lock_module
class TestStaleLockCleanup:
"""Tests for clean_stale_rocksdb_locks()."""
- def _create_lock_file(self, base_dir: str, *path_parts: str) -> str:
+ def _create_lock_file(self, base_dir: Path, *path_parts: str) -> Path:
"""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("")
+ lock_dir = base_dir.joinpath(*path_parts[:-1])
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ lock_path = lock_dir / path_parts[-1]
+ lock_path.write_text("")
return lock_path
- @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
- def test_removes_stale_lock_in_standard_layout(self):
+ def _set_runtime(
+ self,
+ monkeypatch,
+ *,
+ platform: str,
+ dockerenv: bool = False,
+ containerenv: bool = False,
+ ) -> None:
+ """Patch runtime detection for platform/container-specific tests."""
+ original_exists = os.path.exists
+
+ def _fake_exists(path: str) -> bool:
+ if path == "/.dockerenv":
+ return dockerenv
+ if path == "/run/.containerenv":
+ return containerenv
+ return original_exists(path)
+
+ monkeypatch.setattr(stale_lock_module.sys, "platform", platform)
+ monkeypatch.setattr(stale_lock_module.os.path, "exists", _fake_exists)
+
+ def test_removes_stale_lock_in_standard_layout_on_windows(self, tmp_path: Path, monkeypatch):
"""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)
+ lock_path = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="win32")
- removed = clean_stale_rocksdb_locks(tmpdir)
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
- assert removed == 1
- assert not os.path.exists(lock_path)
+ assert removed == 1
+ assert not lock_path.exists()
- @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
- def test_removes_multiple_collection_locks(self):
+ def test_removes_multiple_collection_locks_on_windows(self, tmp_path: Path, monkeypatch):
"""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):
+ lock1 = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ lock2 = self._create_lock_file(tmp_path, "vectordb", "memories", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="win32")
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 2
+ assert not lock1.exists()
+ assert not lock2.exists()
+
+ def test_no_error_on_empty_directory(self, tmp_path: Path, monkeypatch):
"""No crash when data_dir has no LOCK files."""
- with tempfile.TemporaryDirectory() as tmpdir:
- removed = clean_stale_rocksdb_locks(tmpdir)
- assert removed == 0
+ self._set_runtime(monkeypatch, platform="win32")
- @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific behavior")
- def test_no_error_on_nonexistent_directory(self):
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 0
+
+ def test_no_error_on_nonexistent_directory(self, monkeypatch):
"""No crash when data_dir does not exist."""
- removed = clean_stale_rocksdb_locks("/tmp/does_not_exist_ov_test")
+ self._set_runtime(monkeypatch, platform="win32")
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks("/tmp/does_not_exist_ov_test")
+
+ assert removed == 0
+
+ def test_noop_on_posix_without_container_marker(self, tmp_path: Path, monkeypatch):
+ """POSIX without container markers should remain a no-op."""
+ lock_path = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="linux")
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
assert removed == 0
+ assert lock_path.exists()
+
+ def test_container_dockerenv_enables_cleanup(self, tmp_path: Path, monkeypatch):
+ """Containerized Linux should reclaim stale LOCKs when /.dockerenv exists."""
+ lock_path = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="linux", dockerenv=True)
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 1
+ assert not lock_path.exists()
- @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):
+ def test_containerenv_marker_enables_cleanup(self, tmp_path: Path, monkeypatch):
+ """Containerized Linux should reclaim stale LOCKs when /run/.containerenv exists."""
+ lock_path = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="linux", containerenv=True)
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 1
+ assert not lock_path.exists()
+
+ def test_container_cleanup_skips_when_probe_cannot_reclaim(self, tmp_path: Path, monkeypatch):
+ """Container cleanup should skip LOCK files that fail the POSIX probe."""
+ lock_path = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="linux", dockerenv=True)
+ monkeypatch.setattr(stale_lock_module, "_can_reclaim_posix_lock", lambda _path: False)
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 0
+ assert lock_path.exists()
+
+ def test_permission_error_skips_live_lock_on_windows(self, tmp_path: Path, monkeypatch):
+ """PermissionError should be treated as a live Windows LOCK."""
+ lock_path = self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="win32")
+
+ def _raise_permission_error(path: str) -> None:
+ if path == str(lock_path):
+ raise PermissionError("file is in use")
+ raise AssertionError(f"Unexpected remove path: {path}")
+
+ monkeypatch.setattr(stale_lock_module.os, "remove", _raise_permission_error)
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 0
+ assert lock_path.exists()
+
+ def test_deduplicates_overlapping_patterns(self, tmp_path: Path, monkeypatch):
"""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
+ self._create_lock_file(tmp_path, "vectordb", "context", "store", "LOCK")
+ self._set_runtime(monkeypatch, platform="win32")
+
+ removed = stale_lock_module.clean_stale_rocksdb_locks(str(tmp_path))
+
+ assert removed == 1
diff --git a/tests/unit/test_process_lock.py b/tests/unit/test_process_lock.py
index b5774b496..836100031 100644
--- a/tests/unit/test_process_lock.py
+++ b/tests/unit/test_process_lock.py
@@ -8,6 +8,7 @@ from pathlib import Path
import pytest
+import openviking.utils.process_lock as process_lock_module
from openviking.utils.process_lock import (
LOCK_FILENAME,
DataDirectoryLocked,
@@ -94,6 +95,29 @@ class TestIsPidAlive:
"""Test that negative PID is not alive."""
assert _is_pid_alive(-1) is False
+ def test_windows_system_error_treated_as_stale(self, monkeypatch):
+ """Windows SystemError from os.kill(pid, 0) should be treated as stale."""
+
+ def _raise_system_error(_pid: int, _sig: int) -> None:
+ raise SystemError("win32 wrapper failure")
+
+ monkeypatch.setattr(process_lock_module.sys, "platform", "win32")
+ monkeypatch.setattr(process_lock_module.os, "kill", _raise_system_error)
+
+ assert _is_pid_alive(12345) is False
+
+ def test_non_windows_system_error_bubbles_up(self, monkeypatch):
+ """Non-Windows should not downgrade unexpected SystemError values."""
+
+ def _raise_system_error(_pid: int, _sig: int) -> None:
+ raise SystemError("unexpected failure")
+
+ monkeypatch.setattr(process_lock_module.sys, "platform", "linux")
+ monkeypatch.setattr(process_lock_module.os, "kill", _raise_system_error)
+
+ with pytest.raises(SystemError):
+ _is_pid_alive(12345)
+
class TestAcquireDataDirLock:
"""Test acquire_data_dir_lock function."""
@@ -180,6 +204,23 @@ class TestAcquireDataDirLock:
error_msg = str(exc_info.value)
assert str(tmp_path) in error_msg
+ def test_acquire_overwrites_windows_stale_lock_on_system_error(
+ self, tmp_path: Path, monkeypatch
+ ):
+ """Windows stale lock should be reclaimed when os.kill raises SystemError."""
+
+ def _raise_system_error(_pid: int, _sig: int) -> None:
+ raise SystemError("win32 wrapper failure")
+
+ (tmp_path / LOCK_FILENAME).write_text("12345")
+ monkeypatch.setattr(process_lock_module.sys, "platform", "win32")
+ monkeypatch.setattr(process_lock_module.os, "kill", _raise_system_error)
+
+ acquire_data_dir_lock(str(tmp_path))
+
+ stored_pid = int((tmp_path / LOCK_FILENAME).read_text().strip())
+ assert stored_pid == os.getpid()
+
class TestAcquireDataDirLockEdgeCases:
"""Test edge cases for acquire_data_dir_lock."""