Skip to content

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

fix(queuefs): 隔离后台队列与 HTTP 事件循环 (#5096)

Qin Haojiea681e099e0e2
diff --git a/openviking/concurrency.py b/openviking/concurrency.py
new file mode 100644
index 000000000..e86f74dc8
--- /dev/null
+++ b/openviking/concurrency.py
@@ -0,0 +1,62 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Local synchronization for async callers running on different threads."""
+
+import asyncio
+import threading
+from collections import deque
+from concurrent.futures import Future
+
+
+class AsyncSemaphore:
+ """Limit concurrent operations without binding them to one event loop.
+
+ The thread lock only protects admission and handoff. Contended callers
+ await a future on their own loop; no executor thread is occupied waiting.
+ """
+
+ def __init__(self, value: int = 1) -> None:
+ if value < 0:
+ raise ValueError("Semaphore initial value must be >= 0")
+ self._value = value
+ self._lock = threading.Lock()
+ self._waiters: deque[Future[None]] = deque()
+
+ async def acquire(self) -> None:
+ with self._lock:
+ if self._value:
+ self._value -= 1
+ return
+ waiter: Future[None] = Future()
+ self._waiters.append(waiter)
+ try:
+ await asyncio.wrap_future(waiter)
+ except BaseException:
+ with self._lock:
+ try:
+ self._waiters.remove(waiter)
+ except ValueError:
+ # A granted slot must be returned even if cancellation
+ # reached this loop before the grant callback did.
+ granted = not waiter.cancelled()
+ else:
+ granted = False
+ if granted:
+ self.release()
+ raise
+
+ def release(self) -> None:
+ with self._lock:
+ while self._waiters:
+ waiter = self._waiters.popleft()
+ if waiter.set_running_or_notify_cancel():
+ waiter.set_result(None)
+ return
+ self._value += 1
+
+ async def __aenter__(self) -> "AsyncSemaphore":
+ await self.acquire()
+ return self
+
+ async def __aexit__(self, *exc: object) -> None:
+ self.release()
diff --git a/openviking/resource/uri_mutation_coordinator.py b/openviking/resource/uri_mutation_coordinator.py
index 16a3b62ee..c8ad4e997 100644
--- a/openviking/resource/uri_mutation_coordinator.py
+++ b/openviking/resource/uri_mutation_coordinator.py
@@ -3,6 +3,8 @@
"""Process-local coordination for operations that depend on stable URI scopes."""
import asyncio
+import threading
+from concurrent.futures import Future
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import AsyncIterator, Optional, Sequence
@@ -46,7 +48,8 @@ class UriMutationCoordinator:
"""Coordinate stable URI access and URI mutations within one process."""
def __init__(self) -> None:
- self._condition = asyncio.Condition()
+ self._lock = threading.Lock()
+ self._waiters: set[Future[None]] = set()
self._active_accesses: list[_UriLease] = []
self._active_mutations: list[_UriLease] = []
@@ -79,19 +82,31 @@ class UriMutationCoordinator:
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)
+ while True:
+ with self._lock:
+ if not self._has_blocker(lease, mutation=mutation):
+ self._active_leases(mutation=mutation).append(lease)
+ return
+ waiter: Future[None] = Future()
+ self._waiters.add(waiter)
+ try:
+ await asyncio.wrap_future(waiter)
+ finally:
+ with self._lock:
+ self._waiters.discard(waiter)
async def _release(self, lease: _UriLease, *, mutation: bool) -> None:
- async with self._condition:
+ with self._lock:
active = self._active_leases(mutation=mutation)
for index, current in enumerate(active):
if current is lease:
del active[index]
break
- self._condition.notify_all()
+ waiters = self._waiters
+ self._waiters = set()
+ for waiter in waiters:
+ if waiter.set_running_or_notify_cancel():
+ waiter.set_result(None)
def _has_blocker(self, lease: _UriLease, *, mutation: bool) -> bool:
if any(lease.overlaps(active) for active in self._active_mutations):
diff --git a/openviking/resource/watch_manager.py b/openviking/resource/watch_manager.py
index 62b61f2f5..42f057348 100644
--- a/openviking/resource/watch_manager.py
+++ b/openviking/resource/watch_manager.py
@@ -6,7 +6,6 @@ Resource monitoring task manager.
Provides task creation, update, deletion, query, and persistence storage.
"""
-import asyncio
import json
import uuid
from datetime import datetime, timedelta
@@ -14,6 +13,7 @@ from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
+from openviking.concurrency import AsyncSemaphore
from openviking.observability.http_error_context import sanitize_public_http_error
from openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingMode
from openviking.resource.uri_mutation_coordinator import (
@@ -200,7 +200,7 @@ class WatchManager:
# (a refresh replaces the whole root); Connector watches write
# ``to/<relative_path>`` and may share one target.
self._uri_to_task: Dict[tuple[str, str], set[str]] = {}
- self._lock = asyncio.Lock()
+ self._lock = AsyncSemaphore()
self._uri_mutation_coordinator = uri_mutation_coordinator or UriMutationCoordinator()
self._viking_fs = viking_fs
self._initialized = False
diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.py
index 13d852195..f9fcd4112 100644
--- a/openviking/resource/watch_scheduler.py
+++ b/openviking/resource/watch_scheduler.py
@@ -7,6 +7,7 @@ Provides scheduled task execution for watch tasks.
"""
import asyncio
+import threading
from datetime import datetime
from typing import Any, Dict, Optional, Set
@@ -80,7 +81,7 @@ class WatchScheduler:
self._scheduler_task: Optional[asyncio.Task] = None
self._executing_tasks: Set[str] = set()
self._execution_tasks: Dict[asyncio.Task, WatchTask] = {}
- self._lock = asyncio.Lock()
+ self._lock = threading.Lock()
@property
def watch_manager(self) -> Optional[WatchManager]:
@@ -161,7 +162,7 @@ class WatchScheduler:
logger.warning(f"[WatchScheduler] Task {task_id} not found")
return False
- if not await self._try_mark_executing(task_id):
+ if not self._try_mark_executing(task_id):
logger.info(f"[WatchScheduler] Task {task_id} is already executing, skipping")
return False
@@ -173,7 +174,7 @@ class WatchScheduler:
return True
finally:
self._execution_tasks.pop(execution, None)
- await asyncio.shield(self._discard_executing(task_id))
+ self._discard_executing(task_id)
async def delete_tasks(self, account_id: str, user_id: str | None = None) -> None:
"""Remove an identity's watches and settle their current executions."""
@@ -243,7 +244,7 @@ class WatchScheduler:
tasks_to_run = []
for task in due_tasks:
- if not await self._try_mark_executing(task.task_id):
+ if not self._try_mark_executing(task.task_id):
logger.info(f"[WatchScheduler] Task {task.task_id} is already executing, skipping")
continue
tasks_to_run.append(task)
@@ -253,7 +254,7 @@ class WatchScheduler:
async with self._semaphore:
await self._execute_task(t)
finally:
- await asyncio.shield(self._discard_executing(t.task_id))
+ self._discard_executing(t.task_id)
for due_task in tasks_to_run:
execution = asyncio.create_task(run_one(due_task))
@@ -549,23 +550,23 @@ class WatchScheduler:
Used while an import's first round runs so a due tick does not start an
overlapping run; release with :meth:`release_execution`.
"""
- held = await self._try_mark_executing(task_id)
+ held = self._try_mark_executing(task_id)
logger.debug(f"[WatchScheduler] hold_execution task_id={task_id} held={held}")
return held
async def release_execution(self, task_id: str) -> None:
- await self._discard_executing(task_id)
+ self._discard_executing(task_id)
logger.debug(f"[WatchScheduler] release_execution task_id={task_id}")
- async def _try_mark_executing(self, task_id: str) -> bool:
- async with self._lock:
+ def _try_mark_executing(self, task_id: str) -> bool:
+ with self._lock:
if task_id in self._executing_tasks:
return False
self._executing_tasks.add(task_id)
return True
- async def _discard_executing(self, task_id: str) -> None:
- async with self._lock:
+ def _discard_executing(self, task_id: str) -> None:
+ with self._lock:
self._executing_tasks.discard(task_id)
async def _prepare_feishu_auth_state(
@@ -627,4 +628,5 @@ class WatchScheduler:
@property
def executing_tasks(self) -> Set[str]:
"""Get the set of currently executing task IDs."""
- return self._executing_tasks.copy()
+ with self._lock:
+ return self._executing_tasks.copy()
diff --git a/openviking/service/core.py b/openviking/service/core.py
index c3dd0d124..413ec0047 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -498,7 +498,6 @@ class OpenVikingService:
queue_name,
dequeue_handler=AddResourceProcessor(
self._resource_service,
- asyncio.get_running_loop(),
queue_name,
self._viking_fs,
),
@@ -508,7 +507,6 @@ class OpenVikingService:
self._queue_manager.SESSION_COMMIT,
dequeue_handler=SessionCommitProcessor(
self._session_service,
- asyncio.get_running_loop(),
),
allow_create=True,
)
@@ -516,7 +514,6 @@ class OpenVikingService:
self._queue_manager.EXTERNAL_TASK,
dequeue_handler=ExternalTaskProcessor(
self._external_task_service,
- asyncio.get_running_loop(),
),
allow_create=True,
)
diff --git a/openviking/service/external_task_service.py b/openviking/service/external_task_service.py
index 63708d390..d9c8bd26c 100644
--- a/openviking/service/external_task_service.py
+++ b/openviking/service/external_task_service.py
@@ -92,7 +92,8 @@ class ExternalTaskService:
def __init__(self) -> None:
self._providers: dict[str, ExternalTaskProvider] = {}
- # Accessed only on the service loop. Restored owners may include multiple
+ # Restored before workers start, then accessed only by the ExternalTask
+ # queue's loop. Restored owners may include multiple
# tasks submitted before target serialization was enabled.
self._owners: dict[tuple[str | None, str, str], set[str]] = {}
self._executing: set[str] = set()
@@ -331,7 +332,7 @@ class ExternalTaskService:
if task_id in self._executing or (owners and task_id not in owners):
return False
# No await between checking and claiming: concurrent deliveries on the
- # service loop cannot both acquire an unoccupied target.
+ # queue loop cannot both acquire an unoccupied target.
if key is not None:
self._owners.setdefault(key, set()).add(task_id)
self._executing.add(task_id)
diff --git a/openviking/service/resource_memory_link_service.py b/openviking/service/resource_memory_link_service.py
index a9c2f49b6..7a80c1e40 100644
--- a/openviking/service/resource_memory_link_service.py
+++ b/openviking/service/resource_memory_link_service.py
@@ -8,12 +8,12 @@ files' MEMORY_FIELDS metadata.
from __future__ import annotations
-import asyncio
import re
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
+from openviking.concurrency import AsyncSemaphore
from openviking.core.namespace import (
NamespaceShapeError,
canonical_user_root,
@@ -127,7 +127,8 @@ class ResourceMemoryLinkService:
self._vikingdb = vikingdb
self._viking_fs = viking_fs
self._session_service = session_service
- self._reason_session_lock = asyncio.Lock()
+ # Additions run on queue loops; deletions can run on the HTTP loop.
+ self._reason_session_lock = AsyncSemaphore()
def set_dependencies(
self,
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index f5713b701..d70d7b32c 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -33,7 +33,6 @@ from openviking.service.task_events import (
from openviking.service.task_store import TaskStore
from openviking.service.task_tracker_concurrency import (
KeyedAsyncLockPool,
- OwnerLoopDispatcher,
StoreIOLimiter,
run_to_completion,
)
@@ -182,8 +181,8 @@ def _sanitize_task_result(result: Any) -> Any:
class TaskTracker:
"""Async task tracker with persistent storage and a process-local cache.
- Mutations are serialized per task on one owner event loop. The thread lock
- only protects short, synchronous accesses to immutable cache snapshots.
+ Mutations are serialized per task across caller threads and event loops.
+ The thread lock only protects short accesses to immutable cache snapshots.
"""
MAX_TASKS = 10_000
@@ -197,7 +196,6 @@ class TaskTracker:
self._lock = threading.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)
@@ -221,7 +219,6 @@ 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._dispatcher.bind_current_loop()
self._install_work_index_callbacks()
async def restore_work_tasks(self, owners: Dict[str, tuple[str, str]]) -> List[TaskRecord]:
@@ -235,12 +232,10 @@ class TaskTracker:
async def _finalize_before_ack(self, metadata: QueueTaskMetadata) -> None:
"""Persist the terminal state before QueueFS removes the last recovery message."""
- 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,
- )
+ await self._finalize_task(
+ metadata.task_id,
+ account_id=metadata.account_id or None,
+ user_id=metadata.user_id or None,
)
def is_cancellation_requested(self, task_id: str) -> bool:
@@ -260,7 +255,6 @@ class TaskTracker:
"""
if self._cleanup_task is not None and not self._cleanup_task.done():
return
- self._dispatcher.bind_current_loop()
self._cleanup_task = asyncio.create_task(self._cleanup_loop())
logger.debug("[TaskTracker] Cleanup loop started")
@@ -282,9 +276,6 @@ 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()
with self._lock:
expired_ids = [
@@ -293,7 +284,7 @@ class TaskTracker:
evicted_count = 0
for task_id in expired_ids:
- evicted_count += await self._delete_expired_task_on_owner(task_id, now)
+ evicted_count += await self._delete_expired_task(task_id, now)
with self._lock:
if len(self._tasks) > self.MAX_TASKS:
@@ -311,7 +302,7 @@ class TaskTracker:
return age > self.TTL_COMPLETED
return task.status == TaskStatus.FAILED and age > self.TTL_FAILED
- async def _delete_expired_task_on_owner(self, task_id: str, now: float) -> bool:
+ async def _delete_expired_task(self, task_id: str, now: float) -> bool:
async with self._task_locks.acquire(task_id):
task = self._cached_task(task_id)
if task is None or not self._is_expired(task, now):
@@ -390,11 +381,8 @@ class TaskTracker:
meta=dict(meta or {}),
auth=dict(auth or {}),
)
- 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:
+ if task_id is not None:
existing = self._cached_task(task.task_id)
if existing is not None:
if not self._matches_owner(existing, task.account_id, task.user_id):
@@ -434,24 +422,6 @@ class TaskTracker:
"""
self._validate_owner(account_id, user_id)
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))
@@ -490,17 +460,6 @@ class TaskTracker:
stage: Optional[str] = None,
) -> None:
"""Transition task to RUNNING."""
- 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):
@@ -521,18 +480,6 @@ class TaskTracker:
meta: Optional[Dict[str, Any]] = None,
) -> None:
"""Update task progress without changing its lifecycle status."""
- await self._dispatcher.run(
- lambda: self._update_stage_on_owner(task_id, stage, account_id, user_id, meta)
- )
-
- async def _update_stage_on_owner(
- self,
- task_id: str,
- stage: str,
- account_id: Optional[str],
- user_id: Optional[str],
- meta: Optional[Dict[str, Any]],
- ) -> 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 _ACTIVE_STATUSES:
@@ -553,22 +500,6 @@ class TaskTracker:
) -> None:
"""Persist private state required to resume an active task."""
self._validate_owner(account_id, user_id)
- await self._dispatcher.run(
- lambda: self._update_task_auth_on_owner(
- task_id,
- values,
- account_id,
- user_id,
- )
- )
-
- async def _update_task_auth_on_owner(
- self,
- task_id: str,
- values: Dict[str, Any],
- account_id: str,
- user_id: 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 _ACTIVE_STATUSES:
@@ -587,17 +518,14 @@ class TaskTracker:
) -> None:
"""Persist a child submission before polling so a source retry can resume it."""
- async def record() -> None:
- async with self._task_locks.acquire(task_id):
- task = await self._load_for_update(task_id, account_id, user_id)
- if task is None or task.status not in (TaskStatus.PENDING, TaskStatus.RUNNING):
- raise ValueError("Feishu source task is no longer active")
- updated = deepcopy(task)
- updated.meta.setdefault("feishu_responses", {})[entry] = response_id
- updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated, previous=task)
-
- await self._dispatcher.run(record)
+ async with self._task_locks.acquire(task_id):
+ task = await self._load_for_update(task_id, account_id, user_id)
+ if task is None or task.status not in (TaskStatus.PENDING, TaskStatus.RUNNING):
+ raise ValueError("Feishu source task is no longer active")
+ updated = deepcopy(task)
+ updated.meta.setdefault("feishu_responses", {})[entry] = response_id
+ updated.updated_at = self._next_updated_at(task)
+ await self._persist_and_publish("update", updated, previous=task)
async def complete(
self,
@@ -656,16 +584,6 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> None:
"""Record cancellation reported by the task owner without cancelling its worker."""
- await self._dispatcher.run(
- lambda: self._record_cancelled_on_owner(task_id, account_id, user_id)
- )
-
- async def _record_cancelled_on_owner(
- self,
- task_id: 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 _ACTIVE_STATUSES:
@@ -673,7 +591,7 @@ class TaskTracker:
updated.status = TaskStatus.CANCELLING
updated.updated_at = self._next_updated_at(task)
await self._persist_and_publish("update", updated, previous=task)
- await self._finalize_task_on_owner(task_id, account_id, user_id)
+ await self._finalize_task(task_id, account_id, user_id)
async def _record_outcome(
self,
@@ -685,29 +603,6 @@ class TaskTracker:
error: Optional[str] = None,
resource_id: Optional[str] = None,
terminal_status: Optional[TaskStatus] = None,
- ) -> None:
- await self._dispatcher.run(
- lambda: self._record_outcome_on_owner(
- task_id,
- account_id,
- user_id,
- result=result,
- error=error,
- resource_id=resource_id,
- terminal_status=terminal_status,
- )
- )
-
- 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],
- terminal_status: Optional[TaskStatus],
) -> None:
cancellation: asyncio.CancelledError | None = None
outcome_persisted = False
@@ -739,7 +634,7 @@ class TaskTracker:
if outcome_persisted:
try:
await run_to_completion(
- lambda: self._finalize_task_on_owner(
+ lambda: self._finalize_task(
task_id,
account_id=account_id,
user_id=user_id,
@@ -748,7 +643,7 @@ class TaskTracker:
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)
+ await self._finalize_task(task_id, account_id=account_id, user_id=user_id)
if cancellation is not None:
raise cancellation
@@ -759,16 +654,6 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> Optional[TaskRecord]:
"""Request cooperative cancellation and return the current task snapshot."""
- 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):
@@ -796,7 +681,7 @@ class TaskTracker:
async def finish_cancellation() -> None:
self._work_index.cancel_active(task_id)
- await self._finalize_task_on_owner(
+ await self._finalize_task(
task_id,
account_id=account_id,
user_id=user_id,
@@ -823,16 +708,6 @@ 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._task_locks.acquire(task_id):
@@ -893,17 +768,14 @@ class TaskTracker:
"""Load task-owned authentication excluded from public snapshots."""
self._validate_owner(account_id, user_id)
- async def load() -> Dict[str, Any]:
- 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._publish_task(task)
- if task is None or not self._matches_owner(task, account_id, user_id):
- return {}
- return deepcopy(task.auth)
-
- return await self._dispatcher.run(load)
+ 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._publish_task(task)
+ if task is None or not self._matches_owner(task, account_id, user_id):
+ return {}
+ return deepcopy(task.auth)
def forget_account_tasks(self, account_id: str) -> None:
"""Invalidate snapshots after executions settle and account storage is removed."""
@@ -919,11 +791,6 @@ class TaskTracker:
async def delete_user_tasks(self, account_id: str, user_id: str) -> int:
"""Delete terminal task records for one user from storage and cache."""
self._validate_owner(account_id, user_id)
- return await self._dispatcher.run(
- lambda: self._delete_user_tasks_on_owner(account_id, user_id)
- )
-
- async def _delete_user_tasks_on_owner(self, account_id: str, user_id: str) -> int:
self._merge_loaded_tasks(await self._load_all_from_store(account_id, user_id))
tasks = [
task
@@ -998,23 +865,20 @@ class TaskTracker:
if operation is not None and not re.fullmatch(r"[\w.:-]{1,128}", operation):
raise ValueError("operation must be a bounded operation identifier")
- async def record() -> None:
- async with self._task_locks.acquire(task_id):
- task = await self._load_for_update(task_id, account_id, user_id)
- if task is None or task.status not in _ACTIVE_STATUSES:
- return
- updated = deepcopy(task)
- updated.execution_events = append_task_event(
- updated.execution_events,
- kind=kind,
- status=task.status.value,
- stage=_sanitize_error(task.stage) if task.stage else None,
- operation=operation,
- )
- updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated, previous=task)
-
- await self._dispatcher.run(record)
+ async with self._task_locks.acquire(task_id):
+ task = await self._load_for_update(task_id, account_id, user_id)
+ if task is None or task.status not in _ACTIVE_STATUSES:
+ return
+ updated = deepcopy(task)
+ updated.execution_events = append_task_event(
+ updated.execution_events,
+ kind=kind,
+ status=task.status.value,
+ stage=_sanitize_error(task.stage) if task.stage else None,
+ operation=operation,
+ )
+ updated.updated_at = self._next_updated_at(task)
+ await self._persist_and_publish("update", updated, previous=task)
def has_work(self, task_id: str) -> bool:
"""Return whether a task still owns durable or active queue work."""
@@ -1047,20 +911,10 @@ class TaskTracker:
return 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)
+ 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)
@@ -1153,28 +1007,6 @@ class TaskTracker:
include_internal: bool = True,
) -> List[TaskRecord]:
"""List tasks with optional filters. Most-recent first. Returns snapshot copies."""
- return await self._dispatcher.run(
- lambda: self._list_tasks_on_owner(
- task_type,
- status,
- resource_id,
- limit,
- account_id,
- user_id,
- include_internal,
- )
- )
-
- async def _list_tasks_on_owner(
- self,
- task_type: Optional[str],
- status: Optional[str],
- resource_id: Optional[str],
- limit: Optional[int],
- account_id: Optional[str],
- user_id: Optional[str],
- include_internal: bool,
- ) -> 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()
@@ -1198,22 +1030,6 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> bool:
"""Check if there is already a running task for the given type+resource."""
- 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()
diff --git a/openviking/service/task_tracker_concurrency.py b/openviking/service/task_tracker_concurrency.py
index d661a8fb8..f0572d1b8 100644
--- a/openviking/service/task_tracker_concurrency.py
+++ b/openviking/service/task_tracker_concurrency.py
@@ -12,6 +12,7 @@ from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Any, AsyncIterator, Awaitable, Callable, Coroutine, Generic, TypeVar
+from openviking.concurrency import AsyncSemaphore
from openviking_cli.utils.logger import get_logger
_KeyT = TypeVar("_KeyT")
@@ -181,18 +182,21 @@ class StoreIOLimiter:
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._semaphore = AsyncSemaphore(max_concurrent)
+ self._lock = threading.Lock()
self._slow_threshold_seconds = slow_threshold_seconds
self._inflight = 0
self._max_observed_inflight = 0
@property
def inflight(self) -> int:
- return self._inflight
+ with self._lock:
+ return self._inflight
@property
def max_observed_inflight(self) -> int:
- return self._max_observed_inflight
+ with self._lock:
+ return self._max_observed_inflight
async def run(
self,
@@ -201,15 +205,17 @@ class StoreIOLimiter:
) -> _ResultT:
started_at = time.monotonic()
async with self._semaphore:
- self._inflight += 1
- self._max_observed_inflight = max(
- self._max_observed_inflight,
- self._inflight,
- )
+ with self._lock:
+ self._inflight += 1
+ self._max_observed_inflight = max(
+ self._max_observed_inflight,
+ self._inflight,
+ )
try:
return await factory()
finally:
- self._inflight -= 1
+ with self._lock:
+ self._inflight -= 1
duration_seconds = time.monotonic() - started_at
if duration_seconds >= self._slow_threshold_seconds:
logger.warning(
@@ -221,7 +227,7 @@ class StoreIOLimiter:
@dataclass
class _LockEntry:
- lock: asyncio.Lock
+ lock: AsyncSemaphore
users: int = 0
@@ -230,18 +236,21 @@ class KeyedAsyncLockPool(Generic[_KeyT]):
def __init__(self) -> None:
self._entries: dict[_KeyT, _LockEntry] = {}
+ self._lock = threading.Lock()
@property
def entry_count(self) -> int:
- return len(self._entries)
+ with self._lock:
+ 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
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is None:
+ entry = _LockEntry(lock=AsyncSemaphore())
+ self._entries[key] = entry
+ entry.users += 1
acquired = False
try:
@@ -251,6 +260,7 @@ class KeyedAsyncLockPool(Generic[_KeyT]):
finally:
if acquired:
entry.lock.release()
- entry.users -= 1
- if entry.users == 0 and self._entries.get(key) is entry:
- del self._entries[key]
+ with self._lock:
+ entry.users -= 1
+ if entry.users == 0:
+ del self._entries[key]
diff --git a/openviking/storage/queuefs/add_resource_processor.py b/openviking/storage/queuefs/add_resource_processor.py
index 61e39fb26..ba9ce7390 100644
--- a/openviking/storage/queuefs/add_resource_processor.py
+++ b/openviking/storage/queuefs/add_resource_processor.py
@@ -11,7 +11,6 @@ from typing import Any, Dict, Optional
from openviking.observability.context import bind_execution_context
from openviking.server.identity import RequestContext, Role
from openviking.service.task_tracker import TaskStatus, get_task_tracker
-from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher
from openviking.service.task_work_index import bind_task_context, extract_task_metadata
from openviking.storage.queuefs.add_resource_msg import AddResourceMsg
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
@@ -38,12 +37,10 @@ class AddResourceProcessor(DequeueHandlerBase):
def __init__(
self,
resource_service: Any,
- service_loop: asyncio.AbstractEventLoop,
queue_name: str,
viking_fs: Any,
):
self._resource_service = resource_service
- self._dispatcher = OwnerLoopDispatcher(service_loop)
self._queue_name = queue_name
self._viking_fs = viking_fs
@@ -340,16 +337,14 @@ class AddResourceProcessor(DequeueHandlerBase):
msg = AddResourceMsg.from_dict(payload)
except (json.JSONDecodeError, TypeError, ValueError) as exc:
return ProcessResult.failed(str(exc))
- await self._dispatcher.run(
- lambda: self._handle_cancelled(
- msg,
- RequestContext(
- user=UserIdentifier(msg.account_id, msg.user_id),
- role=Role(msg.role),
- group_ids=tuple(msg.group_ids),
- actor_peer_id=msg.actor_peer_id,
- bypass_acl=msg.bypass_acl,
- ),
+ await self._handle_cancelled(
+ msg,
+ RequestContext(
+ user=UserIdentifier(msg.account_id, msg.user_id),
+ role=Role(msg.role),
+ group_ids=tuple(msg.group_ids),
+ actor_peer_id=msg.actor_peer_id,
+ bypass_acl=msg.bypass_acl,
),
)
unregister_telemetry(msg.telemetry_id or "")
@@ -368,4 +363,4 @@ class AddResourceProcessor(DequeueHandlerBase):
except (json.JSONDecodeError, TypeError, ValueError) as exc:
return ProcessResult.failed(str(exc))
- return await self._dispatcher.run(lambda: self._process(msg, data))
+ return await self._process(msg, data)
diff --git a/openviking/storage/queuefs/external_task_processor.py b/openviking/storage/queuefs/external_task_processor.py
index 7a97a8077..47a8ea14b 100644
--- a/openviking/storage/queuefs/external_task_processor.py
+++ b/openviking/storage/queuefs/external_task_processor.py
@@ -4,12 +4,10 @@
from __future__ import annotations
-import asyncio
import json
from typing import Any, Dict, Optional
from openviking.service.external_task_service import ExternalTaskService
-from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher
from openviking.service.task_work_index import TaskWorkRejected
from openviking.storage.queuefs import QueueManager, get_queue_manager
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
@@ -20,12 +18,8 @@ class ExternalTaskProcessor(DequeueHandlerBase):
def __init__(
self,
service: ExternalTaskService,
- service_loop: asyncio.AbstractEventLoop,
) -> None:
self._service = service
- self._dispatcher = OwnerLoopDispatcher()
- if self._dispatcher.bind_current_loop() is not service_loop:
- raise ValueError("ExternalTaskProcessor must be created on the service event loop")
@staticmethod
def _parse(data: Dict[str, Any]) -> tuple[str, str, str]:
@@ -48,9 +42,7 @@ class ExternalTaskProcessor(DequeueHandlerBase):
task_id, account_id, user_id = self._parse(data)
except (json.JSONDecodeError, TypeError, ValueError) as exc:
return ProcessResult.failed(str(exc))
- processed = await self._dispatcher.run(
- lambda: self._service.execute(task_id, account_id, user_id)
- )
+ processed = await self._service.execute(task_id, account_id, user_id)
if not processed:
# Register a new delivery before the old one is ACKed. Keeping the
# task ID preserves cancellation and task-owned work across rotation.
@@ -73,9 +65,7 @@ class ExternalTaskProcessor(DequeueHandlerBase):
task_id, account_id, user_id = self._parse(data)
except (json.JSONDecodeError, TypeError, ValueError) as exc:
return ProcessResult.failed(str(exc))
- await self._dispatcher.run(
- lambda: self._service.cancel_recovered(task_id, account_id, user_id)
- )
+ await self._service.cancel_recovered(task_id, account_id, user_id)
return ProcessResult.cancelled()
diff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.py
index b4d6f53b8..b248fae50 100644
--- a/openviking/storage/queuefs/queue_manager.py
+++ b/openviking/storage/queuefs/queue_manager.py
@@ -267,6 +267,15 @@ class QueueManager:
traceback.print_exc()
stop_event.wait(poll_interval)
finally:
+ # Consumers may own timers and async generators in addition to
+ # their active queue deliveries. Finish them on the worker loop.
+ pending = asyncio.all_tasks(loop)
+ for task in pending:
+ task.cancel()
+ if pending:
+ loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ loop.run_until_complete(loop.shutdown_default_executor())
loop.close()
async def _worker_async_concurrent(
diff --git a/openviking/storage/queuefs/session_commit_processor.py b/openviking/storage/queuefs/session_commit_processor.py
index 8677f6400..9eb14088b 100644
--- a/openviking/storage/queuefs/session_commit_processor.py
+++ b/openviking/storage/queuefs/session_commit_processor.py
@@ -2,7 +2,6 @@
# SPDX-License-Identifier: AGPL-3.0
"""Queue consumer for restart-safe Session Phase 2 work."""
-import asyncio
import json
from typing import TYPE_CHECKING, Any, Dict, Optional
@@ -12,7 +11,6 @@ from openviking.observability.context import (
)
from openviking.server.identity import RequestContext, Role
from openviking.service.task_tracker import get_task_tracker
-from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher
from openviking.service.task_work_index import bind_task_context
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
from openviking.storage.queuefs.process_result import ProcessResult
@@ -28,10 +26,8 @@ class SessionCommitProcessor(DequeueHandlerBase):
def __init__(
self,
session_service: "SessionService",
- service_loop: asyncio.AbstractEventLoop,
) -> None:
self._session_service = session_service
- self._dispatcher = OwnerLoopDispatcher(service_loop)
@staticmethod
def _parse_message(data: Dict[str, Any]) -> tuple[SessionCommitMsg, RequestContext]:
@@ -48,8 +44,8 @@ class SessionCommitProcessor(DequeueHandlerBase):
async def _process(self, msg: SessionCommitMsg, ctx: RequestContext) -> bool:
# Bind a root observability context so Phase-2 extraction VLM/embedding
# token events are attributed to the committing account/user rather than
- # "__unknown__" (mirrors SemanticProcessor.on_dequeue). Bind inside the
- # dispatched operation to cover direct calls and restore the caller context.
+ # "__unknown__" (mirrors SemanticProcessor.on_dequeue). Restore the
+ # worker's previous context when processing finishes.
root_attrs = create_root_span_attributes(
http_method="QUEUE",
http_route="/queuefs/session_commit",
@@ -114,7 +110,7 @@ class SessionCommitProcessor(DequeueHandlerBase):
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
return ProcessResult.failed(str(exc))
- await self._dispatcher.run(lambda: self._finalize_cancelled(msg, ctx))
+ await self._finalize_cancelled(msg, ctx)
return ProcessResult.cancelled()
async def on_dequeue(self, data: Optional[Dict[str, Any]]) -> ProcessResult:
@@ -125,5 +121,5 @@ class SessionCommitProcessor(DequeueHandlerBase):
msg, ctx = self._parse_message(data)
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
return ProcessResult.failed(str(exc))
- processed = await self._dispatcher.run(lambda: self._process(msg, ctx))
+ processed = await self._process(msg, ctx)
return ProcessResult.success() if processed else ProcessResult.requeued()
diff --git a/tests/parse/test_feishu_parser_api.py b/tests/parse/test_feishu_parser_api.py
index a0a90f412..eff5ccd83 100644
--- a/tests/parse/test_feishu_parser_api.py
+++ b/tests/parse/test_feishu_parser_api.py
@@ -42,7 +42,6 @@ async def test_add_resource_processor_cancelled_context_preserves_group_ids(monk
)
processor = AddResourceProcessor(
service,
- asyncio.get_running_loop(),
QueueManager.ADD_RESOURCE,
viking_fs,
)
@@ -1017,7 +1016,6 @@ async def test_add_resource_processor_persists_final_uri_and_cleans_staged_sourc
)
processor = AddResourceProcessor(
service,
- asyncio.get_running_loop(),
QueueManager.ADD_RESOURCE,
viking_fs,
)
@@ -1156,7 +1154,6 @@ async def test_add_resource_processor_collects_stats_without_registered_telemetr
execute_add_resource_job=AsyncMock(side_effect=execute_add_resource_job),
_link_resource_reason_memory=AsyncMock(),
),
- asyncio.get_running_loop(),
QueueManager.ADD_RESOURCE,
SimpleNamespace(_async_agfs=SimpleNamespace(pathlock_release=AsyncMock())),
)
@@ -1220,7 +1217,6 @@ async def test_add_resource_processor_replay_skips_lock_adopt_when_result_exists
)
processor = AddResourceProcessor(
service,
- asyncio.get_running_loop(),
QueueManager.ADD_RESOURCE,
SimpleNamespace(_async_agfs=async_agfs),
)
@@ -1273,7 +1269,6 @@ async def test_add_resource_processor_reports_zero_vectors(monkeypatch):
)
processor = AddResourceProcessor(
service,
- asyncio.get_running_loop(),
QueueManager.ADD_RESOURCE,
SimpleNamespace(_async_agfs=SimpleNamespace(pathlock_release=AsyncMock())),
)
diff --git a/tests/resource/test_watch_manager.py b/tests/resource/test_watch_manager.py
index d7d670dec..e4e136aa5 100644
--- a/tests/resource/test_watch_manager.py
+++ b/tests/resource/test_watch_manager.py
@@ -881,7 +881,9 @@ class TestWatchManagerConcurrency:
to_uri=f"viking://resources/test{index}",
)
- tasks = await asyncio.gather(*[create_task(i) for i in range(10)])
+ tasks = await asyncio.gather(
+ *[asyncio.to_thread(lambda i=i: asyncio.run(create_task(i))) for i in range(10)]
+ )
assert len(tasks) == 10
assert len({task.task_id for task in tasks}) == 10
@@ -895,28 +897,33 @@ class TestWatchManagerConcurrency:
@pytest.mark.asyncio
async def test_concurrent_read_write(self, watch_manager: WatchManager):
- """Test concurrent read and write operations."""
+ """A background result must preserve a concurrent HTTP pause, including on disk."""
task = await watch_manager.create_task(path="/test/path")
- async def update_task(index: int):
+ async def pause_task():
await watch_manager.update_task(
task_id=task.task_id,
account_id=TEST_ACCOUNT_ID,
user_id=TEST_USER_ID,
role=TEST_ROLE,
- reason=f"Update {index}",
+ is_active=False,
)
- async def read_task():
- return await watch_manager.get_task(task.task_id)
-
- operations = [update_task(i) for i in range(5)] + [read_task() for _ in range(5)]
- results = await asyncio.gather(*operations, return_exceptions=True)
-
- assert all(not isinstance(r, Exception) for r in results)
-
- final_task = await watch_manager.get_task(task.task_id)
+ await asyncio.gather(
+ pause_task(),
+ asyncio.to_thread(
+ lambda: asyncio.run(
+ watch_manager.record_execution(task.task_id, status="completed")
+ )
+ ),
+ )
+ restored = WatchManager(viking_fs=watch_manager._viking_fs)
+ await restored.initialize()
+ final_task = await restored.get_task(task.task_id)
assert final_task is not None
+ assert final_task.is_active is False
+ assert final_task.last_status == "completed"
+ assert final_task.next_execution_time is None
_CONNECTOR_AUTH = {"provider": "connector_encrypted", "ciphertext": "unused"}
diff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.py
index 518ae4f4b..cf0e48f23 100644
--- a/tests/resource/test_watch_scheduler.py
+++ b/tests/resource/test_watch_scheduler.py
@@ -1,4 +1,5 @@
import asyncio
+import threading
from datetime import datetime, timedelta
from unittest.mock import AsyncMock
@@ -278,9 +279,18 @@ class TestWatchSchedulerResourceExistence:
processing_mode="vectors_only",
)
+ started = threading.Event()
+
+ async def execute_from_worker():
+ started.set()
+ await scheduler._execute_task(task.model_copy(deep=True))
+
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)
+ execution = asyncio.create_task(
+ asyncio.to_thread(lambda: asyncio.run(execute_from_worker()))
+ )
+ assert await asyncio.to_thread(started.wait, 3)
+ await asyncio.sleep(0.01)
assert resource_service.calls == []
await manager.rewrite_target_prefix_internal(
old_uri,
diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.py
index 99b19c348..3894e9dae 100644
--- a/tests/server/test_bot_proxy_auth.py
+++ b/tests/server/test_bot_proxy_auth.py
@@ -530,7 +530,7 @@ async def test_compile_api_client_session_protocol_retry_and_cancellation(
manager = QueueManager(agfs=object())
queue = manager.get_queue(
QueueManager.EXTERNAL_TASK,
- dequeue_handler=ExternalTaskProcessor(tasks, asyncio.get_running_loop()),
+ dequeue_handler=ExternalTaskProcessor(tasks),
allow_create=True,
)
queue._async_agfs = backend
@@ -639,7 +639,7 @@ async def test_compile_api_client_session_protocol_retry_and_cancellation(
tracker = TaskTracker(store)
tasks = ExternalTaskService()
tasks.register(CompileService(service._config, tasks, SimpleNamespace()))
- queue.set_dequeue_handler(ExternalTaskProcessor(tasks, asyncio.get_running_loop()))
+ queue.set_dequeue_handler(ExternalTaskProcessor(tasks))
await tasks.restore_tasks(await manager.prepare_task_tracking(tracker))
# Recover processing behind pending work to prove recovery reserves the target first.
backend.pending.extend(backend.processing.values())
diff --git a/tests/service/test_resource_memory_link_service.py b/tests/service/test_resource_memory_link_service.py
index 8b6a204e8..2569371be 100644
--- a/tests/service/test_resource_memory_link_service.py
+++ b/tests/service/test_resource_memory_link_service.py
@@ -2,7 +2,9 @@
# SPDX-License-Identifier: AGPL-3.0
"""Tests for resource-memory linking service."""
+import asyncio
import re
+import threading
from types import SimpleNamespace
import pytest
@@ -254,39 +256,63 @@ async def test_on_resource_added_bridges_reason_through_fixed_session(request_co
@pytest.mark.asyncio
async def test_on_resource_added_reuses_same_reason_session(request_context):
- session_service = _FakeSessionService()
+ """Concurrent queue loops must serialize writes to the shared reason session."""
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ worker_waiting = threading.Event()
+
+ class BlockingSessionService(_FakeSessionService):
+ async def get(self, session_id, ctx, auto_create=False):
+ session = await super().get(session_id, ctx, auto_create=auto_create)
+ if len(self.got) == 1:
+ entered.set()
+ await release.wait()
+ return session
+
+ session_service = BlockingSessionService()
service = ResourceMemoryLinkService(
viking_fs=_FakeVikingFS({}),
session_service=session_service,
)
- first = await service.on_resource_added(
- ctx=request_context,
- resource_uri="viking://resources/images/ryoma.jpeg",
- reason="这是越前龙马的照片",
- source_name="ryoma.jpeg",
- )
- second = await service.on_resource_added(
- ctx=request_context,
- resource_uri="viking://resources/images/fuji.jpeg",
- reason="这是不二周助的照片",
- source_name="fuji.jpeg",
- )
+ async def add_reason(name):
+ return await service.on_resource_added(
+ ctx=request_context,
+ resource_uri=f"viking://resources/images/{name}.jpeg",
+ reason=f"这是{name}的照片",
+ source_name=f"{name}.jpeg",
+ )
- assert first["session_id"] == _RESOURCE_REASON_SESSION_ID
- assert second["session_id"] == _RESOURCE_REASON_SESSION_ID
- assert [call["session_id"] for call in session_service.got] == [
- _RESOURCE_REASON_SESSION_ID,
- _RESOURCE_REASON_SESSION_ID,
- ]
+ async def add_from_other_queue():
+ # Notify only after this coroutine has reached its first wait, so the
+ # first queue still holds the session while the other queue enters.
+ asyncio.get_running_loop().call_soon(worker_waiting.set)
+ return await add_reason("tezuka")
+
+ first = asyncio.create_task(add_reason("ryoma"))
+ await entered.wait()
+ second = asyncio.create_task(add_reason("fuji"))
+ await asyncio.sleep(0)
+ worker = asyncio.create_task(
+ asyncio.to_thread(lambda: asyncio.run(add_from_other_queue()))
+ )
+ try:
+ assert await asyncio.to_thread(worker_waiting.wait, 3)
+ assert len(session_service.got) == 1
+ finally:
+ release.set()
+ results = await asyncio.wait_for(asyncio.gather(first, second, worker), timeout=3)
+
+ assert all(result["status"] == "success" for result in results)
+ assert all(result["session_id"] == _RESOURCE_REASON_SESSION_ID for result in results)
assert [call["session_id"] for call in session_service.committed] == [
- _RESOURCE_REASON_SESSION_ID,
- _RESOURCE_REASON_SESSION_ID,
- ]
+ _RESOURCE_REASON_SESSION_ID
+ ] * 3
assert session_service.deleted == []
messages = [item["parts"][0].text for item in session_service.session.messages]
- assert "这是越前龙马的照片" in messages[0]
- assert "这是不二周助的照片" in messages[1]
+ assert len(messages) == 3
+ for name in ("ryoma", "fuji", "tezuka"):
+ assert any(f"这是{name}的照片" in message for message in messages)
@pytest.mark.asyncio
diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.py
index c9b496666..48dd337af 100644
--- a/tests/service/test_resource_service_watch.py
+++ b/tests/service/test_resource_service_watch.py
@@ -812,7 +812,6 @@ async def test_add_resource_processor_records_paused_watch_result(
)
processor = AddResourceProcessor(
service,
- asyncio.get_running_loop(),
QueueManager.ADD_RESOURCE,
SimpleNamespace(_async_agfs=SimpleNamespace(pathlock_release=AsyncMock())),
)
diff --git a/tests/service/test_task_queue_middleware.py b/tests/service/test_task_queue_middleware.py
index 4a36bb19e..9811b8e5c 100644
--- a/tests/service/test_task_queue_middleware.py
+++ b/tests/service/test_task_queue_middleware.py
@@ -4,6 +4,7 @@
import asyncio
import json
+import threading
from unittest.mock import AsyncMock
import pytest
@@ -425,9 +426,10 @@ async def test_cancel_cleanup_interruption_does_not_ack(tracked_queue):
async def test_cross_loop_cancellation_waits_for_handler_cleanup(tracked_queue):
queue, index, transport, _, cancelled = tracked_queue
- started = asyncio.Event()
- cleanup_started = asyncio.Event()
- cleanup_release = asyncio.Event()
+ started = threading.Event()
+ cleanup_started = threading.Event()
+ cleanup_release = threading.Event()
+ request_loop = asyncio.get_running_loop()
class Session:
async def exists(self):
@@ -437,12 +439,13 @@ async def test_cross_loop_cancellation_waits_for_handler_cleanup(tracked_queue):
pass
async def resume_queued_commit(self, msg):
+ assert asyncio.get_running_loop() is not request_loop
started.set()
try:
await asyncio.Event().wait()
finally:
cleanup_started.set()
- await cleanup_release.wait()
+ await asyncio.to_thread(cleanup_release.wait)
class Service:
def session(self, ctx, session_id, session_uri=None):
@@ -462,17 +465,17 @@ async def test_cross_loop_cancellation_waits_for_handler_cleanup(tracked_queue):
await queue.enqueue(msg.to_dict())
message = {"id": "m", "data": transport.write.await_args.args[1].decode()}
transport.write.reset_mock()
- queue.set_dequeue_handler(SessionCommitProcessor(Service(), asyncio.get_running_loop()))
+ queue.set_dequeue_handler(SessionCommitProcessor(Service()))
def consume():
return asyncio.run(queue.process_dequeued(message))
worker = asyncio.create_task(asyncio.to_thread(consume))
try:
- await asyncio.wait_for(started.wait(), timeout=3)
+ assert await asyncio.to_thread(started.wait, 3)
cancelled.add("task-1")
index.cancel_active("task-1")
- await asyncio.wait_for(cleanup_started.wait(), timeout=3)
+ assert await asyncio.to_thread(cleanup_started.wait, 3)
assert not worker.done()
transport.write.assert_not_awaited()
finally:
diff --git a/tests/storage/test_session_commit_processor_identity.py b/tests/storage/test_session_commit_processor_identity.py
index 14c1c2be3..5c184413b 100644
--- a/tests/storage/test_session_commit_processor_identity.py
+++ b/tests/storage/test_session_commit_processor_identity.py
@@ -8,7 +8,6 @@ worker binds the committing account/user (so tokens are not attributed to
"__unknown__") and resets the context afterwards.
"""
-import asyncio
import json
from openviking.observability.context import get_root_observability_context
@@ -80,7 +79,6 @@ async def test_process_binds_committing_identity_to_root_context():
captured: dict = {}
processor = SessionCommitProcessor(
_FakeSessionService(captured),
- asyncio.get_running_loop(),
)
ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
@@ -100,7 +98,6 @@ async def test_process_requeues_deferred_commit_and_resets_root_context(monkeypa
processor = SessionCommitProcessor(
_FakeSessionService({}, processed=False),
- asyncio.get_running_loop(),
)
monkeypatch.setattr(
"openviking.storage.queuefs.get_queue_manager",
@@ -125,7 +122,6 @@ async def test_cancelled_queued_commit_writes_terminal_marker_before_returning()
)
processor = SessionCommitProcessor(
_SingleSessionService(session),
- asyncio.get_running_loop(),
)
marker_uri = f"{msg.archive_uri}/.failed.json"
diff --git a/tests/test_task_tracker_concurrency.py b/tests/test_task_tracker_concurrency.py
index e95c4d2b2..342c4566d 100644
--- a/tests/test_task_tracker_concurrency.py
+++ b/tests/test_task_tracker_concurrency.py
@@ -479,38 +479,27 @@ 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()
+ same_key_entered = threading.Event()
+ other_key_entered = threading.Event()
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()),
- ]
+ async def work() -> None:
+ await asyncio.gather(wait_for_same_key(), use_other_key())
- await asyncio.wait_for(other_key_entered.wait(), timeout=1)
- assert not same_key_entered.is_set()
+ async with pool.acquire("task-1"):
+ worker = asyncio.create_task(asyncio.to_thread(lambda: asyncio.run(work())))
+ assert await asyncio.to_thread(other_key_entered.wait, 3)
+ assert not same_key_entered.is_set()
- release_first.set()
- await asyncio.wait_for(same_key_entered.wait(), timeout=1)
- await asyncio.gather(*tasks)
+ await asyncio.wait_for(worker, timeout=3)
+ assert same_key_entered.is_set()
@pytest.mark.asyncio
@@ -549,6 +538,17 @@ async def test_keyed_lock_registry_is_cleaned_after_use_and_cancellation():
await blocker_task
assert pool.entry_count == 0
+ # Cancellation can arrive after release hands over the slot, but before
+ # the waiting coroutine resumes. The slot must still become available.
+ async with pool.acquire("cancelled"):
+ granted_waiter = asyncio.create_task(waiter())
+ await asyncio.sleep(0)
+ granted_waiter.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await granted_waiter
+ await asyncio.wait_for(waiter(), timeout=1)
+ assert pool.entry_count == 0
+
@pytest.mark.asyncio
async def test_task_tracker_different_task_updates_do_not_block_each_other():
@@ -1015,12 +1015,12 @@ async def test_cancelled_create_waiting_for_task_lock_finishes_before_lock_relea
@pytest.mark.asyncio
-async def test_task_tracker_public_mutation_from_foreign_loop_runs_on_owner():
+async def test_task_tracker_public_mutation_stays_on_calling_loop():
from openviking.service.task_tracker import TaskStatus, TaskTracker
store = _ControllableTaskStore()
tracker = TaskTracker(store=store)
- owner_loop = asyncio.get_running_loop()
+ request_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)))
@@ -1035,18 +1035,17 @@ async def test_task_tracker_public_mutation_from_foreign_loop_runs_on_owner():
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)
+ assert store.operation_loops[0] is request_loop
+ assert all(loop is not request_loop for loop in store.operation_loops[1:])
@pytest.mark.asyncio
async def test_cancelling_foreign_mutation_cleans_task_lock_and_store_slot():
from openviking.service.task_tracker import TaskStatus, TaskTracker
- store = _ControllableTaskStore()
+ store = _ThreadBlockingUpdateTaskStore()
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:
@@ -1060,11 +1059,11 @@ async def test_cancelling_foreign_mutation_cleans_task_lock_and_store_slot():
asyncio.run(invoke())
foreign_call = asyncio.create_task(asyncio.to_thread(run_from_foreign_loop))
- await store.update_started[task.task_id].wait()
+ assert await asyncio.to_thread(store.thread_update_started.wait, 3)
cancel_foreign.set()
await asyncio.sleep(0.05)
returned_before_store_settled = foreign_call.done()
- store.update_release[task.task_id].set()
+ store.thread_update_release.set()
await foreign_call
assert not returned_before_store_settled