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
优化 TaskTracker 并发,消除全局异步锁阻塞 (#3829)
Kchen7038ba0694c3
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.pyindex c1bc7e827..2e3373a8b 100644--- a/openviking/service/task_tracker.py+++ b/openviking/service/task_tracker.py@@ -14,6 +14,7 @@ Design decisions:"""import asyncio+import mathimport reimport threadingimport time@@ -25,12 +26,22 @@ from typing import Any, Dict, List, Optionalfrom uuid import uuid4from openviking.service.task_store import TaskStore+from openviking.service.task_tracker_concurrency import (+ KeyedAsyncLockPool,+ OwnerLoopDispatcher,+ StoreIOLimiter,+ run_to_completion,+)from openviking.service.task_work_index import QueueTaskMetadata, TaskWorkIndexfrom openviking_cli.utils.logger import get_loggerlogger = get_logger(__name__)+class _CommittedMutationCancelled(asyncio.CancelledError):+ """Caller cancellation observed after store and cache commit completed."""++class TaskStatus(str, Enum):"""Lifecycle states of an async task."""@@ -151,8 +162,8 @@ def _sanitize_task_result(result: Any) -> Any:class TaskTracker:"""Async task tracker with persistent storage and a process-local cache.- Async lifecycle operations are serialized by ``_async_lock``. The thread- lock only protects sync snapshot reads of the local cache.+ Mutations are serialized per task on one owner event loop. The thread lock+ only protects short, synchronous accesses to immutable cache snapshots."""MAX_TASKS = 10_000@@ -160,13 +171,17 @@ class TaskTracker:TTL_FAILED = 604_800 # 7 daysCLEANUP_INTERVAL = 300 # 5 minutes- def __init__(self, store: TaskStore) -> None:+ def __init__(self, store: TaskStore, *, max_concurrent_store_io: int = 8) -> None:self._store = storeself._tasks: Dict[str, TaskRecord] = {}self._lock = threading.Lock()- self._async_lock = asyncio.Lock()+ # The keyed registries provide process-local ordering. A deployment with+ # multiple TaskTracker writers must add store-level revision/CAS first.+ self._dispatcher = OwnerLoopDispatcher()+ self._task_locks = KeyedAsyncLockPool[str]()+ self._business_locks = KeyedAsyncLockPool[tuple[str, str, str, str]]()+ self._store_io = StoreIOLimiter(max_concurrent_store_io)self._cleanup_task: Optional[asyncio.Task] = None- self._runtime_loop: Optional[asyncio.AbstractEventLoop] = Noneself._work_index = TaskWorkIndex()self._install_work_index_callbacks()logger.info(@@ -186,7 +201,7 @@ class TaskTracker:def attach_work_index(self, work_index: TaskWorkIndex) -> None:"""Use the QueueManager-owned index as the task lifecycle authority."""self._work_index = work_index- self._runtime_loop = asyncio.get_running_loop()+ self._dispatcher.bind_current_loop()self._install_work_index_callbacks()async def restore_work_tasks(self, owners: Dict[str, tuple[str, str]]) -> None:@@ -196,25 +211,13 @@ class TaskTracker:async def _finalize_before_ack(self, metadata: QueueTaskMetadata) -> None:"""Persist the terminal state before QueueFS removes the last recovery message."""- loop = self._runtime_loop- if loop is None or loop.is_closed():- raise RuntimeError("TaskTracker runtime loop is unavailable during QueueFS ACK")- if asyncio.get_running_loop() is loop:- await self._finalize_task(+ await self._dispatcher.run(+ lambda: self._finalize_task_on_owner(metadata.task_id,account_id=metadata.account_id or None,user_id=metadata.user_id or None,)- return- future = asyncio.run_coroutine_threadsafe(- self._finalize_task(- metadata.task_id,- account_id=metadata.account_id or None,- user_id=metadata.user_id or None,- ),- loop,)- await asyncio.wrap_future(future)def is_cancellation_requested(self, task_id: str) -> bool:"""Fast thread-safe status check used by queue workers."""@@ -233,7 +236,7 @@ class TaskTracker:"""if self._cleanup_task is not None and not self._cleanup_task.done():return- self._runtime_loop = asyncio.get_running_loop()+ self._dispatcher.bind_current_loop()self._cleanup_task = asyncio.create_task(self._cleanup_loop())logger.debug("[TaskTracker] Cleanup loop started")@@ -255,29 +258,32 @@ class TaskTracker:async def _evict_expired(self) -> None:"""Remove expired tasks and enforce MAX_TASKS."""+ await self._dispatcher.run(self._evict_expired_on_owner)++ async def _evict_expired_on_owner(self) -> None:now = time.time()- async with self._async_lock:- with self._lock:- expired_ids = []- for tid, t in self._tasks.items():- if t.status in (TaskStatus.COMPLETED, TaskStatus.CANCELLED) and (- now - t.updated_at- ) > self.TTL_COMPLETED:- expired_ids.append(tid)- elif t.status == TaskStatus.FAILED and (now - t.updated_at) > self.TTL_FAILED:- expired_ids.append(tid)-- for tid in expired_ids:+ with self._lock:+ expired_ids = []+ for tid, t in self._tasks.items():+ if (+ t.status in (TaskStatus.COMPLETED, TaskStatus.CANCELLED)+ and (now - t.updated_at) > self.TTL_COMPLETED+ ):+ expired_ids.append(tid)+ elif t.status == TaskStatus.FAILED and (now - t.updated_at) > self.TTL_FAILED:+ expired_ids.append(tid)++ for tid in expired_ids:+ self._tasks.pop(tid, None)++ if len(self._tasks) > self.MAX_TASKS:+ sorted_tasks = sorted(self._tasks.items(), key=lambda x: x[1].created_at)+ excess = len(self._tasks) - self.MAX_TASKS+ for tid, _ in sorted_tasks[:excess]:self._tasks.pop(tid, None)- if len(self._tasks) > self.MAX_TASKS:- sorted_tasks = sorted(self._tasks.items(), key=lambda x: x[1].created_at)- excess = len(self._tasks) - self.MAX_TASKS- for tid, _ in sorted_tasks[:excess]:- self._tasks.pop(tid, None)-- if expired_ids:- logger.debug("[TaskTracker] Evicted %d expired tasks", len(expired_ids))+ if expired_ids:+ logger.debug("[TaskTracker] Evicted %d expired tasks", len(expired_ids))@staticmethoddef _matches_owner(@@ -320,27 +326,32 @@ class TaskTracker:user_id=user_id,meta=dict(meta or {}),)- async with self._async_lock:- if task_id:- with self._lock:- existing = self._tasks.get(task_id)+ return await self._dispatcher.run(lambda: self._create_on_owner(task, task_id is not None))++ async def _create_on_owner(self, task: TaskRecord, check_existing: bool) -> TaskRecord:+ async with self._task_locks.acquire(task.task_id):+ if check_existing:+ existing = self._cached_task(task.task_id)if existing is not None:- if not self._matches_owner(existing, account_id, user_id):- raise ValueError(f"Task ID already belongs to another owner: {task_id}")+ if not self._matches_owner(existing, task.account_id, task.user_id):+ raise ValueError(+ f"Task ID already belongs to another owner: {task.task_id}"+ )return self._copy(existing)- existing = await self._load_from_store(task_id, account_id, user_id)+ existing = await self._load_from_store(+ task.task_id,+ task.account_id or "",+ task.user_id,+ )if existing is not None:- with self._lock:- self._tasks[task_id] = existing+ self._publish_task(existing)return self._copy(existing)- await self._store.create(task)- with self._lock:- self._tasks[task.task_id] = task+ await self._persist_and_publish("create", task)logger.debug("[TaskTracker] Created task %s type=%s resource=%s",task.task_id,- task_type,- resource_id,+ task.task_type,+ task.resource_id,)return self._copy(task)@@ -358,13 +369,29 @@ class TaskTracker:This eliminates the race condition between has_running() and create()."""self._validate_owner(account_id, user_id)- async with self._async_lock:- for task in await self._load_all_from_store(account_id, user_id):- with self._lock:- self._tasks[task.task_id] = task+ business_key = (account_id, user_id, task_type, resource_id)+ return await self._dispatcher.run(+ lambda: self._create_if_no_running_on_owner(+ business_key,+ task_type,+ resource_id,+ account_id,+ user_id,+ )+ )++ async def _create_if_no_running_on_owner(+ self,+ business_key: tuple[str, str, str, str],+ task_type: str,+ resource_id: str,+ account_id: str,+ user_id: str,+ ) -> Optional[TaskRecord]:+ async with self._business_locks.acquire(business_key):+ self._merge_loaded_tasks(await self._load_all_from_store(account_id, user_id))- with self._lock:- tasks = list(self._tasks.values())+ tasks = self._cache_snapshot()has_active = any(t.task_type == task_typeand t.resource_id == resource_id@@ -381,9 +408,8 @@ class TaskTracker:account_id=account_id,user_id=user_id,)- await self._store.create(task)- with self._lock:- self._tasks[task.task_id] = task+ async with self._task_locks.acquire(task.task_id):+ await self._persist_and_publish("create", task)logger.debug("[TaskTracker] Created task %s type=%s resource=%s",task.task_id,@@ -400,16 +426,26 @@ class TaskTracker:stage: Optional[str] = None,) -> None:"""Transition task to RUNNING."""- async with self._async_lock:+ await self._dispatcher.run(+ lambda: self._start_on_owner(task_id, account_id, user_id, stage)+ )++ async def _start_on_owner(+ self,+ task_id: str,+ account_id: Optional[str],+ user_id: Optional[str],+ stage: Optional[str],+ ) -> None:+ async with self._task_locks.acquire(task_id):task = await self._load_for_update(task_id, account_id, user_id)if task and task.status in (TaskStatus.PENDING, TaskStatus.RUNNING):- task.status = TaskStatus.RUNNING+ updated = deepcopy(task)+ updated.status = TaskStatus.RUNNINGif stage is not None:- task.stage = stage- task.updated_at = time.time()- await self._store.update(task)- with self._lock:- self._tasks[task.task_id] = task+ updated.stage = stage+ updated.updated_at = self._next_updated_at(task)+ await self._persist_and_publish("update", updated)async def update_stage(self,@@ -419,14 +455,24 @@ class TaskTracker:user_id: Optional[str] = None,) -> None:"""Update task stage without changing its lifecycle status."""- async with self._async_lock:+ await self._dispatcher.run(+ lambda: self._update_stage_on_owner(task_id, stage, account_id, user_id)+ )++ async def _update_stage_on_owner(+ self,+ task_id: str,+ stage: str,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> None:+ async with self._task_locks.acquire(task_id):task = await self._load_for_update(task_id, account_id, user_id)if task and task.status in (TaskStatus.PENDING, TaskStatus.RUNNING):- task.stage = stage- task.updated_at = time.time()- await self._store.update(task)- with self._lock:- self._tasks[task.task_id] = task+ updated = deepcopy(task)+ updated.stage = stage+ updated.updated_at = self._next_updated_at(task)+ await self._persist_and_publish("update", updated)async def complete(self,@@ -466,23 +512,65 @@ class TaskTracker:error: Optional[str] = None,resource_id: Optional[str] = None,) -> None:- async with self._async_lock:+ await self._dispatcher.run(+ lambda: self._record_outcome_on_owner(+ task_id,+ account_id,+ user_id,+ result=result,+ error=error,+ resource_id=resource_id,+ )+ )++ async def _record_outcome_on_owner(+ self,+ task_id: str,+ account_id: Optional[str],+ user_id: Optional[str],+ *,+ result: Optional[Dict[str, Any]],+ error: Optional[str],+ resource_id: Optional[str],+ ) -> None:+ cancellation: asyncio.CancelledError | None = None+ outcome_persisted = False+ async with self._task_locks.acquire(task_id):task = await self._load_for_update(task_id, account_id, user_id)if task and task.status in (TaskStatus.PENDING, TaskStatus.RUNNING):+ updated = deepcopy(task)if result is not None:- task.result = result+ updated.result = deepcopy(result)if resource_id is not None:- task.resource_id = resource_id- if error is not None and task.error is None:- task.error = _sanitize_error(error)+ updated.resource_id = resource_id+ if error is not None and updated.error is None:+ updated.error = _sanitize_error(error)work_error = self._work_index.failure(task_id)- if work_error and task.error is None:- task.error = _sanitize_error(work_error)- task.updated_at = time.time()- await self._store.update(task)- with self._lock:- self._tasks[task.task_id] = task- await self._finalize_task(task_id, account_id=account_id, user_id=user_id)+ if work_error and updated.error is None:+ updated.error = _sanitize_error(work_error)+ updated.updated_at = self._next_updated_at(task)+ try:+ await self._persist_and_publish("update", updated)+ except _CommittedMutationCancelled as exc:+ cancellation = exc+ outcome_persisted = True+ else:+ outcome_persisted = True+ if outcome_persisted:+ try:+ await run_to_completion(+ lambda: self._finalize_task_on_owner(+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ )+ except asyncio.CancelledError as exc:+ cancellation = cancellation or exc+ else:+ await self._finalize_task_on_owner(task_id, account_id=account_id, user_id=user_id)+ if cancellation is not None:+ raise cancellationasync def cancel(self,@@ -491,7 +579,19 @@ class TaskTracker:user_id: Optional[str] = None,) -> Optional[TaskRecord]:"""Request cooperative cancellation and return the current task snapshot."""- async with self._async_lock:+ return await self._dispatcher.run(+ lambda: self._cancel_on_owner(task_id, account_id, user_id)+ )++ async def _cancel_on_owner(+ self,+ task_id: str,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> Optional[TaskRecord]:+ cancellation: asyncio.CancelledError | None = None+ cancellation_persisted = False+ async with self._task_locks.acquire(task_id):task = await self._load_for_update(task_id, account_id, user_id)if task is None:return None@@ -503,18 +603,38 @@ class TaskTracker:if task.status in _TERMINAL_STATUSES:raise ValueError(f"Task is already {task.status.value}")- task.status = TaskStatus.CANCELLING- task.updated_at = time.time()- await self._store.update(task)- with self._lock:- self._tasks[task.task_id] = task- self._work_index.cancel_active(task_id)- await self._finalize_task(- task_id,- account_id=account_id,- user_id=user_id,- )- return await self.get(task_id, account_id=account_id, user_id=user_id)+ updated = deepcopy(task)+ updated.status = TaskStatus.CANCELLING+ updated.updated_at = self._next_updated_at(task)+ try:+ await self._persist_and_publish("update", updated)+ except _CommittedMutationCancelled as exc:+ cancellation = exc+ cancellation_persisted = True+ else:+ cancellation_persisted = True++ async def finish_cancellation() -> None:+ self._work_index.cancel_active(task_id)+ await self._finalize_task_on_owner(+ task_id,+ account_id=account_id,+ user_id=user_id,+ )++ if cancellation_persisted:+ try:+ await run_to_completion(finish_cancellation)+ except asyncio.CancelledError as exc:+ cancellation = cancellation or exc+ else:+ await finish_cancellation()+ task = self._cached_task(task_id)+ if task is None or not self._matches_owner(task, account_id, user_id):+ return None+ if cancellation is not None:+ raise cancellation+ return self._copy(task)async def _finalize_task(self,@@ -523,9 +643,19 @@ class TaskTracker:user_id: Optional[str] = None,) -> None:"""Apply the task's terminal outcome after all owned work is settled."""+ await self._dispatcher.run(+ lambda: self._finalize_task_on_owner(task_id, account_id, user_id)+ )++ async def _finalize_task_on_owner(+ self,+ task_id: str,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> None:if self._work_index.has_work(task_id):return- async with self._async_lock:+ async with self._task_locks.acquire(task_id):task = await self._load_for_update(task_id, account_id, user_id)if task and task.status in _ACTIVE_STATUSES:if self._work_index.has_work(task_id):@@ -544,10 +674,8 @@ class TaskTracker:else:returnupdated.stage = updated.status.value- updated.updated_at = time.time()- await self._store.update(updated)- with self._lock:- self._tasks[updated.task_id] = updated+ updated.updated_at = self._next_updated_at(task)+ await self._persist_and_publish("update", updated)self._work_index.clear_failure(task_id)logger.info("[TaskTracker] Task %s %s", task_id, updated.status.value)@@ -560,9 +688,12 @@ class TaskTracker:poll_interval: float = 0.05,) -> TaskRecord:"""Wait for one task's terminal state without changing its lifecycle."""+async def _poll() -> TaskRecord:while True:task = await self.get(task_id, account_id=account_id, user_id=user_id)+ if task is None:+ raise KeyError(f"Task not found: {task_id}")if task.status in _TERMINAL_STATUSES:return taskawait asyncio.sleep(poll_interval)@@ -578,7 +709,6 @@ class TaskTracker:def register_running_task(self, task_id: str) -> None:"""Register the current asyncio task so cancellation can interrupt it."""- self._runtime_loop = self._runtime_loop or asyncio.get_running_loop()active_task = asyncio.current_task()if active_task is not None:self._work_index.register_active(task_id, active_task)@@ -597,17 +727,30 @@ class TaskTracker:user_id: Optional[str] = None,) -> Optional[TaskRecord]:"""Look up a single task. Returns a snapshot copy (None if not found)."""- async with self._async_lock:- with self._lock:- task = self._tasks.get(task_id)- if task is None and account_id is not None:- task = await self._load_from_store(task_id, account_id, user_id)- if task is not None:- with self._lock:- self._tasks[task.task_id] = task- if task is None or not self._matches_owner(task, account_id, user_id):+ task = self._cached_task(task_id)+ if task is not None:+ if not self._matches_owner(task, account_id, user_id):return Nonereturn self._copy(task)+ if account_id is None:+ return None+ return await self._dispatcher.run(lambda: self._get_on_owner(task_id, account_id, user_id))++ async def _get_on_owner(+ self,+ task_id: str,+ account_id: str,+ user_id: Optional[str],+ ) -> Optional[TaskRecord]:+ task = self._cached_task(task_id)+ if task is None:+ task = await self._load_from_store(task_id, account_id, user_id)+ if task is not None:+ self._merge_loaded_tasks([task])+ task = self._cached_task(task_id)+ if task is None or not self._matches_owner(task, account_id, user_id):+ return None+ return self._copy(task)async def list_tasks(self,@@ -619,16 +762,30 @@ class TaskTracker:user_id: Optional[str] = None,) -> List[TaskRecord]:"""List tasks with optional filters. Most-recent first. Returns snapshot copies."""- async with self._async_lock:- if account_id is not None:- loaded = await self._load_all_from_store(account_id, user_id)- if loaded:- with self._lock:- for task in loaded:- self._tasks[task.task_id] = task- with self._lock:- source = list(self._tasks.values())- tasks = [self._copy(t) for t in source if self._matches_owner(t, account_id, user_id)]+ return await self._dispatcher.run(+ lambda: self._list_tasks_on_owner(+ task_type,+ status,+ resource_id,+ limit,+ account_id,+ user_id,+ )+ )++ async def _list_tasks_on_owner(+ self,+ task_type: Optional[str],+ status: Optional[str],+ resource_id: Optional[str],+ limit: int,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> List[TaskRecord]:+ if account_id is not None:+ self._merge_loaded_tasks(await self._load_all_from_store(account_id, user_id))+ source = self._cache_snapshot()+ tasks = [self._copy(t) for t in source if self._matches_owner(t, account_id, user_id)]if task_type:tasks = [t for t in tasks if t.task_type == task_type]if status:@@ -646,22 +803,32 @@ class TaskTracker:user_id: Optional[str] = None,) -> bool:"""Check if there is already a running task for the given type+resource."""- async with self._async_lock:- if account_id is not None:- loaded = await self._load_all_from_store(account_id, user_id)- if loaded:- with self._lock:- for task in loaded:- self._tasks[task.task_id] = task- with self._lock:- tasks = list(self._tasks.values())- return any(- t.task_type == task_type- and t.resource_id == resource_id- and self._matches_owner(t, account_id, user_id)- and t.status in _ACTIVE_STATUSES- for t in tasks+ return await self._dispatcher.run(+ lambda: self._has_running_on_owner(+ task_type,+ resource_id,+ account_id,+ user_id,)+ )++ async def _has_running_on_owner(+ self,+ task_type: str,+ resource_id: str,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> bool:+ if account_id is not None:+ self._merge_loaded_tasks(await self._load_all_from_store(account_id, user_id))+ tasks = self._cache_snapshot()+ return any(+ t.task_type == task_type+ and t.resource_id == resource_id+ and self._matches_owner(t, account_id, user_id)+ and t.status in _ACTIVE_STATUSES+ for t in tasks+ )async def _load_for_update(self,@@ -669,8 +836,7 @@ class TaskTracker:account_id: Optional[str],user_id: Optional[str],) -> Optional[TaskRecord]:- with self._lock:- task = self._tasks.get(task_id)+ task = self._cached_task(task_id)if task is not None:return task if self._matches_owner(task, account_id, user_id) else Noneif account_id is None or user_id is None:@@ -689,7 +855,10 @@ class TaskTracker:account_id: str,user_id: Optional[str],) -> Optional[TaskRecord]:- payload = await self._store.get(task_id, account_id=account_id, user_id=user_id)+ payload = await self._store_io.run(+ "get",+ lambda: self._store.get(task_id, account_id=account_id, user_id=user_id),+ )if payload is None:return Nonereturn self._record_from_payload(payload)@@ -699,9 +868,64 @@ class TaskTracker:) -> List[TaskRecord]:return [self._record_from_payload(payload)- for payload in await self._store.list(account_id, user_id=user_id)+ for payload in await self._store_io.run(+ "list",+ lambda: self._store.list(account_id, user_id=user_id),+ )]+ async def _persist_and_publish(self, operation: str, task: TaskRecord) -> None:+ committed = False++ async def write_and_publish() -> None:+ nonlocal committed+ if operation == "create":+ await self._store.create(task)+ else:+ await self._store.update(task)+ self._publish_task(task)+ committed = True++ # Semaphore/lock waits remain cancellable. Once the store operation is+ # admitted, settle the physical write and publish its cache snapshot+ # before propagating caller cancellation.+ try:+ await self._store_io.run(+ operation,+ lambda: run_to_completion(write_and_publish),+ )+ except asyncio.CancelledError as exc:+ if committed:+ raise _CommittedMutationCancelled() from exc+ raise++ def _cached_task(self, task_id: str) -> Optional[TaskRecord]:+ with self._lock:+ task = self._tasks.get(task_id)+ return deepcopy(task) if task is not None else None++ def _cache_snapshot(self) -> List[TaskRecord]:+ with self._lock:+ tasks = list(self._tasks.values())+ return [deepcopy(task) for task in tasks]++ def _publish_task(self, task: TaskRecord) -> None:+ published = deepcopy(task)+ with self._lock:+ self._tasks[task.task_id] = published++ def _merge_loaded_tasks(self, loaded_tasks: List[TaskRecord]) -> None:+ candidates = [deepcopy(task) for task in loaded_tasks]+ with self._lock:+ for loaded in candidates:+ cached = self._tasks.get(loaded.task_id)+ if cached is None or loaded.updated_at > cached.updated_at:+ self._tasks[loaded.task_id] = loaded++ @staticmethod+ def _next_updated_at(task: TaskRecord) -> float:+ return max(time.time(), math.nextafter(task.updated_at, math.inf))+@staticmethoddef _copy(task: TaskRecord) -> TaskRecord:"""Return a defensive copy of a TaskRecord."""@@ -719,7 +943,7 @@ class TaskTracker:"""Return a snapshot of task counts grouped by task_type and status."""from collections import defaultdict- grouped: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int)) # type: ignore[assignment]+ grouped: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))with self._lock:tasks = list(self._tasks.values())for t in tasks:diff --git a/openviking/service/task_tracker_concurrency.py b/openviking/service/task_tracker_concurrency.pynew file mode 100644index 000000000..4a6499e43--- /dev/null+++ b/openviking/service/task_tracker_concurrency.py@@ -0,0 +1,256 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++"""Concurrency primitives used by the task tracker."""++import asyncio+import threading+import time+from concurrent.futures import Future as ConcurrentFuture+from concurrent.futures import InvalidStateError+from contextlib import asynccontextmanager+from dataclasses import dataclass+from typing import Any, AsyncIterator, Awaitable, Callable, Coroutine, Generic, TypeVar++from openviking_cli.utils.logger import get_logger++_KeyT = TypeVar("_KeyT")+_ResultT = TypeVar("_ResultT")++logger = get_logger(__name__)+++async def run_to_completion(+ factory: Callable[[], Awaitable[_ResultT]],+) -> _ResultT:+ """Finish started work before propagating caller cancellation.++ ``asyncio.to_thread`` cancellation cannot stop the underlying synchronous+ call. Waiting for the work to settle keeps lock and concurrency accounting+ aligned with the physical I/O lifetime.+ """+ work: asyncio.Future[_ResultT] = asyncio.ensure_future(factory())+ caller = asyncio.current_task()+ cancellation: asyncio.CancelledError | None = None+ while not work.done():+ try:+ await asyncio.shield(work)+ except asyncio.CancelledError as exc:+ if work.cancelled():+ raise+ cancellation = exc+ except BaseException:+ # A completion exception can race with delivery of caller+ # cancellation. Honour the already-requested cancellation below.+ caller_with_cancellation_count: Any = caller+ if (+ caller is None+ or not hasattr(caller, "cancelling")+ or caller_with_cancellation_count.cancelling() == 0+ ):+ raise+ cancellation = asyncio.CancelledError()++ if cancellation is not None:+ if not work.cancelled():+ # Caller cancellation wins once it has been observed. Consume a+ # later work failure so asyncio does not report it as unhandled.+ work.exception()+ raise cancellation+ return work.result()+++class OwnerLoopDispatcher:+ """Run coroutine factories on one event loop, including foreign callers."""++ def __init__(self) -> None:+ self._owner_loop: asyncio.AbstractEventLoop | None = None+ self._bind_lock = threading.Lock()++ def bind_current_loop(self) -> asyncio.AbstractEventLoop:+ current_loop = asyncio.get_running_loop()+ with self._bind_lock:+ if self._owner_loop is None:+ self._owner_loop = current_loop+ elif self._owner_loop is not current_loop:+ raise RuntimeError("owner event loop is already bound")+ return self._owner_loop++ async def run(+ self,+ factory: Callable[[], Coroutine[Any, Any, _ResultT]],+ ) -> _ResultT:+ current_loop = asyncio.get_running_loop()+ with self._bind_lock:+ owner_loop = self._owner_loop+ if owner_loop is None:+ self._owner_loop = current_loop+ owner_loop = current_loop++ if owner_loop.is_closed():+ raise RuntimeError("owner event loop is closed")+ if current_loop is owner_loop:+ return await factory()+ if not owner_loop.is_running():+ raise RuntimeError("owner event loop is not running")++ future: ConcurrentFuture[_ResultT] = ConcurrentFuture()+ owner_task: list[asyncio.Task[_ResultT]] = []++ def transfer_result(task: asyncio.Task[_ResultT]) -> None:+ if future.cancelled():+ if not task.cancelled():+ task.exception()+ return+ try:+ if task.cancelled():+ future.cancel()+ elif (error := task.exception()) is not None:+ future.set_exception(error)+ else:+ future.set_result(task.result())+ except InvalidStateError:+ pass++ def submit_to_owner() -> None:+ if future.cancelled():+ return+ try:+ task = owner_loop.create_task(factory())+ except BaseException as exc:+ try:+ future.set_exception(exc)+ except InvalidStateError:+ pass+ return+ owner_task.append(task)+ task.add_done_callback(transfer_result)++ def cancel_owner_task() -> None:+ if owner_task:+ owner_task[0].cancel()++ def propagate_cancellation(completed: ConcurrentFuture[_ResultT]) -> None:+ if not completed.cancelled():+ return+ try:+ owner_loop.call_soon_threadsafe(cancel_owner_task)+ except RuntimeError:+ pass++ future.add_done_callback(propagate_cancellation)+ try:+ owner_loop.call_soon_threadsafe(submit_to_owner)+ except BaseException:+ future.cancel()+ raise+ wrapped = asyncio.wrap_future(future)+ cancellation: asyncio.CancelledError | None = None+ while True:+ try:+ done, _ = await asyncio.wait((wrapped,), timeout=0.1)+ except asyncio.CancelledError as exc:+ cancellation = cancellation or exc+ try:+ owner_loop.call_soon_threadsafe(cancel_owner_task)+ except RuntimeError:+ pass+ continue+ if done:+ if cancellation is not None:+ if not wrapped.cancelled():+ wrapped.exception()+ raise cancellation+ return wrapped.result()+ if not owner_loop.is_running():+ if owner_task and owner_task[0].done():+ try:+ return owner_task[0].result()+ finally:+ future.cancel()+ if future.cancel():+ if owner_task and owner_task[0].done():+ return owner_task[0].result()+ raise RuntimeError("owner event loop stopped while dispatch was pending")+ return future.result()+++class StoreIOLimiter:+ """Bound task-store concurrency and expose low-cardinality diagnostics."""++ def __init__(self, max_concurrent: int, slow_threshold_seconds: float = 1.0) -> None:+ if max_concurrent <= 0:+ raise ValueError("max_concurrent must be positive")+ self._semaphore = asyncio.Semaphore(max_concurrent)+ self._slow_threshold_seconds = slow_threshold_seconds+ self._inflight = 0+ self._max_observed_inflight = 0++ @property+ def inflight(self) -> int:+ return self._inflight++ @property+ def max_observed_inflight(self) -> int:+ return self._max_observed_inflight++ async def run(+ self,+ operation: str,+ factory: Callable[[], Awaitable[_ResultT]],+ ) -> _ResultT:+ started_at = time.monotonic()+ async with self._semaphore:+ self._inflight += 1+ self._max_observed_inflight = max(+ self._max_observed_inflight,+ self._inflight,+ )+ try:+ return await factory()+ finally:+ self._inflight -= 1+ duration_seconds = time.monotonic() - started_at+ if duration_seconds >= self._slow_threshold_seconds:+ logger.warning(+ "Slow task store operation: operation=%s duration_ms=%.1f",+ operation,+ duration_seconds * 1000,+ )+++@dataclass+class _LockEntry:+ lock: asyncio.Lock+ users: int = 0+++class KeyedAsyncLockPool(Generic[_KeyT]):+ """Serialize work by key without retaining idle lock objects."""++ def __init__(self) -> None:+ self._entries: dict[_KeyT, _LockEntry] = {}++ @property+ def entry_count(self) -> int:+ return len(self._entries)++ @asynccontextmanager+ async def acquire(self, key: _KeyT) -> AsyncIterator[None]:+ entry = self._entries.get(key)+ if entry is None:+ entry = _LockEntry(lock=asyncio.Lock())+ self._entries[key] = entry+ entry.users += 1++ acquired = False+ try:+ await entry.lock.acquire()+ acquired = True+ yield+ finally:+ if acquired:+ entry.lock.release()+ entry.users -= 1+ if entry.users == 0 and self._entries.get(key) is entry:+ del self._entries[key]diff --git a/tests/agfs/test_viking_fs_git.py b/tests/agfs/test_viking_fs_git.pyindex f1b489d92..0985e904e 100644--- a/tests/agfs/test_viking_fs_git.py+++ b/tests/agfs/test_viking_fs_git.py@@ -878,15 +878,15 @@ async def test_restore_returns_pollable_task_id(vfs, monkeypatch):task_id = result.get("task_id")assert task_id- # Let the tracked background worker run to completion.- for _ in range(5):- await asyncio.sleep(0)-from openviking.service.task_tracker import get_task_trackertracker = get_task_tracker()- task = await tracker.get(task_id, account_id=ctx.account_id, user_id=ctx.user.user_id)- assert task is not None+ task = await tracker.wait(+ task_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ timeout=1,+ )assert task.task_type == "snapshot_restore_reindex"assert task.status.value == "completed"assert ("reindex_file", "viking://resources/proj/x.md") in spy.callsdiff --git a/tests/test_task_tracker_concurrency.py b/tests/test_task_tracker_concurrency.pynew file mode 100644index 000000000..fb19e50b4--- /dev/null+++ b/tests/test_task_tracker_concurrency.py@@ -0,0 +1,1106 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import asyncio+import threading+from copy import deepcopy+from typing import Any++import pytest+++class _ControllableTaskStore:+ def __init__(self) -> None:+ self.payloads: dict[str, dict[str, Any]] = {}+ self.create_calls = 0+ self.update_started: dict[str, asyncio.Event] = {}+ self.update_release: dict[str, asyncio.Event] = {}+ self.update_errors: dict[str, Exception] = {}+ self.list_started: asyncio.Event | None = None+ self.list_release: asyncio.Event | None = None+ self.get_calls = 0+ self.operation_loops: list[asyncio.AbstractEventLoop] = []++ @staticmethod+ def _payload(task: Any) -> dict[str, Any]:+ return {+ "task_id": task.task_id,+ "task_type": task.task_type,+ "status": task.status.value,+ "created_at": task.created_at,+ "updated_at": task.updated_at,+ "resource_id": task.resource_id,+ "account_id": task.account_id,+ "user_id": task.user_id,+ "meta": deepcopy(task.meta),+ "stage": task.stage,+ "result": deepcopy(task.result),+ "error": task.error,+ }++ async def create(self, task: Any) -> None:+ self.operation_loops.append(asyncio.get_running_loop())+ self.create_calls += 1+ self.payloads[task.task_id] = self._payload(task)++ async def update(self, task: Any) -> None:+ self.operation_loops.append(asyncio.get_running_loop())+ started = self.update_started.get(task.task_id)+ if started is not None:+ started.set()+ release = self.update_release.get(task.task_id)+ if release is not None:+ await release.wait()+ error = self.update_errors.get(task.task_id)+ if error is not None:+ raise error+ self.payloads[task.task_id] = self._payload(task)++ async def get(+ self,+ task_id: str,+ *,+ account_id: str | None = None,+ user_id: str | None = None,+ ) -> dict[str, Any] | None:+ self.operation_loops.append(asyncio.get_running_loop())+ self.get_calls += 1+ payload = self.payloads.get(task_id)+ if payload is None:+ return None+ if account_id is not None and payload["account_id"] != account_id:+ return None+ if user_id is not None and payload["user_id"] != user_id:+ return None+ return deepcopy(payload)++ async def list(+ self,+ account_id: str,+ *,+ user_id: str | None = None,+ ) -> list[dict[str, Any]]:+ self.operation_loops.append(asyncio.get_running_loop())+ snapshot = [+ deepcopy(payload)+ for payload in self.payloads.values()+ if payload["account_id"] == account_id+ and (user_id is None or payload["user_id"] == user_id)+ ]+ if self.list_started is not None:+ self.list_started.set()+ if self.list_release is not None:+ await self.list_release.wait()+ return snapshot++ async def delete(+ self,+ task_id: str,+ *,+ account_id: str,+ user_id: str | None = None,+ ) -> None:+ self.payloads.pop(task_id, None)+++class _BlockingCreateTaskStore(_ControllableTaskStore):+ def __init__(self, expected_concurrency: int) -> None:+ super().__init__()+ self.expected_concurrency = expected_concurrency+ self.create_release = asyncio.Event()+ self.expected_entered = asyncio.Event()+ self.create_inflight = 0+ self.max_create_inflight = 0++ async def create(self, task: Any) -> None:+ self.create_inflight += 1+ self.max_create_inflight = max(self.max_create_inflight, self.create_inflight)+ if self.create_inflight == self.expected_concurrency:+ self.expected_entered.set()+ try:+ await self.create_release.wait()+ await super().create(task)+ finally:+ self.create_inflight -= 1+++class _ThreadBlockingUpdateTaskStore(_ControllableTaskStore):+ def __init__(self) -> None:+ super().__init__()+ self.thread_update_started = threading.Event()+ self.thread_update_release = threading.Event()+ self._block_next_update = True++ async def update(self, task: Any) -> None:+ if not self._block_next_update:+ await super().update(task)+ return+ self._block_next_update = False+ payload = self._payload(task)++ def blocking_write() -> None:+ self.thread_update_started.set()+ self.thread_update_release.wait()+ self.payloads[task.task_id] = payload++ self.operation_loops.append(asyncio.get_running_loop())+ await asyncio.to_thread(blocking_write)+++async def test_owner_loop_dispatcher_runs_foreign_loop_work_on_owner_loop():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()+ dispatcher.bind_current_loop()+ owner_loop = asyncio.get_running_loop()+ work_loop: asyncio.AbstractEventLoop | None = None++ async def work() -> str:+ nonlocal work_loop+ work_loop = asyncio.get_running_loop()+ return "done"++ def run_from_foreign_loop() -> str:+ return asyncio.run(dispatcher.run(work))++ result = await asyncio.to_thread(run_from_foreign_loop)++ assert result == "done"+ assert work_loop is owner_loop+++async def test_owner_loop_dispatcher_propagates_foreign_cancellation():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()+ dispatcher.bind_current_loop()+ work_started = asyncio.Event()+ work_cancelled = asyncio.Event()+ foreign_ready = threading.Event()+ cancel_foreign = threading.Event()++ async def work() -> None:+ work_started.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ work_cancelled.set()+ raise++ def run_from_foreign_loop() -> None:+ async def invoke() -> None:+ task = asyncio.create_task(dispatcher.run(work))+ foreign_ready.set()+ await asyncio.to_thread(cancel_foreign.wait)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(invoke())++ foreign_call = asyncio.create_task(asyncio.to_thread(run_from_foreign_loop))+ await work_started.wait()+ await asyncio.to_thread(foreign_ready.wait)+ cancel_foreign.set()+ await foreign_call+ await asyncio.wait_for(work_cancelled.wait(), timeout=1)+++def test_owner_loop_dispatcher_rejects_calls_after_owner_loop_closes():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()++ async def bind() -> None:+ dispatcher.bind_current_loop()++ asyncio.run(bind())++ async def invoke() -> None:+ with pytest.raises(RuntimeError, match="owner event loop is closed"):+ await dispatcher.run(lambda: asyncio.sleep(0))++ asyncio.run(invoke())+++def test_owner_loop_dispatcher_rejects_stopped_owner_loop():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()+ owner_loop = asyncio.new_event_loop()+ owner_loop.run_until_complete(asyncio.sleep(0))+ owner_loop.run_until_complete(_bind_dispatcher(dispatcher))++ async def invoke() -> None:+ with pytest.raises(RuntimeError, match="owner event loop is not running"):+ await dispatcher.run(lambda: asyncio.sleep(0))++ try:+ asyncio.run(invoke())+ finally:+ owner_loop.close()+++async def _bind_dispatcher(dispatcher: Any) -> None:+ dispatcher.bind_current_loop()+++def test_owner_loop_dispatcher_concurrent_first_calls_share_winning_loop():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()+ calls_started = threading.Barrier(2)+ work_started = threading.Barrier(2)+ results: list[int] = []+ errors: list[BaseException] = []++ async def work() -> int:+ await asyncio.to_thread(work_started.wait)+ return id(asyncio.get_running_loop())++ def invoke() -> None:+ try:+ calls_started.wait()+ results.append(asyncio.run(dispatcher.run(work)))+ except BaseException as exc:+ errors.append(exc)++ threads = [threading.Thread(target=invoke) for _ in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=2)++ assert not errors+ assert len(results) == 2+ assert results[0] == results[1]+++def test_owner_loop_dispatcher_fails_if_loop_stops_during_dispatch():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()+ owner_loop = asyncio.new_event_loop()+ owner_ready = threading.Event()+ stop_requested = threading.Event()+ let_stop_callback_return = threading.Event()+ first_run_stopped = threading.Event()+ cleanup_queued_callbacks = threading.Event()++ def owner_thread_main() -> None:+ asyncio.set_event_loop(owner_loop)++ def bind() -> None:+ dispatcher.bind_current_loop()+ owner_ready.set()++ owner_loop.call_soon(bind)+ owner_loop.run_forever()+ first_run_stopped.set()+ cleanup_queued_callbacks.wait()+ owner_loop.call_soon(owner_loop.stop)+ owner_loop.run_forever()+ owner_loop.close()++ owner_thread = threading.Thread(target=owner_thread_main)+ owner_thread.start()+ assert owner_ready.wait(timeout=1)++ def stop_inside_owner_callback() -> None:+ owner_loop.stop()+ stop_requested.set()+ let_stop_callback_return.wait()++ owner_loop.call_soon_threadsafe(stop_inside_owner_callback)+ assert stop_requested.wait(timeout=1)++ async def invoke() -> None:+ async def release_callback() -> None:+ await asyncio.sleep(0.05)+ let_stop_callback_return.set()++ release_task = asyncio.create_task(release_callback())+ with pytest.raises(RuntimeError, match="owner event loop stopped"):+ await asyncio.wait_for(+ dispatcher.run(lambda: asyncio.sleep(0)),+ timeout=1,+ )+ await release_task++ asyncio.run(invoke())+ assert first_run_stopped.wait(timeout=1)+ cleanup_queued_callbacks.set()+ owner_thread.join(timeout=2)+ assert not owner_thread.is_alive()+++def test_owner_loop_dispatcher_prefers_completed_result_over_simultaneous_stop():+ from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher++ dispatcher = OwnerLoopDispatcher()+ owner_loop = asyncio.new_event_loop()+ owner_ready = threading.Event()++ def owner_thread_main() -> None:+ asyncio.set_event_loop(owner_loop)++ def bind() -> None:+ dispatcher.bind_current_loop()+ owner_ready.set()++ owner_loop.call_soon(bind)+ owner_loop.run_forever()+ owner_loop.close()++ owner_thread = threading.Thread(target=owner_thread_main)+ owner_thread.start()+ assert owner_ready.wait(timeout=1)++ async def finish_and_stop() -> str:+ owner_loop.stop()+ return "committed"++ result = asyncio.run(dispatcher.run(finish_and_stop))++ owner_thread.join(timeout=2)+ assert result == "committed"+ assert not owner_thread.is_alive()+++async def test_store_io_limiter_bounds_concurrency():+ from openviking.service.task_tracker_concurrency import StoreIOLimiter++ limiter = StoreIOLimiter(max_concurrent=3)+ release = asyncio.Event()+ entered = 0+ max_entered = 0+ limit_reached = asyncio.Event()++ async def operation() -> None:+ nonlocal entered, max_entered+ entered += 1+ max_entered = max(max_entered, entered)+ if entered == 3:+ limit_reached.set()+ await release.wait()+ entered -= 1++ tasks = [asyncio.create_task(limiter.run("test", operation)) for _ in range(20)]+ await asyncio.wait_for(limit_reached.wait(), timeout=1)+ await asyncio.sleep(0)++ assert max_entered == 3+ release.set()+ await asyncio.gather(*tasks)+ assert limiter.inflight == 0+ assert limiter.max_observed_inflight == 3+++def test_store_io_limiter_rejects_non_positive_limit():+ from openviking.service.task_tracker_concurrency import StoreIOLimiter++ with pytest.raises(ValueError, match="max_concurrent must be positive"):+ StoreIOLimiter(max_concurrent=0)+++async def test_run_to_completion_preserves_caller_cancellation_when_work_fails_later():+ from openviking.service.task_tracker_concurrency import run_to_completion++ started = asyncio.Event()+ release = asyncio.Event()++ async def fail_later() -> None:+ started.set()+ await release.wait()+ raise RuntimeError("late store failure")++ operation = asyncio.create_task(run_to_completion(fail_later))+ await started.wait()+ operation.cancel()+ release.set()++ with pytest.raises(asyncio.CancelledError):+ await operation+++async def test_keyed_lock_serializes_same_key_and_allows_different_keys():+ from openviking.service.task_tracker_concurrency import KeyedAsyncLockPool++ pool = KeyedAsyncLockPool[str]()+ first_entered = asyncio.Event()+ release_first = asyncio.Event()+ same_key_entered = asyncio.Event()+ other_key_entered = asyncio.Event()++ async def hold_first_key() -> None:+ async with pool.acquire("task-1"):+ first_entered.set()+ await release_first.wait()++ async def wait_for_same_key() -> None:+ await first_entered.wait()+ async with pool.acquire("task-1"):+ same_key_entered.set()++ async def use_other_key() -> None:+ await first_entered.wait()+ async with pool.acquire("task-2"):+ other_key_entered.set()++ tasks = [+ asyncio.create_task(hold_first_key()),+ asyncio.create_task(wait_for_same_key()),+ asyncio.create_task(use_other_key()),+ ]++ await asyncio.wait_for(other_key_entered.wait(), timeout=1)+ assert not same_key_entered.is_set()++ release_first.set()+ await asyncio.wait_for(same_key_entered.wait(), timeout=1)+ await asyncio.gather(*tasks)+++async def test_keyed_lock_registry_is_cleaned_after_use_and_cancellation():+ from openviking.service.task_tracker_concurrency import KeyedAsyncLockPool++ pool = KeyedAsyncLockPool[str]()++ async with pool.acquire("completed"):+ assert pool.entry_count == 1+ assert pool.entry_count == 0++ blocker_entered = asyncio.Event()+ release_blocker = asyncio.Event()++ async def blocker() -> None:+ async with pool.acquire("cancelled"):+ blocker_entered.set()+ await release_blocker.wait()++ async def waiter() -> None:+ await blocker_entered.wait()+ async with pool.acquire("cancelled"):+ pass++ blocker_task = asyncio.create_task(blocker())+ waiter_task = asyncio.create_task(waiter())+ await blocker_entered.wait()+ await asyncio.sleep(0)++ waiter_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await waiter_task++ release_blocker.set()+ await blocker_task+ assert pool.entry_count == 0+++async def test_task_tracker_different_task_updates_do_not_block_each_other():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ first = await tracker.create("add_resource", account_id="acme", user_id="alice")+ second = await tracker.create("add_resource", account_id="acme", user_id="alice")+ store.update_started[first.task_id] = asyncio.Event()+ store.update_release[first.task_id] = asyncio.Event()++ first_update = asyncio.create_task(tracker.start(first.task_id))+ await store.update_started[first.task_id].wait()++ await asyncio.wait_for(tracker.start(second.task_id), timeout=1)+ second_snapshot = await tracker.get(second.task_id)+ assert second_snapshot is not None+ assert second_snapshot.status == TaskStatus.RUNNING++ store.update_release[first.task_id].set()+ await first_update+++async def test_task_tracker_cache_hit_get_is_not_blocked_by_in_flight_update():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ store.update_started[task.task_id] = asyncio.Event()+ store.update_release[task.task_id] = asyncio.Event()++ update = asyncio.create_task(tracker.start(task.task_id))+ await store.update_started[task.task_id].wait()++ snapshot = await asyncio.wait_for(tracker.get(task.task_id), timeout=0.1)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.PENDING++ store.update_release[task.task_id].set()+ await update+++async def test_task_tracker_failed_update_does_not_contaminate_cached_snapshot():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ store.update_errors[task.task_id] = RuntimeError("store unavailable")++ with pytest.raises(RuntimeError, match="store unavailable"):+ await tracker.start(task.task_id)++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.PENDING+++async def test_cancelled_thread_write_settles_before_later_same_task_mutation():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ThreadBlockingUpdateTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")++ starting = asyncio.create_task(tracker.start(task.task_id))+ await asyncio.to_thread(store.thread_update_started.wait)+ starting.cancel()+ completing = asyncio.create_task(tracker.complete(task.task_id, {"done": True}))+ await asyncio.sleep(0)+ assert not completing.done()++ store.thread_update_release.set()+ with pytest.raises(asyncio.CancelledError):+ await starting+ await completing++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.COMPLETED+ assert store.payloads[task.task_id]["status"] == TaskStatus.COMPLETED.value+ assert tracker._task_locks.entry_count == 0+ assert tracker._store_io.inflight == 0+++ ("outcome", "expected_status"),+ [("complete", "completed"), ("fail", "failed")],+)+async def test_cancelled_outcome_finishes_terminal_transition(outcome, expected_status):+ from openviking.service.task_tracker import TaskTracker++ store = _ThreadBlockingUpdateTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")++ if outcome == "complete":+ operation = asyncio.create_task(tracker.complete(task.task_id, {"done": True}))+ else:+ operation = asyncio.create_task(tracker.fail(task.task_id, "failed on purpose"))+ await asyncio.to_thread(store.thread_update_started.wait)+ operation.cancel()+ store.thread_update_release.set()++ with pytest.raises(asyncio.CancelledError):+ await operation++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status.value == expected_status+ assert store.payloads[task.task_id]["status"] == expected_status+ assert tracker._task_locks.entry_count == 0+ assert tracker._store_io.inflight == 0+++async def test_cancelled_cancel_request_still_cancels_active_work_and_finalizes():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ThreadBlockingUpdateTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ work_started = asyncio.Event()+ work_cancelled = asyncio.Event()++ async def active_work() -> None:+ tracker.register_running_task(task.task_id)+ work_started.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ work_cancelled.set()+ raise+ finally:+ await tracker.unregister_running_task(task.task_id)++ worker = asyncio.create_task(active_work())+ await work_started.wait()+ cancelling = asyncio.create_task(tracker.cancel(task.task_id))+ await asyncio.to_thread(store.thread_update_started.wait)+ cancelling.cancel()+ store.thread_update_release.set()++ with pytest.raises(asyncio.CancelledError):+ await cancelling+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(worker, timeout=1)+ await asyncio.wait_for(work_cancelled.wait(), timeout=1)++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.CANCELLED+ assert store.payloads[task.task_id]["status"] == TaskStatus.CANCELLED.value+ assert tracker._task_locks.entry_count == 0+ assert tracker._store_io.inflight == 0+++async def test_cancel_request_cancelled_before_store_admission_does_not_cancel_work():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store, max_concurrent_store_io=1)+ blocker = await tracker.create("add_resource", account_id="acme", user_id="alice")+ target = await tracker.create("add_resource", account_id="acme", user_id="alice")+ await tracker.start(target.task_id)+ store.update_started[blocker.task_id] = asyncio.Event()+ store.update_release[blocker.task_id] = asyncio.Event()++ blocking_update = asyncio.create_task(tracker.start(blocker.task_id))+ await store.update_started[blocker.task_id].wait()++ work_started = asyncio.Event()+ work_cancelled = asyncio.Event()++ async def active_work() -> None:+ tracker.register_running_task(target.task_id)+ work_started.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ work_cancelled.set()+ raise++ worker = asyncio.create_task(active_work())+ await work_started.wait()+ cancelling = asyncio.create_task(tracker.cancel(target.task_id))+ for _ in range(100):+ if tracker._task_locks.entry_count == 2:+ break+ await asyncio.sleep(0.01)++ cancelling.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(cancelling, timeout=1)++ snapshot = await tracker.get(target.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.RUNNING+ assert not work_cancelled.is_set()+ assert not worker.done()++ worker.cancel()+ with pytest.raises(asyncio.CancelledError):+ await worker+ store.update_release[blocker.task_id].set()+ await blocking_update+++async def test_same_task_late_mutations_cannot_revert_terminal_status():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ await tracker.start(task.task_id)+ store.update_started[task.task_id] = asyncio.Event()+ store.update_release[task.task_id] = asyncio.Event()++ completing = asyncio.create_task(tracker.complete(task.task_id, {"done": True}))+ await store.update_started[task.task_id].wait()+ late_start = asyncio.create_task(tracker.start(task.task_id, stage="late-start"))+ late_stage = asyncio.create_task(tracker.update_stage(task.task_id, "late-stage"))++ store.update_release[task.task_id].set()+ await asyncio.gather(completing, late_start, late_stage)++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.COMPLETED+ assert snapshot.stage == "completed"+++async def test_concurrent_create_with_fixed_task_id_is_idempotent():+ from openviking.service.task_tracker import TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)++ first, second = await asyncio.gather(+ tracker.create(+ "add_resource",+ task_id="fixed",+ account_id="acme",+ user_id="alice",+ ),+ tracker.create(+ "add_resource",+ task_id="fixed",+ account_id="acme",+ user_id="alice",+ ),+ )++ assert first.task_id == second.task_id == "fixed"+ assert store.create_calls == 1+ with pytest.raises(ValueError, match="already belongs to another owner"):+ await tracker.create(+ "add_resource",+ task_id="fixed",+ account_id="acme",+ user_id="bob",+ )+++async def test_task_tracker_cache_hit_does_not_read_store():+ from openviking.service.task_tracker import TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")++ snapshot = await tracker.get(task.task_id, account_id="acme", user_id="alice")++ assert snapshot is not None+ assert snapshot.task_id == task.task_id+ assert store.get_calls == 0+++async def test_task_tracker_list_does_not_replace_newer_cache_with_stale_store_data():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ stale_payload = deepcopy(store.payloads[task.task_id])++ await tracker.start(task.task_id)+ store.payloads[task.task_id] = stale_payload++ snapshots = await tracker.list_tasks(account_id="acme", user_id="alice")++ assert len(snapshots) == 1+ assert snapshots[0].status == TaskStatus.RUNNING+++async def test_blocked_store_list_does_not_block_cached_get():+ from openviking.service.task_tracker import TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ store.list_started = asyncio.Event()+ store.list_release = asyncio.Event()++ listing = asyncio.create_task(tracker.list_tasks(account_id="acme", user_id="alice"))+ await store.list_started.wait()++ snapshot = await asyncio.wait_for(tracker.get(task.task_id), timeout=0.1)+ assert snapshot is not None+ assert snapshot.task_id == task.task_id++ store.list_release.set()+ await listing+++async def test_stale_in_flight_list_does_not_overwrite_completed_cache():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ await tracker.start(task.task_id)+ store.list_started = asyncio.Event()+ store.list_release = asyncio.Event()++ listing = asyncio.create_task(tracker.list_tasks(account_id="acme", user_id="alice"))+ await store.list_started.wait()+ await tracker.complete(task.task_id, {"root_uri": "viking://resources/done"})++ store.list_release.set()+ await listing++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.COMPLETED+++async def test_clock_rollback_cannot_make_stale_store_snapshot_look_newer(monkeypatch):+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ await tracker.start(task.task_id)+ stale_payload = deepcopy(store.payloads[task.task_id])+ monkeypatch.setattr("openviking.service.task_tracker.time.time", lambda: 0.0)++ await tracker.complete(task.task_id, {"done": True})+ store.payloads[task.task_id] = stale_payload+ await tracker.list_tasks(account_id="acme", user_id="alice")++ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.COMPLETED+ assert snapshot.updated_at > stale_payload["updated_at"]+++async def test_task_tracker_store_io_limit_allows_bounded_parallelism():+ from openviking.service.task_tracker import TaskTracker++ store = _BlockingCreateTaskStore(expected_concurrency=3)+ tracker = TaskTracker(store=store, max_concurrent_store_io=3)++ creates = [+ asyncio.create_task(tracker.create("add_resource", account_id="acme", user_id="alice"))+ for _ in range(10)+ ]+ await asyncio.wait_for(store.expected_entered.wait(), timeout=1)+ await asyncio.sleep(0)++ assert store.max_create_inflight == 3+ store.create_release.set()+ await asyncio.gather(*creates)+ assert tracker._store_io.max_observed_inflight == 3+ assert tracker._store_io.inflight == 0+++async def test_cancelled_create_waiting_for_store_slot_has_no_side_effect():+ from openviking.service.task_tracker import TaskTracker++ store = _BlockingCreateTaskStore(expected_concurrency=1)+ tracker = TaskTracker(store=store, max_concurrent_store_io=1)++ first = asyncio.create_task(tracker.create("add_resource", account_id="acme", user_id="alice"))+ await asyncio.wait_for(store.expected_entered.wait(), timeout=1)++ waiting = asyncio.create_task(+ tracker.create("add_resource", account_id="acme", user_id="alice")+ )+ for _ in range(100):+ if tracker._task_locks.entry_count == 2:+ break+ await asyncio.sleep(0.01)+ assert tracker._task_locks.entry_count == 2++ waiting.cancel()+ await asyncio.sleep(0.05)+ cancelled_before_release = waiting.done()+ store.create_release.set()+ with pytest.raises(asyncio.CancelledError):+ await waiting++ created = await first++ assert cancelled_before_release+ assert store.create_calls == 1+ assert set(store.payloads) == {created.task_id}+ assert tracker._task_locks.entry_count == 0+ assert tracker._store_io.inflight == 0+++async def test_cancelled_create_waiting_for_task_lock_finishes_before_lock_release():+ from openviking.service.task_tracker import TaskTracker++ store = _BlockingCreateTaskStore(expected_concurrency=1)+ tracker = TaskTracker(store=store)+ create_args = {+ "task_type": "add_resource",+ "task_id": "fixed",+ "account_id": "acme",+ "user_id": "alice",+ }++ first = asyncio.create_task(tracker.create(**create_args))+ await asyncio.wait_for(store.expected_entered.wait(), timeout=1)+ waiting = asyncio.create_task(tracker.create(**create_args))+ await asyncio.sleep(0)++ waiting.cancel()+ await asyncio.sleep(0.05)+ cancelled_before_release = waiting.done()+ store.create_release.set()+ with pytest.raises(asyncio.CancelledError):+ await waiting++ await first+ assert cancelled_before_release+ assert store.create_calls == 1+++async def test_task_tracker_public_mutation_from_foreign_loop_runs_on_owner():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ owner_loop = asyncio.get_running_loop()+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")++ await asyncio.to_thread(lambda: asyncio.run(tracker.start(task.task_id)))++ with tracker._lock:+ tracker._tasks.pop(task.task_id)+ loaded = await asyncio.to_thread(+ lambda: asyncio.run(tracker.get(task.task_id, account_id="acme", user_id="alice"))+ )++ snapshot = await tracker.get(task.task_id)+ assert loaded is not None+ assert snapshot is not None+ assert snapshot.status == TaskStatus.RUNNING+ assert all(loop is owner_loop for loop in store.operation_loops)+++async def test_cancelling_foreign_mutation_cleans_task_lock_and_store_slot():+ from openviking.service.task_tracker import TaskStatus, TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)+ task = await tracker.create("add_resource", account_id="acme", user_id="alice")+ store.update_started[task.task_id] = asyncio.Event()+ store.update_release[task.task_id] = asyncio.Event()+ cancel_foreign = threading.Event()++ def run_from_foreign_loop() -> None:+ async def invoke() -> None:+ mutation = asyncio.create_task(tracker.start(task.task_id))+ await asyncio.to_thread(cancel_foreign.wait)+ mutation.cancel()+ with pytest.raises(asyncio.CancelledError):+ await mutation++ asyncio.run(invoke())++ foreign_call = asyncio.create_task(asyncio.to_thread(run_from_foreign_loop))+ await store.update_started[task.task_id].wait()+ cancel_foreign.set()+ await asyncio.sleep(0.05)+ returned_before_store_settled = foreign_call.done()+ store.update_release[task.task_id].set()+ await foreign_call++ assert not returned_before_store_settled+ snapshot = await tracker.get(task.task_id)+ assert snapshot is not None+ assert snapshot.status == TaskStatus.RUNNING+ assert tracker._task_locks.entry_count == 0+ assert tracker._store_io.inflight == 0+ assert store.payloads[task.task_id]["status"] == TaskStatus.RUNNING.value+++async def test_create_if_no_running_is_unique_per_business_key():+ from openviking.service.task_tracker import TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)++ results = await asyncio.gather(+ *[+ tracker.create_if_no_running(+ "add_resource",+ "viking://resources/shared",+ account_id="acme",+ user_id="alice",+ )+ for _ in range(20)+ ]+ )++ created = [task for task in results if task is not None]+ assert len(created) == 1+ assert tracker._business_locks.entry_count == 0+ assert tracker._task_locks.entry_count == 0+++async def test_create_if_no_running_uses_independent_business_keys():+ from openviking.service.task_tracker import TaskTracker++ store = _BlockingCreateTaskStore(expected_concurrency=2)+ tracker = TaskTracker(store=store)++ first_call = asyncio.create_task(+ tracker.create_if_no_running(+ "add_resource",+ "viking://resources/one",+ account_id="acme",+ user_id="alice",+ )+ )+ second_call = asyncio.create_task(+ tracker.create_if_no_running(+ "add_resource",+ "viking://resources/two",+ account_id="acme",+ user_id="alice",+ )+ )+ await asyncio.wait_for(store.expected_entered.wait(), timeout=1)+ assert store.max_create_inflight == 2+ store.create_release.set()+ first, second = await asyncio.gather(first_call, second_call)++ assert first is not None+ assert second is not None+ assert first.task_id != second.task_id+++async def test_task_and_business_lock_registries_do_not_grow_with_completed_calls():+ from openviking.service.task_tracker import TaskTracker++ store = _ControllableTaskStore()+ tracker = TaskTracker(store=store)++ tasks = await asyncio.gather(+ *[tracker.create("add_resource", account_id="acme", user_id="alice") for _ in range(100)]+ )+ await asyncio.gather(*(tracker.start(task.task_id) for task in tasks))+ await asyncio.gather(+ *[+ tracker.create_if_no_running(+ "reindex",+ f"viking://resources/{index}",+ account_id="acme",+ user_id="alice",+ )+ for index in range(20)+ ]+ )++ assert tracker._task_locks.entry_count == 0+ assert tracker._business_locks.entry_count == 0