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
fix(watch): 避免资源移动期间持有全局锁 (#3833)
Kchen8acaf7f872be
diff --git a/openviking/resource/uri_mutation_coordinator.py b/openviking/resource/uri_mutation_coordinator.pynew file mode 100644index 000000000..16a3b62ee--- /dev/null+++ b/openviking/resource/uri_mutation_coordinator.py@@ -0,0 +1,102 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Process-local coordination for operations that depend on stable URI scopes."""++import asyncio+from contextlib import asynccontextmanager+from dataclasses import dataclass+from typing import AsyncIterator, Optional, Sequence+++def _normalize_uri(uri: str) -> str:+ return uri.rstrip("/")+++def _normalize_uris(uris: Sequence[Optional[str]]) -> tuple[str, ...]:+ return tuple(sorted({_normalize_uri(uri) for uri in uris if uri}))+++def uri_matches_prefix(uri: Optional[str], prefix: str) -> bool:+ """Return whether *uri* is equal to or below *prefix* on a path boundary."""+ if not uri:+ return False+ normalized_uri = _normalize_uri(uri)+ normalized_prefix = _normalize_uri(prefix)+ return normalized_uri == normalized_prefix or normalized_uri.startswith(f"{normalized_prefix}/")+++def _uris_overlap(left: tuple[str, ...], right: tuple[str, ...]) -> bool:+ return any(+ uri_matches_prefix(left_uri, right_uri) or uri_matches_prefix(right_uri, left_uri)+ for left_uri in left+ for right_uri in right+ )+++@dataclass(eq=False, frozen=True)+class _UriLease:+ account_id: str+ uris: tuple[str, ...]++ def overlaps(self, other: "_UriLease") -> bool:+ return self.account_id == other.account_id and _uris_overlap(self.uris, other.uris)+++class UriMutationCoordinator:+ """Coordinate stable URI access and URI mutations within one process."""++ def __init__(self) -> None:+ self._condition = asyncio.Condition()+ self._active_accesses: list[_UriLease] = []+ self._active_mutations: list[_UriLease] = []++ @asynccontextmanager+ async def access(+ self,+ account_id: str,+ uris: Sequence[Optional[str]],+ ) -> AsyncIterator[None]:+ """Hold a lease requiring the supplied URI scopes to remain stable."""+ lease = _UriLease(account_id=account_id, uris=_normalize_uris(uris))+ await self._acquire(lease, mutation=False)+ try:+ yield+ finally:+ await self._release(lease, mutation=False)++ @asynccontextmanager+ async def mutation(+ self,+ account_id: str,+ uris: Sequence[Optional[str]],+ ) -> AsyncIterator[None]:+ """Hold an exclusive lease for mutating the supplied URI scopes."""+ lease = _UriLease(account_id=account_id, uris=_normalize_uris(uris))+ await self._acquire(lease, mutation=True)+ try:+ yield+ finally:+ await self._release(lease, mutation=True)++ async def _acquire(self, lease: _UriLease, *, mutation: bool) -> None:+ async with self._condition:+ while self._has_blocker(lease, mutation=mutation):+ await self._condition.wait()+ self._active_leases(mutation=mutation).append(lease)++ async def _release(self, lease: _UriLease, *, mutation: bool) -> None:+ async with self._condition:+ active = self._active_leases(mutation=mutation)+ for index, current in enumerate(active):+ if current is lease:+ del active[index]+ break+ self._condition.notify_all()++ def _has_blocker(self, lease: _UriLease, *, mutation: bool) -> bool:+ if any(lease.overlaps(active) for active in self._active_mutations):+ return True+ return mutation and any(lease.overlaps(active) for active in self._active_accesses)++ def _active_leases(self, *, mutation: bool) -> list[_UriLease]:+ return self._active_mutations if mutation else self._active_accessesdiff --git a/openviking/resource/watch_manager.py b/openviking/resource/watch_manager.pyindex de8b841b2..d3271e9b5 100644--- a/openviking/resource/watch_manager.py+++ b/openviking/resource/watch_manager.py@@ -7,15 +7,20 @@ Provides task creation, update, deletion, query, and persistence storage."""import asyncio-import inspectimport jsonimport uuidfrom datetime import datetime, timedelta-from typing import Any, Awaitable, Callable, Dict, List, Optional+from typing import Any, Dict, List, Optionalfrom pydantic import BaseModel, Fieldfrom openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingMode+from openviking.resource.uri_mutation_coordinator import (+ UriMutationCoordinator,+)+from openviking.resource.uri_mutation_coordinator import (+ uri_matches_prefix as _uri_matches_prefix,+)from openviking.resource.watch_storage import (WATCH_TASK_STORAGE_BAK_URI,WATCH_TASK_STORAGE_TMP_URI,@@ -29,13 +34,6 @@ logger = get_logger(__name__)_UNSET = object()-def _uri_matches_prefix(uri: Optional[str], prefix: str) -> bool:- if not uri:- return False- normalized = prefix.rstrip("/")- return uri == normalized or uri.startswith(normalized + "/")--def _rewrite_uri_prefix(uri: str, old_prefix: str, new_prefix: str) -> str:old_normalized = old_prefix.rstrip("/")new_normalized = new_prefix.rstrip("/")@@ -169,7 +167,11 @@ class WatchManager:STORAGE_BAK_URI = WATCH_TASK_STORAGE_BAK_URISTORAGE_TMP_URI = WATCH_TASK_STORAGE_TMP_URI- def __init__(self, viking_fs: Optional[Any] = None):+ def __init__(+ self,+ viking_fs: Optional[Any] = None,+ uri_mutation_coordinator: Optional[UriMutationCoordinator] = None,+ ):"""Initialize WatchManager.Args:@@ -178,6 +180,7 @@ class WatchManager:self._tasks: Dict[str, WatchTask] = {}self._uri_to_task: Dict[tuple[str, str], str] = {}self._lock = asyncio.Lock()+ self._uri_mutation_coordinator = uri_mutation_coordinator or UriMutationCoordinator()self._viking_fs = viking_fsself._initialized = False@@ -400,67 +403,51 @@ class WatchManager:processor_kwargs: Optional[Dict[str, Any]] = None,auth_state: Optional[Dict[str, Any]] = None,) -> WatchTask:- """Create a new monitoring task.-- Args:- path: Resource path to monitor- account_id: Account ID (tenant)- user_id: User ID who creates this task- to_uri: Target URI- parent_uri: Parent URI- reason: Reason for monitoring- instruction: Monitoring instruction- watch_interval: Monitoring interval in minutes-- Returns:- Created WatchTask-- Raises:- ValueError: If required fields are missing- ConflictError: If target URI conflicts with existing tasks- """+ """Create and persist a watch task while its target URI is stable."""if not path:raise ValueError("Path is required")if watch_interval <= 0:raise ValueError("watch_interval must be > 0")- async with self._lock:- if self._check_uri_conflict(to_uri, account_id=account_id):- raise ConflictError(- f"Target URI '{to_uri}' is already used by another task",- resource=to_uri,- )+ async with self._uri_mutation_coordinator.access(account_id, [to_uri]):+ async with self._lock:+ if self._check_uri_conflict(to_uri, account_id=account_id):+ raise ConflictError(+ f"Target URI '{to_uri}' is already used by another task",+ resource=to_uri,+ )- task = WatchTask(- path=path,- to_uri=to_uri,- to_is_directory=to_is_directory,- parent_uri=parent_uri,- reason=reason,- instruction=instruction,- watch_interval=watch_interval,- build_index=build_index,- summarize=summarize,- processing_mode=processing_mode,- processor_kwargs=processor_kwargs or {},- auth_state=auth_state,- account_id=account_id,- user_id=user_id,- original_role=original_role,- )+ task = WatchTask(+ path=path,+ to_uri=to_uri,+ to_is_directory=to_is_directory,+ parent_uri=parent_uri,+ reason=reason,+ instruction=instruction,+ watch_interval=watch_interval,+ build_index=build_index,+ summarize=summarize,+ processing_mode=processing_mode,+ processor_kwargs=processor_kwargs or {},+ auth_state=auth_state,+ account_id=account_id,+ user_id=user_id,+ original_role=original_role,+ )- task.next_execution_time = task.calculate_next_execution_time()+ task.next_execution_time = task.calculate_next_execution_time()- self._tasks[task.task_id] = task- if to_uri:- self._uri_to_task[(account_id, to_uri)] = task.task_id+ self._tasks[task.task_id] = task+ if to_uri:+ self._uri_to_task[(account_id, to_uri)] = task.task_id- await self._save_tasks()+ await self._save_tasks()- logger.info(- f"[WatchManager] Created task {task.task_id} for path {path} by user {account_id}/{user_id}"- )- return task+ logger.info(+ f"[WatchManager] Created task {task.task_id} for path {path} "+ f"by user {account_id}/{user_id}"+ )+ return taskasync def update_task(self,@@ -482,107 +469,133 @@ class WatchManager:auth_state: Any = _UNSET,is_active: Optional[bool] = None,) -> WatchTask:- """Update an existing monitoring task.-- Args:- task_id: Task ID to update- account_id: Requester's account ID- user_id: Requester's user ID- role: Requester's role (ROOT/ADMIN/USER)- path: New resource path- to_uri: New target URI- parent_uri: New parent URI- reason: New reason- instruction: New instruction- watch_interval: New monitoring interval- is_active: New active status-- Returns:- Updated WatchTask-- Raises:- ValueError: If task not found or invalid arguments- ConflictError: If target URI conflicts with existing tasks- PermissionDeniedError: If user doesn't have permission- """- async with self._lock:- task = self._tasks.get(task_id)- if not task:- raise ValueError(f"Task {task_id} not found")+ """Update a watch task while its current and requested target URIs are stable."""+ while True:+ async with self._lock:+ snapshot = self._tasks.get(task_id)+ if not snapshot:+ raise ValueError(f"Task {task_id} not found")+ stable_account_id = snapshot.account_id+ stable_to_uri = snapshot.to_uri++ async with self._uri_mutation_coordinator.access(+ stable_account_id, [stable_to_uri, to_uri]+ ):+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ raise ValueError(f"Task {task_id} not found")+ if task.account_id != stable_account_id or task.to_uri != stable_to_uri:+ continue+ if not self._check_permission(task, account_id, user_id, role):+ raise PermissionDeniedError(+ f"User {account_id}/{user_id} does not have permission to "+ f"update task {task_id}"+ )+ return await self._update_task_unlocked(+ task,+ account_id=account_id,+ user_id=user_id,+ path=path,+ to_uri=to_uri,+ to_is_directory=to_is_directory,+ parent_uri=parent_uri,+ reason=reason,+ instruction=instruction,+ watch_interval=watch_interval,+ build_index=build_index,+ summarize=summarize,+ processing_mode=processing_mode,+ processor_kwargs=processor_kwargs,+ auth_state=auth_state,+ is_active=is_active,+ )- if not self._check_permission(task, account_id, user_id, role):- raise PermissionDeniedError(- f"User {account_id}/{user_id} does not have permission to update task {task_id}"- )+ async def _update_task_unlocked(+ self,+ task: WatchTask,+ *,+ account_id: str,+ user_id: str,+ path: Optional[str],+ to_uri: Optional[str],+ to_is_directory: Optional[bool],+ parent_uri: Optional[str],+ reason: Optional[str],+ instruction: Optional[str],+ watch_interval: Optional[float],+ build_index: Optional[bool],+ summarize: Optional[bool],+ processing_mode: Optional[ProcessingMode],+ processor_kwargs: Optional[Dict[str, Any]],+ auth_state: Any,+ is_active: Optional[bool],+ ) -> WatchTask:+ task_id = task.task_id+ if self._check_uri_conflict(to_uri, account_id=task.account_id, exclude_task_id=task_id):+ raise ConflictError(+ f"Target URI '{to_uri}' is already used by another task",+ resource=to_uri,+ )- if self._check_uri_conflict(- to_uri, account_id=task.account_id, exclude_task_id=task_id- ):- raise ConflictError(- f"Target URI '{to_uri}' is already used by another task",- resource=to_uri,- )+ old_to_uri = task.to_uri+ if path is not None:+ task.path = path+ if to_uri is not None:+ task.to_uri = to_uri+ if to_is_directory is not None:+ task.to_is_directory = to_is_directory+ if parent_uri is not None:+ task.parent_uri = parent_uri+ if reason is not None:+ task.reason = reason+ if instruction is not None:+ task.instruction = instruction+ if watch_interval is not None:+ if watch_interval <= 0:+ if is_active is True:+ raise ValueError("watch_interval must be > 0 for active tasks")+ task.watch_interval = watch_interval+ task.is_active = False+ task.next_execution_time = None+ else:+ task.watch_interval = watch_interval+ if build_index is not None:+ task.build_index = build_index+ if summarize is not None:+ task.summarize = summarize+ if processing_mode is not None:+ task.processing_mode = processing_mode+ if processor_kwargs is not None:+ task.processor_kwargs = processor_kwargs+ if auth_state is not _UNSET:+ task.auth_state = auth_state+ if is_active is not None:+ task.is_active = is_active- old_to_uri = task.to_uri-- if path is not None:- task.path = path- if to_uri is not None:- task.to_uri = to_uri- if to_is_directory is not None:- task.to_is_directory = to_is_directory- if parent_uri is not None:- task.parent_uri = parent_uri- if reason is not None:- task.reason = reason- if instruction is not None:- task.instruction = instruction- if watch_interval is not None:- if watch_interval <= 0:- if is_active is True:- raise ValueError("watch_interval must be > 0 for active tasks")- task.watch_interval = watch_interval- task.is_active = False- task.next_execution_time = None- else:- task.watch_interval = watch_interval- if build_index is not None:- task.build_index = build_index- if summarize is not None:- task.summarize = summarize- if processing_mode is not None:- task.processing_mode = processing_mode- if processor_kwargs is not None:- task.processor_kwargs = processor_kwargs- if auth_state is not _UNSET:- task.auth_state = auth_state- if is_active is not None:- task.is_active = is_active-- if watch_interval is not None:- if task.is_active and task.watch_interval > 0:+ if watch_interval is not None:+ if task.is_active and task.watch_interval > 0:+ task.next_execution_time = task.calculate_next_execution_time()+ else:+ task.next_execution_time = None+ if is_active is not None and watch_interval is None:+ if task.is_active:+ if task.watch_interval <= 0:+ raise ValueError("watch_interval must be > 0 for active tasks")+ if task.next_execution_time is None:task.next_execution_time = task.calculate_next_execution_time()- else:- task.next_execution_time = None- if is_active is not None and watch_interval is None:- if task.is_active:- if task.watch_interval <= 0:- raise ValueError("watch_interval must be > 0 for active tasks")- if task.next_execution_time is None:- task.next_execution_time = task.calculate_next_execution_time()- else:- task.next_execution_time = None-- if to_uri is not None:- if old_to_uri and old_to_uri != to_uri:- self._uri_to_task.pop((task.account_id, old_to_uri), None)- if to_uri:- self._uri_to_task[(task.account_id, to_uri)] = task_id+ else:+ task.next_execution_time = None- await self._save_tasks()+ if to_uri is not None:+ if old_to_uri and old_to_uri != to_uri:+ self._uri_to_task.pop((task.account_id, old_to_uri), None)+ if to_uri:+ self._uri_to_task[(task.account_id, to_uri)] = task_id- logger.info(f"[WatchManager] Updated task {task_id} by user {account_id}/{user_id}")- return task+ await self._save_tasks()+ logger.info(f"[WatchManager] Updated task {task_id} by user {account_id}/{user_id}")+ return taskasync def update_auth_state(self,@@ -597,7 +610,7 @@ class WatchManager:task.auth_state = auth_stateawait self._save_tasks()- def _plan_move_tasks_under_uri_unlocked(+ def _plan_target_prefix_rewrite_unlocked(self,old_uri: str,new_uri: str,@@ -625,20 +638,25 @@ class WatchManager:)return plan- async def sync_tasks_with_resource_move_internal(+ async def validate_target_prefix_rewrite_internal(+ self,+ old_uri: str,+ new_uri: str,+ account_id: str = "default",+ ) -> None:+ """Validate a watch target prefix rewrite without changing state."""+ async with self._lock:+ self._plan_target_prefix_rewrite_unlocked(old_uri, new_uri, account_id)++ async def rewrite_target_prefix_internal(self,old_uri: str,new_uri: str,- move_resource: Callable[[], Awaitable[None]],- rollback_resource: Optional[Callable[[], Awaitable[None]]] = None,account_id: str = "default",) -> List[WatchTask]:- """Move a resource and keep watch-task target URIs in sync under one lock."""+ """Atomically rewrite matching watch target URIs and persist the result."""async with self._lock:- plan = self._plan_move_tasks_under_uri_unlocked(old_uri, new_uri, account_id)- move_result = move_resource()- if inspect.isawaitable(move_result):- await move_result+ plan = self._plan_target_prefix_rewrite_unlocked(old_uri, new_uri, account_id)if not plan:return []@@ -672,37 +690,37 @@ class WatchManager:)return updatedexcept Exception:- for task_id, (original_to_uri, original_parent_uri) in original_targets.items():+ for task_id, (+ original_to_uri,+ original_parent_uri,+ ) in original_targets.items():task = self._tasks[task_id]task.to_uri = original_to_uritask.parent_uri = original_parent_uriself._uri_to_task = original_uri_to_task- if rollback_resource is not None:- rollback_result = rollback_resource()- if inspect.isawaitable(rollback_result):- await rollback_resultraiseasync def deactivate_tasks_under_uri_internal(self, uri: str, account_id: str = "default") -> List[WatchTask]:"""Deactivate watch tasks whose target URI is deleted."""- async with self._lock:- matched = [- task- for task in self._tasks.values()- if task.account_id == account_id and _uri_matches_prefix(task.to_uri, uri)- ]- if not matched:- return []-- for task in matched:- task.is_active = False- task.next_execution_time = None+ async with self._uri_mutation_coordinator.access(account_id, [uri]):+ async with self._lock:+ matched = [+ task+ for task in self._tasks.values()+ if task.account_id == account_id and _uri_matches_prefix(task.to_uri, uri)+ ]+ if not matched:+ return []++ for task in matched:+ task.is_active = False+ task.next_execution_time = None- await self._save_tasks()- logger.info(f"[WatchManager] Deactivated {len(matched)} watch task(s) under {uri}")- return matched+ await self._save_tasks()+ logger.info(f"[WatchManager] Deactivated {len(matched)} watch task(s) under {uri}")+ return matchedasync def delete_task(self,@@ -725,24 +743,36 @@ class WatchManager:Raises:PermissionDeniedError: If user doesn't have permission"""- async with self._lock:- task = self._tasks.get(task_id)- if not task:- return False-- if not self._check_permission(task, account_id, user_id, role):- raise PermissionDeniedError(- f"User {account_id}/{user_id} does not have permission to delete task {task_id}"- )-- self._tasks.pop(task_id, None)- if task.to_uri:- self._uri_to_task.pop((task.account_id, task.to_uri), None)-- await self._save_tasks()+ while True:+ async with self._lock:+ snapshot = self._tasks.get(task_id)+ if not snapshot:+ return False+ stable_account_id = snapshot.account_id+ stable_to_uri = snapshot.to_uri++ async with self._uri_mutation_coordinator.access(stable_account_id, [stable_to_uri]):+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ return False+ if task.account_id != stable_account_id or task.to_uri != stable_to_uri:+ continue+ if not self._check_permission(task, account_id, user_id, role):+ raise PermissionDeniedError(+ f"User {account_id}/{user_id} does not have permission to "+ f"delete task {task_id}"+ )++ self._tasks.pop(task_id, None)+ if task.to_uri:+ self._uri_to_task.pop((task.account_id, task.to_uri), None)- logger.info(f"[WatchManager] Deleted task {task_id} by user {account_id}/{user_id}")- return True+ await self._save_tasks()+ logger.info(+ f"[WatchManager] Deleted task {task_id} by user {account_id}/{user_id}"+ )+ return Trueasync def get_task(self,@@ -762,15 +792,24 @@ class WatchManager:Returns:WatchTask if found and accessible, None otherwise"""- async with self._lock:- task = self._tasks.get(task_id)- if not task:- return None-- if not self._check_permission(task, account_id, user_id, role):- return None-- return task+ while True:+ async with self._lock:+ snapshot = self._tasks.get(task_id)+ if not snapshot:+ return None+ stable_account_id = snapshot.account_id+ stable_to_uri = snapshot.to_uri++ async with self._uri_mutation_coordinator.access(stable_account_id, [stable_to_uri]):+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ return None+ if task.account_id != stable_account_id or task.to_uri != stable_to_uri:+ continue+ if not self._check_permission(task, account_id, user_id, role):+ return None+ return taskasync def get_all_tasks(self,@@ -818,19 +857,20 @@ class WatchManager:Returns:WatchTask if found and accessible, None otherwise"""- async with self._lock:- task_id = self._uri_to_task.get((account_id, to_uri))- if not task_id:- return None+ async with self._uri_mutation_coordinator.access(account_id, [to_uri]):+ async with self._lock:+ task_id = self._uri_to_task.get((account_id, to_uri))+ if not task_id:+ return None- task = self._tasks.get(task_id)- if not task:- return None+ task = self._tasks.get(task_id)+ if not task:+ return None- if not self._check_permission(task, account_id, user_id, role):- return None+ if not self._check_permission(task, account_id, user_id, role):+ return None- return task+ return taskasync def update_execution_time(self, task_id: str) -> None:"""Update task execution time after execution.diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.pyindex dd5133ae2..7e12b2bcc 100644--- a/openviking/resource/watch_scheduler.py+++ b/openviking/resource/watch_scheduler.py@@ -17,6 +17,7 @@ from openviking.resource.feishu_watch_auth import (feishu_auth_state_needs_refresh,is_feishu_auth_state,)+from openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_manager import WatchManagerfrom openviking.server.error_mapping import is_not_found_errorfrom openviking.server.identity import RequestContext, Role@@ -44,6 +45,7 @@ class WatchScheduler:viking_fs: Optional[Any] = None,check_interval: float = DEFAULT_CHECK_INTERVAL,max_concurrency: int = 4,+ uri_mutation_coordinator: Optional[UriMutationCoordinator] = None,):"""Initialize WatchScheduler.@@ -54,6 +56,7 @@ class WatchScheduler:"""self._resource_service = resource_serviceself._viking_fs = viking_fs+ self._uri_mutation_coordinator = uri_mutation_coordinator or UriMutationCoordinator()if check_interval <= 0:raise ValueError("check_interval must be > 0")if max_concurrency <= 0:@@ -85,7 +88,10 @@ class WatchScheduler:return# Initialize WatchManager- self._watch_manager = WatchManager(viking_fs=self._viking_fs)+ self._watch_manager = WatchManager(+ viking_fs=self._viking_fs,+ uri_mutation_coordinator=self._uri_mutation_coordinator,+ )await self._watch_manager.initialize()logger.info("[WatchScheduler] WatchManager initialized")@@ -211,6 +217,38 @@ class WatchScheduler:await asyncio.gather(*(asyncio.create_task(run_one(t)) for t in tasks_to_run))async def _execute_task(self, task) -> None:+ """Execute a task only after confirming its target URI is stable."""+ if not self._watch_manager:+ return++ candidate = task+ while True:+ stable_account_id = candidate.account_id+ stable_to_uri = candidate.to_uri+ async with self._uri_mutation_coordinator.access(+ stable_account_id,+ [stable_to_uri],+ ):+ current = await self._watch_manager.get_task(+ candidate.task_id,+ account_id=candidate.account_id,+ user_id=candidate.user_id,+ role=getattr(candidate, "original_role", None) or str(Role.USER),+ )+ if current is None:+ logger.info(+ f"[WatchScheduler] Task {candidate.task_id} disappeared before execution"+ )+ return+ if current.account_id != stable_account_id or current.to_uri != stable_to_uri:+ candidate = current+ continue++ stable_task = current.model_copy(deep=True)+ await self._execute_stable_task(stable_task)+ return++ async def _execute_stable_task(self, task) -> None:"""Execute a single watch task.Calls ResourceService.refresh_resource to re-process the resource.diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 88b6800a5..e56eebc5b 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any, Optionalfrom openviking.core.directories import DirectoryInitializerfrom openviking.core.namespace import canonicalize_urifrom openviking.privacy import UserPrivacyConfigService+from openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_scheduler import WatchSchedulerfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.agent_evolution_service import AgentEvolutionService@@ -23,8 +24,8 @@ from openviking.service.relation_service import RelationServicefrom openviking.service.resource_memory_link_service import ResourceMemoryLinkServicefrom openviking.service.resource_service import ResourceServicefrom openviking.service.search_service import SearchService-from openviking.service.session_service import SessionServicefrom openviking.service.session_auto_commit import SessionAutoCommitScheduler+from openviking.service.session_service import SessionServicefrom openviking.service.task_tracker import get_task_tracker, set_task_trackerfrom openviking.session import create_session_compressorfrom openviking.storage.collection_schemas import init_context_collection@@ -92,6 +93,7 @@ class OpenVikingService:self._session_compressor: Optional["SessionCompressorV2"] = Noneself._directory_initializer: Optional[DirectoryInitializer] = None+ self._uri_mutation_coordinator = UriMutationCoordinator()self._watch_scheduler: Optional[WatchScheduler] = Noneself._session_auto_commit_scheduler: Optional[SessionAutoCommitScheduler] = Noneself._encryptor: Optional[Any] = None@@ -100,7 +102,9 @@ class OpenVikingService:self._data_dir_lock_path: Optional[str] = None# Sub-services- self._fs_service = FSService()+ self._fs_service = FSService(+ uri_mutation_coordinator=self._uri_mutation_coordinator,+ )self._relation_service = RelationService()self._pack_service = PackService()self._search_service = SearchService()@@ -380,6 +384,7 @@ class OpenVikingService:self._watch_scheduler = WatchScheduler(resource_service=self._resource_service,viking_fs=self._viking_fs,+ uri_mutation_coordinator=self._uri_mutation_coordinator,)# Wire up sub-services@@ -389,6 +394,7 @@ class OpenVikingService:privacy_config_service=self._privacy_config_service,resource_memory_link_service=self._resource_memory_link_service,watch_scheduler=self._watch_scheduler,+ uri_mutation_coordinator=self._uri_mutation_coordinator,)self._relation_service.set_viking_fs(self._viking_fs)self._pack_service.set_dependencies(diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex d73779640..8ee7a9e5e 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -6,6 +6,7 @@ File System Service for OpenViking.Provides file system operations: ls, mkdir, rm, mv, tree, stat, read, abstract, overview, grep, glob."""+import asynciofrom typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom openviking.core.namespace import classify_uri, context_type_for_uri@@ -15,6 +16,7 @@ from openviking.privacy import (get_skill_name_from_uri,restore_skill_content,)+from openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_storage import is_watch_task_control_urifrom openviking.server.identity import RequestContextfrom openviking.session.memory.memory_updater import MemoryUpdater@@ -64,12 +66,14 @@ class FSService:privacy_config_service: Optional[UserPrivacyConfigService] = None,resource_memory_link_service: Optional["ResourceMemoryLinkService"] = None,watch_scheduler: Optional["WatchScheduler"] = None,+ uri_mutation_coordinator: Optional[UriMutationCoordinator] = None,):self._viking_fs = viking_fsself._vikingdb = vikingdbself._privacy_config_service = privacy_config_serviceself._resource_memory_link_service = resource_memory_link_serviceself._watch_scheduler = watch_scheduler+ self._uri_mutation_coordinator = uri_mutation_coordinator or UriMutationCoordinator()def set_dependencies(self,@@ -78,6 +82,7 @@ class FSService:privacy_config_service: Optional[UserPrivacyConfigService] = None,resource_memory_link_service: Optional["ResourceMemoryLinkService"] = None,watch_scheduler: Optional["WatchScheduler"] = None,+ uri_mutation_coordinator: Optional[UriMutationCoordinator] = None,) -> None:"""Set service dependencies (for deferred initialization)."""self._viking_fs = viking_fs@@ -85,6 +90,8 @@ class FSService:self._privacy_config_service = privacy_config_serviceself._resource_memory_link_service = resource_memory_link_serviceself._watch_scheduler = watch_scheduler+ if uri_mutation_coordinator is not None:+ self._uri_mutation_coordinator = uri_mutation_coordinatordef _ensure_initialized(self) -> VikingFS:"""Ensure VikingFS is initialized."""@@ -421,13 +428,72 @@ class FSService:await viking_fs.mv(from_uri, to_uri, ctx=ctx)return- await watch_manager.sync_tasks_with_resource_move_internal(- from_uri,- to_uri,- account_id=ctx.account_id,- move_resource=lambda: viking_fs.mv(from_uri, to_uri, ctx=ctx),- rollback_resource=lambda: viking_fs.mv(to_uri, from_uri, ctx=ctx),+ transaction_task = asyncio.create_task(+ self._move_resource_with_watch_transaction(+ viking_fs,+ watch_manager,+ from_uri,+ to_uri,+ ctx,+ ))+ try:+ await asyncio.shield(transaction_task)+ except asyncio.CancelledError:+ while not transaction_task.done():+ try:+ await asyncio.shield(transaction_task)+ except asyncio.CancelledError:+ continue+ except Exception:+ break+ try:+ transaction_task.result()+ except asyncio.CancelledError:+ pass+ except Exception:+ logger.error(+ "Resource move transaction failed while caller was cancelled",+ exc_info=True,+ )+ raise++ async def _move_resource_with_watch_transaction(+ self,+ viking_fs: VikingFS,+ watch_manager: "WatchManager",+ from_uri: str,+ to_uri: str,+ ctx: RequestContext,+ ) -> None:+ async with self._uri_mutation_coordinator.mutation(+ ctx.account_id,+ [from_uri, to_uri],+ ):+ await watch_manager.validate_target_prefix_rewrite_internal(+ from_uri,+ to_uri,+ account_id=ctx.account_id,+ )+ await viking_fs.mv(from_uri, to_uri, ctx=ctx)+ try:+ await watch_manager.rewrite_target_prefix_internal(+ from_uri,+ to_uri,+ account_id=ctx.account_id,+ )+ except Exception as commit_error:+ try:+ await viking_fs.mv(to_uri, from_uri, ctx=ctx)+ except Exception as rollback_error:+ logger.error(+ "Failed to roll back resource move from %s to %s",+ to_uri,+ from_uri,+ exc_info=True,+ )+ raise rollback_error from commit_error+ raiseasync def _sync_watch_after_rm(self, uri: str, *, account_id: str, context_type: str) -> None:if context_type != "resource":diff --git a/tests/resource/test_watch_manager.py b/tests/resource/test_watch_manager.pyindex 66c13dc33..95251d9a0 100644--- a/tests/resource/test_watch_manager.py+++ b/tests/resource/test_watch_manager.py@@ -254,31 +254,24 @@ class TestWatchManager:assert (await watch_manager_no_fs.get_task(sibling.task_id)).is_active is True@pytest.mark.asyncio- async def test_sync_tasks_with_resource_move_internal_rolls_back_task_state_on_save_failure(- self, watch_manager_no_fs: WatchManager- ):- root = await watch_manager_no_fs.create_task(+ async def test_target_prefix_rewrite_rolls_back_task_state_on_save_failure(self):+ manager = WatchManager()+ root = await manager.create_task(path="/test/root",to_uri="viking://resources/codeask/wiki",parent_uri=None,watch_interval=30.0,)- watch_manager_no_fs._save_tasks = AsyncMock(side_effect=RuntimeError("save failed"))- move_resource = AsyncMock()- rollback_resource = AsyncMock()+ manager._save_tasks = AsyncMock(side_effect=RuntimeError("save failed"))with pytest.raises(RuntimeError, match="save failed"):- await watch_manager_no_fs.sync_tasks_with_resource_move_internal(+ await manager.rewrite_target_prefix_internal("viking://resources/codeask/wiki","viking://resources/codeask/wiki-renamed",- move_resource=move_resource,- rollback_resource=rollback_resource,account_id=TEST_ACCOUNT_ID,)- move_resource.assert_awaited_once()- rollback_resource.assert_awaited_once()- restored = await watch_manager_no_fs.get_task(root.task_id)+ restored = await manager.get_task(root.task_id)assert restored is not Noneassert restored.to_uri == "viking://resources/codeask/wiki"assert restored.parent_uri is None@@ -287,19 +280,19 @@ class TestWatchManager:async def test_uri_index_move_and_deactivate_are_account_scoped(self):manager = WatchManager()uri = "viking://resources/shared"- task_a = await manager.create_task(- path="/a", account_id="account-a", to_uri=uri- )- task_b = await manager.create_task(- path="/b", account_id="account-b", to_uri=uri- )+ task_a = await manager.create_task(path="/a", account_id="account-a", to_uri=uri)+ task_b = await manager.create_task(path="/b", account_id="account-b", to_uri=uri)with pytest.raises(ConflictError):await manager.create_task(path="/duplicate", account_id="account-a", to_uri=uri)- await manager.sync_tasks_with_resource_move_internal(+ await manager.validate_target_prefix_rewrite_internal(+ uri,+ f"{uri}-moved",+ account_id="account-a",+ )+ await manager.rewrite_target_prefix_internal(uri,f"{uri}-moved",- move_resource=AsyncMock(),account_id="account-a",)deactivated = await manager.deactivate_tasks_under_uri_internal(uri, "account-b")@@ -309,9 +302,7 @@ class TestWatchManager:assert task_b.to_uri == uriassert task_b.is_active is Falseassert deactivated == [task_b]- moved = await manager.get_task_by_uri(- f"{uri}-moved", "account-a", "default", "root"- )+ moved = await manager.get_task_by_uri(f"{uri}-moved", "account-a", "default", "root")assert moved is task_aassert await manager.get_task_by_uri(uri, "account-b", "default", "root") is task_bdiff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.pyindex 627bed3e8..869e3580d 100644--- a/tests/resource/test_watch_scheduler.py+++ b/tests/resource/test_watch_scheduler.py@@ -1,7 +1,9 @@+import asynciofrom unittest.mock import AsyncMockimport pytest+from openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_manager import WatchManagerfrom openviking.resource.watch_scheduler import WatchSchedulerfrom openviking.service.resource_service import ResourceService@@ -112,7 +114,7 @@ class TestWatchSchedulerResourceExistence:manager.update_execution_time.assert_awaited_once_with(task.task_id)@pytest.mark.asyncio- async def test_execute_task_forwards_processing_mode(self, tmp_path):+ async def test_execute_task_uses_stable_target_and_options(self, tmp_path):class FakeResourceService(ResourceService):def __init__(self):super().__init__()@@ -124,21 +126,39 @@ class TestWatchSchedulerResourceExistence:source = tmp_path / "source.txt"source.write_text("ok")+ coordinator = UriMutationCoordinator()resource_service = FakeResourceService()- scheduler = WatchScheduler(resource_service=resource_service, check_interval=1)- manager = WatchManager(viking_fs=None)+ scheduler = WatchScheduler(+ resource_service=resource_service,+ uri_mutation_coordinator=coordinator,+ check_interval=1,+ )+ manager = WatchManager(uri_mutation_coordinator=coordinator)await manager.initialize()scheduler._watch_manager = managermanager.update_execution_time = AsyncMock()+ old_uri = "viking://resources/codeask/wiki"+ new_uri = "viking://resources/codeask/wiki-renamed"task = await manager.create_task(path=str(source),- to_uri="viking://resources/codeask/wiki",+ to_uri=old_uri,watch_interval=30.0,processing_mode="vectors_only",)- await scheduler._execute_task(task)+ async with coordinator.mutation(task.account_id, [old_uri, new_uri]):+ execution = asyncio.create_task(scheduler._execute_task(task.model_copy(deep=True)))+ await asyncio.sleep(0)+ assert resource_service.calls == []+ await manager.rewrite_target_prefix_internal(+ old_uri,+ new_uri,+ account_id=task.account_id,+ )++ await asyncio.wait_for(execution, timeout=1)- assert resource_service.calls+ assert len(resource_service.calls) == 1+ assert resource_service.calls[0]["to"] == new_uriassert resource_service.calls[0]["processing_mode"] == "vectors_only"assert resource_service.calls[0]["enforce_public_remote_targets"] is Truediff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.pyindex ff6b315f4..fd55fd180 100644--- a/tests/service/test_fs_service.py+++ b/tests/service/test_fs_service.py@@ -13,10 +13,11 @@ from openviking_cli.session.user_id import UserIdentifierclass _FakeVikingFS:- def __init__(self, *, rm_error=None):+ def __init__(self, *, rm_error=None, events=None):self.rm_calls = []self.mv_calls = []self.rm_error = rm_error+ self.events = eventsasync def rm(self, uri, recursive=False, ctx=None):self.rm_calls.append({"uri": uri, "recursive": recursive, "ctx": ctx})@@ -26,38 +27,33 @@ class _FakeVikingFS:async def mv(self, from_uri, to_uri, ctx=None):self.mv_calls.append({"from_uri": from_uri, "to_uri": to_uri, "ctx": ctx})+ if self.events is not None:+ self.events.append(("mv", from_uri, to_uri))class _FakeWatchManager:- def __init__(self):- self.plan_calls = []- self.move_calls = []- self.sync_calls = []+ def __init__(self, *, events=None):+ self.validate_calls = []+ self.rewrite_calls = []self.deactivate_calls = []- self.plan_error = None-- async def plan_move_tasks_under_uri_internal(self, from_uri, to_uri):- self.plan_calls.append({"from_uri": from_uri, "to_uri": to_uri})- if self.plan_error:- raise self.plan_error- return {}-- async def move_tasks_under_uri_internal(self, from_uri, to_uri):- self.move_calls.append({"from_uri": from_uri, "to_uri": to_uri})- return [SimpleNamespace(task_id="watch-1")]+ self.validate_error = None+ self.events = events- async def sync_tasks_with_resource_move_internal(- self,- from_uri,- to_uri,- account_id,- move_resource,- rollback_resource=None,- ):- self.sync_calls.append({"from_uri": from_uri, "to_uri": to_uri, "account_id": account_id})- if self.plan_error:- raise self.plan_error- await move_resource()+ async def validate_target_prefix_rewrite_internal(self, from_uri, to_uri, account_id):+ self.validate_calls.append(+ {"from_uri": from_uri, "to_uri": to_uri, "account_id": account_id}+ )+ if self.events is not None:+ self.events.append(("validate", from_uri, to_uri))+ if self.validate_error:+ raise self.validate_error++ async def rewrite_target_prefix_internal(self, from_uri, to_uri, account_id):+ self.rewrite_calls.append(+ {"from_uri": from_uri, "to_uri": to_uri, "account_id": account_id}+ )+ if self.events is not None:+ self.events.append(("rewrite", from_uri, to_uri))return [SimpleNamespace(task_id="watch-1")]async def deactivate_tasks_under_uri_internal(self, uri, account_id):@@ -315,9 +311,10 @@ async def test_resource_rm_does_not_deactivate_watch_task_control_uri(request_co@pytest.mark.asyncio-async def test_resource_mv_plans_then_moves_then_rewrites_watch_tasks(request_context):- viking_fs = _FakeVikingFS()- watch_manager = _FakeWatchManager()+async def test_resource_mv_validates_then_moves_then_rewrites_watch_tasks(request_context):+ events = []+ viking_fs = _FakeVikingFS(events=events)+ watch_manager = _FakeWatchManager(events=events)service = FSService(viking_fs=viking_fs,watch_scheduler=_FakeWatchScheduler(watch_manager),@@ -329,13 +326,15 @@ async def test_resource_mv_plans_then_moves_then_rewrites_watch_tasks(request_coctx=request_context,)- assert watch_manager.sync_calls == [+ expected_watch_call = [{"from_uri": "viking://resources/codeask/wiki","to_uri": "viking://resources/codeask/wiki-renamed","account_id": "default",}]+ assert watch_manager.validate_calls == expected_watch_call+ assert watch_manager.rewrite_calls == expected_watch_callassert viking_fs.mv_calls == [{"from_uri": "viking://resources/codeask/wiki",@@ -343,15 +342,14 @@ async def test_resource_mv_plans_then_moves_then_rewrites_watch_tasks(request_co"ctx": request_context,}]- assert watch_manager.plan_calls == []- assert watch_manager.move_calls == []+ assert [event[0] for event in events] == ["validate", "mv", "rewrite"]@pytest.mark.asyncioasync def test_resource_mv_conflict_fails_before_resource_move(request_context):viking_fs = _FakeVikingFS()watch_manager = _FakeWatchManager()- watch_manager.plan_error = RuntimeError("watch conflict")+ watch_manager.validate_error = RuntimeError("watch conflict")service = FSService(viking_fs=viking_fs,watch_scheduler=_FakeWatchScheduler(watch_manager),@@ -365,7 +363,7 @@ async def test_resource_mv_conflict_fails_before_resource_move(request_context):)assert viking_fs.mv_calls == []- assert watch_manager.move_calls == []+ assert watch_manager.rewrite_calls == []@pytest.mark.asyncio