Skip to content

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

fix(tasks): 移除文件任务存储的统一 I/O 限流 (#6265)

bot-of-qin-ctxb727b816325b
diff --git a/openviking/service/task_store.py b/openviking/service/task_store.py
index ce9ccdfcb..77eb8654e 100644
--- a/openviking/service/task_store.py
+++ b/openviking/service/task_store.py
@@ -41,7 +41,6 @@ from openviking.service.task_domain import (
from openviking.service.task_events import append_task_event
from openviking.service.task_tracker_concurrency import (
KeyedAsyncLockPool,
- StoreIOLimiter,
run_to_completion,
)
@@ -407,7 +406,7 @@ class PersistentTaskStore(TaskWorkStore):
SYSTEM_DIRNAME = "_system"
TASKS_DIRNAME = "tasks"
- def __init__(self, agfs: Any, *, max_concurrent_io: int = 8) -> None:
+ def __init__(self, agfs: Any) -> None:
self._agfs = agfs if isinstance(agfs, AsyncAGFSClient) else AsyncAGFSClient(agfs)
self._ensured_task_dirs: set[tuple[str, str]] = set()
self._lock = threading.Lock()
@@ -417,7 +416,6 @@ class PersistentTaskStore(TaskWorkStore):
self._record_locks = KeyedAsyncLockPool()
self._cleanup_lock = KeyedAsyncLockPool()
self._cleanup_scan: Optional[AsyncIterator[Optional[Dict[str, Any]]]] = None
- self._io = StoreIOLimiter(max_concurrent_io)
@property
def work_recovery_mode(self) -> WorkRecoveryMode:
@@ -1613,16 +1611,13 @@ class PersistentTaskStore(TaskWorkStore):
)
async def _read(self, path: str) -> Any:
- return await self._io.run("read", lambda: run_to_completion(lambda: self._agfs.read(path)))
+ return await run_to_completion(lambda: self._agfs.read(path))
async def _ls(self, path: str) -> Any:
- return await self._io.run("ls", lambda: run_to_completion(lambda: self._agfs.ls(path)))
+ return await run_to_completion(lambda: self._agfs.ls(path))
async def _rm(self, path: str) -> None:
- await self._io.run(
- "rm",
- lambda: run_to_completion(lambda: self._agfs.rm(path, force=True, auto_pathlock=False)),
- )
+ await run_to_completion(lambda: self._agfs.rm(path, force=True, auto_pathlock=False))
async def _write_task(self, task: TaskRecord) -> None:
if not task.account_id or not task.user_id:
@@ -1631,21 +1626,11 @@ class PersistentTaskStore(TaskWorkStore):
payload = json.dumps(_task_to_payload(task), ensure_ascii=False).encode()
path = self._task_path(task.account_id, task.user_id, task.task_id)
try:
- await self._io.run(
- "write",
- lambda: run_to_completion(
- lambda: self._agfs.write(path, payload, auto_pathlock=False)
- ),
- )
+ await run_to_completion(lambda: self._agfs.write(path, payload, auto_pathlock=False))
except (AGFSNotFoundError, FileNotFoundError):
self._ensured_task_dirs.discard((task.account_id, task.user_id))
await self._ensure_task_dir(task.account_id, task.user_id)
- await self._io.run(
- "write",
- lambda: run_to_completion(
- lambda: self._agfs.write(path, payload, auto_pathlock=False)
- ),
- )
+ await run_to_completion(lambda: self._agfs.write(path, payload, auto_pathlock=False))
async def _ensure_task_dir(self, account_id: str, user_id: str) -> None:
key = (account_id, user_id)
@@ -1653,10 +1638,7 @@ class PersistentTaskStore(TaskWorkStore):
return
for path in self._task_dir_chain(account_id, user_id):
try:
- await self._io.run(
- "mkdir",
- lambda path=path: run_to_completion(lambda: self._agfs.mkdir(path)),
- )
+ await run_to_completion(lambda path=path: self._agfs.mkdir(path))
except AGFSAlreadyExistsError:
pass
except Exception as exc:
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index dab4495d2..508d9245f 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -283,8 +283,7 @@ class TaskTracker:
CLEANUP_INTERVAL = 300
CLEANUP_BATCH = 256
- def __init__(self, store: TaskWorkStore, *, max_concurrent_store_io: int = 8) -> None:
- del max_concurrent_store_io
+ def __init__(self, store: TaskWorkStore) -> None:
self._store = store
self._cleanup_task: Optional[asyncio.Task[Any]] = None
self._cancel_poll_task: Optional[asyncio.Task[Any]] = None
diff --git a/openviking/service/task_tracker_concurrency.py b/openviking/service/task_tracker_concurrency.py
index f0572d1b8..cc2864876 100644
--- a/openviking/service/task_tracker_concurrency.py
+++ b/openviking/service/task_tracker_concurrency.py
@@ -5,7 +5,6 @@
import asyncio
import threading
-import time
from concurrent.futures import Future as ConcurrentFuture
from concurrent.futures import InvalidStateError
from contextlib import asynccontextmanager
@@ -13,13 +12,10 @@ 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")
_ResultT = TypeVar("_ResultT")
-logger = get_logger(__name__)
-
async def run_to_completion(
factory: Callable[[], Awaitable[_ResultT]],
@@ -176,55 +172,6 @@ class OwnerLoopDispatcher:
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 = 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:
- with self._lock:
- return self._inflight
-
- @property
- def max_observed_inflight(self) -> int:
- with self._lock:
- return self._max_observed_inflight
-
- async def run(
- self,
- operation: str,
- factory: Callable[[], Awaitable[_ResultT]],
- ) -> _ResultT:
- started_at = time.monotonic()
- async with self._semaphore:
- with self._lock:
- self._inflight += 1
- self._max_observed_inflight = max(
- self._max_observed_inflight,
- self._inflight,
- )
- try:
- return await factory()
- finally:
- with self._lock:
- 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: AsyncSemaphore
diff --git a/tests/server/test_compile_studio.py b/tests/server/test_compile_studio.py
index c7423c0ec..0b5891d07 100644
--- a/tests/server/test_compile_studio.py
+++ b/tests/server/test_compile_studio.py
@@ -245,7 +245,7 @@ async def test_cursor_prunes_cold_expired_records_without_loading_cache():
payload["updated_at"] = time.time() - days * 86400
agfs.files[path] = json.dumps(payload).encode()
store = PersistentTaskStore(agfs)
- tracker = TaskTracker(store, max_concurrent_store_io=1)
+ tracker = TaskTracker(store)
await tracker.delete_expired()
page = await asyncio.wait_for(
tracker.list_tasks(
@@ -270,7 +270,7 @@ async def test_cursor_prunes_cold_expired_records_without_loading_cache():
async def test_cursor_cleanup_rechecks_task_updated_after_scan():
agfs = _FakeAgfs()
store = PersistentTaskStore(agfs)
- tracker = TaskTracker(store, max_concurrent_store_io=1)
+ tracker = TaskTracker(store)
owner = {"account_id": "acme", "user_id": "alice"}
task = await tracker.create("compile", task_id="updated-after-scan", **owner)
path = f"/local/acme/_system/tasks/alice/{task.task_id}.json"
@@ -279,7 +279,7 @@ async def test_cursor_cleanup_rechecks_task_updated_after_scan():
payload["updated_at"] = time.time() - 2 * 86400
agfs.files[path] = json.dumps(payload).encode()
store = PersistentTaskStore(agfs)
- tracker = TaskTracker(store, max_concurrent_store_io=1)
+ tracker = TaskTracker(store)
record_lock = ("acme", "alice", task.task_id)
async with store._record_locks.acquire(record_lock):
cleanup = asyncio.create_task(tracker.delete_expired())
diff --git a/tests/test_task_tracker_concurrency.py b/tests/test_task_tracker_concurrency.py
index 7292d3efd..941f91b8e 100644
--- a/tests/test_task_tracker_concurrency.py
+++ b/tests/test_task_tracker_concurrency.py
@@ -158,43 +158,6 @@ def test_owner_loop_dispatcher_concurrent_first_calls_share_winning_loop():
assert results[0] == results[1]
-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)
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize("cancel", [False, True])
async def test_run_to_completion_releases_request_and_preserves_cancellation(cancel):