Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
perf(session): skip content loading and vector cleanup during deletion (#6165)
dingben2ef422561cec
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 91b2768b8..d8f2f6605 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -386,12 +386,12 @@ class SessionService:self._ensure_initialized()session_uri = canonical_session_uri(ctx, session_id)- session = await self.get(session_id, ctx)+ session = self.session(ctx, session_id)if not await session.exists():self._record_lifecycle_metric("delete", "error")raise NotFoundError(session_id, "session")- await self._viking_fs.rm(session_uri, recursive=True, ctx=ctx)+ await self._viking_fs.rm(session_uri, recursive=True, ctx=ctx, no_vector=True)if self._session_expiry_adapter is not None:from openviking.scheduling.expiry import SESSION_ITEM_TYPE, ItemIdentitydiff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.pyindex 7bba4648c..c2363a23a 100644--- a/openviking/storage/viking_fs/_ops.py+++ b/openviking/storage/viking_fs/_ops.py@@ -220,6 +220,8 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,lease_ref: Dict[str, Any] | None = None,auto_pathlock: bool = True,+ *,+ no_vector: bool = False,) -> Dict[str, Any]:"""Delete file/directory + recursively update vector index.@@ -230,6 +232,11 @@ class _OpsMixin:Raises ResourceBusyError when the target is locked by an ongoingoperation (e.g. semantic processing).+ Set ``no_vector`` only when the caller guarantees the target subtree+ has no vector/context records. This skips vector cleanup and directory traversal+ unless descendant ACL checks require it. Namespace permission checks+ and path locking still apply.+When ``auto_pathlock`` is False and no outer ``lease_ref`` is supplied,the VikingFS-level tree/exact lease is skipped and the underlying AGFSdelete runs with automatic pathlock disabled. Callers must guarantee the@@ -273,6 +280,8 @@ class _OpsMixin:raiseif recursive:await self._ensure_access(target_uri, ctx, action=AclAction.MANAGE)+ if no_vector:+ return {"estimated_deleted_count": 0}# Path does not exist: clean up any orphan index records and returnuris_to_delete = await self._collect_uris(path, recursive, ctx=ctx)uris_to_delete.append(target_uri)@@ -306,22 +315,29 @@ class _OpsMixin:raise ResourceBusyError(f"Resource is being processed: {uri}", uri=uri)try:+ check_descendant_acl = (+ is_dir+ and (not no_vector or is_acl_uri(target_uri))+ and await self._acl_enabled(ctx)+ )uris_to_delete = (await self._collect_uris(path,recursive,ctx=ctx,- strict=is_dir and await self._acl_enabled(ctx),+ strict=check_descendant_acl,)- if is_dir+ if is_dir and (not no_vector or check_descendant_acl)else [])uris_to_delete.append(target_uri)if is_dir:await self._ensure_access_many(uris_to_delete, ctx, action=AclAction.MANAGE)- real_ctx = self._ctx_or_default(ctx)- estimated_count = await _estimate_deleted_count(path, real_ctx)- await self._delete_from_vector_store(uris_to_delete, ctx=ctx)+ estimated_count = 0+ if not no_vector:+ real_ctx = self._ctx_or_default(ctx)+ estimated_count = await _estimate_deleted_count(path, real_ctx)+ await self._delete_from_vector_store(uris_to_delete, ctx=ctx)try:result = await self._async_agfs.rm(path,diff --git a/tests/service/test_session_service_delete.py b/tests/service/test_session_service_delete.pynew file mode 100644index 000000000..8c9ae28bb--- /dev/null+++ b/tests/service/test_session_service_delete.py@@ -0,0 +1,108 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from openviking.core.namespace import canonical_session_uri+from openviking.scheduling.expiry import SESSION_ITEM_TYPE, ItemIdentity+from openviking.server.identity import RequestContext, Role+from openviking.service.session_service import SessionService+from openviking.storage.viking_fs import VikingFS+from openviking_cli.exceptions import NotFoundError+from openviking_cli.session.user_id import UserIdentifier+from tests.utils.mock_agfs import MockLocalAGFS+++def session_storage(tmp_path):+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.ADMIN)+ agfs = MockLocalAGFS(root_path=tmp_path)+ vector = SimpleNamespace(count=AsyncMock(), delete_uris=AsyncMock())+ viking_fs = VikingFS(agfs=agfs, vector_store=vector)+ service = SessionService(viking_fs=viking_fs)+ session_id = "delete-session"+ session_uri = canonical_session_uri(ctx, session_id)+ path = viking_fs._uri_to_path(session_uri, ctx=ctx)+ agfs.write(f"{path}/messages.jsonl", "")+ agfs.write(f"{path}/.meta.json", "{}")+ sibling_path = viking_fs._uri_to_path(canonical_session_uri(ctx, "keep-session"), ctx=ctx)+ memory_path = viking_fs._uri_to_path(+ "viking://user/alice/memories/preferences/keep.md", ctx=ctx+ )+ agfs.write(f"{sibling_path}/messages.jsonl", "sibling messages")+ agfs.write(memory_path, "extracted memory")+ agfs.read = Mock(wraps=agfs.read)+ agfs.rm = Mock(wraps=agfs.rm)+ expiry = SimpleNamespace(unregister_after_delete=AsyncMock())+ service._session_expiry_adapter = expiry+ return SimpleNamespace(+ service=service,+ ctx=ctx,+ session_id=session_id,+ path=path,+ sibling_path=sibling_path,+ memory_path=memory_path,+ agfs=agfs,+ vector=vector,+ expiry=expiry,+ )++[email protected]("filename", ["messages.jsonl", ".meta.json"])+async def test_delete_does_not_read_or_parse_session_contents(session_storage, filename):+ state = session_storage+ state.agfs.write(f"{state.path}/{filename}", "malformed JSON")++ assert await state.service.delete(state.session_id, state.ctx) is True++ assert not state.agfs.exists(state.path)+ state.agfs.read.assert_not_called()+ state.vector.count.assert_not_awaited()+ state.vector.delete_uris.assert_not_awaited()+++async def test_delete_unregisters_expiry_only_after_removing_session(session_storage):+ state = session_storage++ async def unregister(identity):+ assert not state.agfs.exists(state.path)++ state.expiry.unregister_after_delete.side_effect = unregister++ assert await state.service.delete(state.session_id, state.ctx) is True++ state.agfs.rm.assert_called_once()+ state.expiry.unregister_after_delete.assert_awaited_once_with(+ ItemIdentity(SESSION_ITEM_TYPE, "acme", "alice", state.session_id)+ )+ assert state.agfs.read(f"{state.sibling_path}/messages.jsonl") == b"sibling messages"+ assert state.agfs.read(state.memory_path) == b"extracted memory"+++async def test_delete_missing_session_keeps_not_found_semantics(session_storage):+ state = session_storage++ with pytest.raises(NotFoundError, match="missing-session"):+ await state.service.delete("missing-session", state.ctx)++ state.agfs.rm.assert_not_called()+ state.expiry.unregister_after_delete.assert_not_awaited()+ assert state.agfs.exists(state.path)+++async def test_delete_failure_does_not_unregister_expiry(session_storage):+ state = session_storage+ state.agfs.rm.side_effect = OSError("storage delete failed")++ with pytest.raises(OSError, match="storage delete failed"):+ await state.service.delete(state.session_id, state.ctx)++ assert state.agfs.exists(state.path)+ state.expiry.unregister_after_delete.assert_not_awaited()diff --git a/tests/storage/test_session_delete_storage.py b/tests/storage/test_session_delete_storage.pynew file mode 100644index 000000000..f5e98983a--- /dev/null+++ b/tests/storage/test_session_delete_storage.py@@ -0,0 +1,244 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++"""Unindexed deletion avoids vector work while retaining storage safety checks."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from openviking.core.namespace import resolve_request_uri+from openviking.server.identity import RequestContext, Role+from openviking.storage.acl import AclEntry, AclLevel, AclMode, DirectAcl, EffectiveAcl+from openviking.storage.errors import LockAcquisitionError, ResourceBusyError+from openviking.storage.viking_fs import VikingFS+from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedError+from openviking_cli.session.user_id import UserIdentifier++SESSION_URI = "viking://user/alice/sessions/session-1"+SESSION_PATH = "/local/account/user/alice/sessions/session-1"+RESOURCE_URI = "viking://resources/project"+RESOURCE_PATH = "/local/account/resources/project"+++def storage():+ """Use real URI, authorization, lock-context, and vector cleanup behavior."""+ lease = {"lease_ref": "delete-lease"}+ agfs = SimpleNamespace(+ stat=AsyncMock(return_value={"isDir": True}),+ ls=AsyncMock(return_value=[]),+ pathlock_acquire_tree=AsyncMock(return_value=lease),+ pathlock_acquire_exact=AsyncMock(return_value=lease),+ pathlock_release=AsyncMock(),+ rm=AsyncMock(return_value={}),+ )+ vector = SimpleNamespace(count=AsyncMock(return_value=7), delete_uris=AsyncMock())+ acl = SimpleNamespace(is_enabled=AsyncMock(return_value=False), resolve_many=AsyncMock())+ fs = VikingFS(agfs=SimpleNamespace(), vector_store=vector, acl_manager=acl)+ fs._async_agfs = agfs+ fs._collect_uris = AsyncMock(return_value=[])+ ctx = RequestContext(user=UserIdentifier("account", "alice"), role=Role.USER)+ return SimpleNamespace(fs=fs, agfs=agfs, vector=vector, acl=acl, ctx=ctx, lease=lease)++[email protected]("acl_enabled", [False, True])+ "request_uri",+ [+ SESSION_URI,+ "viking://session/session-1",+ "viking://~/sessions/session-1",+ "viking://temp/alice/raw-upload-1",+ ],+)+async def test_no_vector_rm_skips_subtree_enumeration_and_vector_store(+ storage, acl_enabled, request_uri+):+ storage.acl.is_enabled.return_value = acl_enabled+ uri = resolve_request_uri(request_uri, storage.ctx)+ path = storage.fs._uri_to_path(uri, ctx=storage.ctx)++ result = await storage.fs.rm(uri, recursive=True, ctx=storage.ctx, no_vector=True)++ assert result == {"estimated_deleted_count": 0}+ storage.fs._collect_uris.assert_not_awaited()+ storage.agfs.ls.assert_not_awaited()+ storage.vector.count.assert_not_awaited()+ storage.vector.delete_uris.assert_not_awaited()+ storage.agfs.pathlock_acquire_tree.assert_awaited_once_with(path)+ storage.agfs.pathlock_acquire_exact.assert_not_awaited()+ storage.agfs.rm.assert_awaited_once_with(+ path,+ recursive=True,+ fs_ctx={"account_id": "account", "lease_ref": "delete-lease"},+ auto_pathlock=True,+ )+ storage.agfs.pathlock_release.assert_awaited_once_with(storage.lease)+++async def test_session_file_rm_keeps_exact_lock_and_skips_vector_store(storage):+ storage.agfs.stat.return_value = {"isDir": False}+ uri = f"{SESSION_URI}/messages.jsonl"+ path = f"{SESSION_PATH}/messages.jsonl"++ result = await storage.fs.rm(uri, ctx=storage.ctx, no_vector=True)++ assert result == {"estimated_deleted_count": 0}+ storage.fs._collect_uris.assert_not_awaited()+ storage.vector.count.assert_not_awaited()+ storage.vector.delete_uris.assert_not_awaited()+ storage.agfs.pathlock_acquire_tree.assert_not_awaited()+ storage.agfs.pathlock_acquire_exact.assert_awaited_once_with(path)+ storage.agfs.rm.assert_awaited_once_with(+ path,+ recursive=False,+ fs_ctx={"account_id": "account", "lease_ref": "delete-lease"},+ auto_pathlock=True,+ )+ storage.agfs.pathlock_release.assert_awaited_once_with(storage.lease)+++async def test_session_directory_rm_still_requires_recursive(storage):+ with pytest.raises(InvalidArgumentError, match="recursive"):+ await storage.fs.rm(SESSION_URI, ctx=storage.ctx, no_vector=True)++ storage.agfs.pathlock_acquire_tree.assert_not_awaited()+ storage.agfs.pathlock_acquire_exact.assert_not_awaited()+ storage.agfs.rm.assert_not_awaited()+ storage.vector.count.assert_not_awaited()+ storage.vector.delete_uris.assert_not_awaited()++[email protected]("acl_enabled", [False, True])[email protected]("uri", [SESSION_URI, "viking://temp/alice/raw-upload-1"])+async def test_missing_no_vector_rm_does_not_scan_or_clean_vector_records(+ storage, acl_enabled, uri+):+ storage.acl.is_enabled.return_value = acl_enabled+ storage.agfs.stat.side_effect = FileNotFoundError(SESSION_PATH)++ result = await storage.fs.rm(uri, recursive=True, ctx=storage.ctx, no_vector=True)++ assert result == {"estimated_deleted_count": 0}+ storage.fs._collect_uris.assert_not_awaited()+ storage.vector.count.assert_not_awaited()+ storage.vector.delete_uris.assert_not_awaited()+ storage.agfs.pathlock_acquire_tree.assert_not_awaited()+ storage.agfs.rm.assert_not_awaited()+++async def test_session_rm_releases_its_tree_lease_when_backend_delete_fails(storage):+ storage.agfs.rm.side_effect = OSError("storage delete failed")++ with pytest.raises(OSError, match="storage delete failed"):+ await storage.fs.rm(SESSION_URI, recursive=True, ctx=storage.ctx, no_vector=True)++ storage.agfs.pathlock_release.assert_awaited_once_with(storage.lease)+ assert storage.agfs.rm.await_args.kwargs["fs_ctx"]["lease_ref"] == "delete-lease"+++async def test_session_rm_reuses_outer_lease_without_releasing_it(storage):+ outer_lease = {"lease_ref": "outer-lease"}++ await storage.fs.rm(+ SESSION_URI, recursive=True, ctx=storage.ctx, lease_ref=outer_lease, no_vector=True+ )++ storage.agfs.pathlock_acquire_tree.assert_not_awaited()+ storage.agfs.pathlock_release.assert_not_awaited()+ assert storage.agfs.rm.await_args.kwargs["fs_ctx"]["lease_ref"] == "outer-lease"+++async def test_session_rm_preserves_retryable_busy_error(storage):+ storage.agfs.pathlock_acquire_tree.side_effect = LockAcquisitionError("path is locked")++ with pytest.raises(ResourceBusyError) as error:+ await storage.fs.rm(SESSION_URI, recursive=True, ctx=storage.ctx, no_vector=True)++ assert error.value.uri == SESSION_URI+ assert error.value.conflict_type == "path_busy"+ assert error.value.retryable is True+ storage.agfs.rm.assert_not_awaited()+ storage.agfs.pathlock_release.assert_not_awaited()++[email protected]("acl_enabled", [False, True])+ "uri",+ ["viking://user/bob/sessions/session-1", f"{SESSION_URI}/../another-session"],+)+async def test_session_rm_preserves_namespace_and_path_validation(storage, acl_enabled, uri):+ storage.acl.is_enabled.return_value = acl_enabled++ with pytest.raises(PermissionDeniedError):+ await storage.fs.rm(uri, recursive=True, ctx=storage.ctx, no_vector=True)++ storage.agfs.stat.assert_not_awaited()+ storage.agfs.pathlock_acquire_tree.assert_not_awaited()+ storage.agfs.rm.assert_not_awaited()+ storage.vector.delete_uris.assert_not_awaited()++[email protected]("missing", [False, True])[email protected]("uri", [RESOURCE_URI, SESSION_URI])+async def test_default_rm_still_cleans_vector_records(storage, missing, uri):+ child_uri = f"{uri}/document.md"+ storage.fs._collect_uris.return_value = [child_uri]+ if missing:+ storage.agfs.stat.side_effect = FileNotFoundError(RESOURCE_PATH)++ result = await storage.fs.rm(uri, recursive=True, ctx=storage.ctx)++ assert result == {"estimated_deleted_count": 7}+ storage.fs._collect_uris.assert_awaited_once()+ storage.vector.count.assert_awaited_once()+ assert storage.vector.count.await_args.kwargs["ctx"] == storage.ctx+ storage.vector.delete_uris.assert_awaited_once_with(storage.ctx, [child_uri, uri])+ if missing:+ storage.agfs.rm.assert_not_awaited()+ else:+ storage.agfs.rm.assert_awaited_once()+ storage.agfs.pathlock_release.assert_awaited_once_with(storage.lease)++[email protected]("no_vector", [False, True])[email protected]("child_allowed", [False, True])+async def test_resource_rm_still_checks_descendant_manage_acl(storage, no_vector, child_allowed):+ child_uri = f"{RESOURCE_URI}/restricted.md"+ storage.fs._collect_uris.return_value = [child_uri]+ storage.acl.is_enabled.return_value = True+ allowed = EffectiveAcl(+ AclMode.RESTRICTED,+ DirectAcl((AclEntry("user:alice", AclLevel.MANAGE),)),+ DirectAcl(),+ )+ denied = EffectiveAcl(AclMode.RESTRICTED, DirectAcl(), DirectAcl())++ async def resolve_many(uris, ctx):+ return {uri: denied if uri == child_uri and not child_allowed else allowed for uri in uris}++ storage.acl.resolve_many.side_effect = resolve_many++ if child_allowed:+ result = await storage.fs.rm(+ RESOURCE_URI, recursive=True, ctx=storage.ctx, no_vector=no_vector+ )+ assert result == {"estimated_deleted_count": 0 if no_vector else 7}+ storage.agfs.rm.assert_awaited_once()+ else:+ with pytest.raises(PermissionDeniedError, match="restricted.md"):+ await storage.fs.rm(RESOURCE_URI, recursive=True, ctx=storage.ctx, no_vector=no_vector)+ storage.agfs.rm.assert_not_awaited()++ storage.fs._collect_uris.assert_awaited_once_with(+ RESOURCE_PATH, True, ctx=storage.ctx, strict=True+ )+ if no_vector or not child_allowed:+ storage.vector.count.assert_not_awaited()+ storage.vector.delete_uris.assert_not_awaited()+ else:+ storage.vector.count.assert_awaited_once()+ storage.vector.delete_uris.assert_awaited_once_with(storage.ctx, [child_uri, RESOURCE_URI])+ storage.agfs.pathlock_release.assert_awaited_once_with(storage.lease)