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
feat(tasks): add MySQL task work store (#6258)
runyunzhouc01bb34d8e37
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 37997fa18..1cade6e0f 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1285,6 +1285,7 @@ Storage configuration for context data, including file storage (RAGFS) and vecto| `skip_process_lock` | bool | Skip the exclusive `.openviking.lock` file lock on `storage.workspace` for embedded vector backends (`local`, `cuvs`). Other backends do not acquire this lock. Skipping it does not make embedded vector storage safe for multiple processes. | `false` || `agfs` | object | RAGFS (Rust-based AGFS) configuration | {} || `vectordb` | object | Vector database storage configuration | {} |+| `task_store` | object | Durable Task/Work backend configuration | `{"provider":"file"}` |```json@@ -1302,6 +1303,41 @@ Storage configuration for context data, including file storage (RAGFS) and vecto}```+#### task_store++Task records use the local FileStore by default. To share Task/Work state across+OpenViking processes, provision `openviking/service/sql/task_store_init.sql` in+MySQL and select the relational backend:++```json+{+ "storage": {+ "task_store": {+ "provider": "mysql",+ "params": {+ "user": "openviking",+ "password": "change-me",+ "database": "openviking",+ "host": "127.0.0.1",+ "port": 3306,+ "table": "ov_tasks"+ }+ }+ }+}+```++`params.table` is the table prefix. It must start with an ASCII letter, contain+only ASCII letters, digits, or underscores, and be at most 38 characters so+derived table, index, and constraint names fit MySQL's 64-character limit.+Replace `ov_tasks` consistently in the provisioning SQL when using a custom prefix.++The MySQL backend requires the `openviking[mysql]` extra. Its mutations,+Task finalization, and execution-event updates commit in one database+transaction. `task_id` is globally unique; `account_id` and `user_id` scope+authorization and queries. Do not use the FileStore tables and MySQL tables as+active writers for the same deployment.+#### agfs (RAGFS)| Parameter | Type | Description | Default |diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex a6244251d..5400795bb 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1275,6 +1275,7 @@ Glob 引擎配置,用于路径模式匹配。这些设置为服务端配置,| `skip_process_lock` | bool | 是否跳过本地向量后端(`local`、`cuvs`)对 `storage.workspace` 的 `.openviking.lock` 独占文件锁。其他后端不会获取此锁。跳过检查不代表本地向量存储支持多进程共享。 | `false` || `agfs` | object | RAGFS(Rust 实现的 AGFS)配置 | {} || `vectordb` | object | 向量库存储配置 | {} |+| `task_store` | object | 持久化 Task/Work 后端配置 | `{"provider":"file"}` |```json@@ -1292,6 +1293,39 @@ Glob 引擎配置,用于路径模式匹配。这些设置为服务端配置,}```+#### task_store++Task 记录默认使用本地 FileStore。需要多个 OpenViking 进程共享+Task/Work 状态时,先在 MySQL 中执行+`openviking/service/sql/task_store_init.sql`,再选择关系型后端:++```json+{+ "storage": {+ "task_store": {+ "provider": "mysql",+ "params": {+ "user": "openviking",+ "password": "change-me",+ "database": "openviking",+ "host": "127.0.0.1",+ "port": 3306,+ "table": "ov_tasks"+ }+ }+ }+}+```++`params.table` 是表前缀,必须以 ASCII 字母开头,只能包含 ASCII 字母、数字和+下划线,最多 38 个字符,确保派生的表名、索引名和约束名不超过 MySQL 的 64 字符上限。+使用自定义前缀时,需要在建表 SQL 中统一替换 `ov_tasks`。++MySQL 后端需要安装 `openviking[mysql]` extra。Task mutation、Task+最终化和 execution event 更新在同一个数据库事务中提交。`task_id`+是全局唯一身份;`account_id` 和 `user_id` 用于鉴权和查询范围。同一部署+不要同时让 FileStore 和 MySQL 表作为写入端。+#### agfs (RAGFS)| 参数 | 类型 | 说明 | 默认值 |diff --git a/openviking/server/account_stores/mysql.py b/openviking/server/account_stores/mysql.pyindex d3507e617..142ba68ad 100644--- a/openviking/server/account_stores/mysql.py+++ b/openviking/server/account_stores/mysql.py@@ -43,6 +43,13 @@ from openviking.server.account_stores.mysql_schema import (User,)from openviking.server.identity import Role+from openviking.storage.mysql_runtime import (+ MySQLRuntime,+ get_shared_mysql_runtime,+ mysql_runtime_store,+ wait_mysql_cleanup,+)+from openviking.storage.mysql_session import MySQLAsyncSessionfrom openviking_cli.exceptions import (AlreadyExistsError,FailedPreconditionError,@@ -122,6 +129,7 @@ def _deletion(record) -> DeletionRecord | None:)+@mysql_runtime_storeclass MySQLAccountStore(AccountStore):"""A manually provisioned relational account store scoped by service name."""@@ -130,6 +138,7 @@ class MySQLAccountStore(AccountStore):*,service_name: str,params: dict[str, object] | None = None,+ runtime: MySQLRuntime | None = None,) -> None:values = dict(params or {})try:@@ -148,6 +157,8 @@ class MySQLAccountStore(AccountStore):)self._url, engine_options = self._connection_options(values)self._engine_options = engine_options+ self._mysql_runtime = runtime or get_shared_mysql_runtime()+ self._mysql_lease = Falseself._engine: AsyncEngine | None = Noneself._sessions: async_sessionmaker[AsyncSession] | None = None@@ -297,16 +308,29 @@ class MySQLAccountStore(AccountStore):async def load(self) -> None:if self._engine is not None:return+ await self._mysql_runtime.acquire()+ self._mysql_lease = True++ async def cleanup_failed_load(engine: AsyncEngine | None = None) -> None:+ if engine is not None:+ await engine.dispose()+ if self._mysql_lease:+ self._mysql_lease = False+ await self._mysql_runtime.release()+try:engine = create_async_engine(self._url, **self._engine_options)- sessions = async_sessionmaker(engine, expire_on_commit=False)+ sessions: async_sessionmaker[AsyncSession] = async_sessionmaker(+ engine, class_=MySQLAsyncSession, expire_on_commit=False+ )async with sessions() as session:for model in (Account, User, Group, GroupMember, Credential):await session.execute(select(*model.__table__.columns).limit(1))except ImportError:+ await wait_mysql_cleanup(cleanup_failed_load())raise RuntimeError("MySQL account storage requires openviking[mysql]") from Noneexcept DBAPIError as exc:- await engine.dispose()+ await wait_mysql_cleanup(cleanup_failed_load(engine if "engine" in locals() else None))original_args = getattr(exc.orig, "args", ())error_code = original_args[0] if original_args else Nonemessage = str(exc).lower()@@ -320,17 +344,22 @@ class MySQLAccountStore(AccountStore):) from excraiseexcept BaseException:- if "engine" in locals():- await engine.dispose()+ await wait_mysql_cleanup(cleanup_failed_load(engine if "engine" in locals() else None))raiseself._engine = engineself._sessions = sessionsasync def close(self) -> None:- if self._engine is not None:- await self._engine.dispose()- self._engine = None- self._sessions = None+ async def cleanup() -> None:+ if self._engine is not None:+ await self._engine.dispose()+ self._engine = None+ self._sessions = None+ if self._mysql_lease:+ self._mysql_lease = False+ await self._mysql_runtime.release()++ await wait_mysql_cleanup(cleanup())@propertydef _session_factory(self) -> async_sessionmaker[AsyncSession]:diff --git a/openviking/server/app.py b/openviking/server/app.pyindex f74e3078f..fd33a4ff6 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -415,12 +415,6 @@ def create_app(uninstall_executor_monitor()task_tracker.stop_cleanup_loop()- auth_plugin_state = getattr(app.state, "auth_plugin", None)- if auth_plugin_state is not None:- try:- await auth_plugin_state.shutdown()- except Exception as e: # noqa: BLE001- logger.warning("Auth plugin shutdown failed: %s", e)if oauth_gc_task is not None:oauth_gc_task.cancel()try:@@ -433,14 +427,24 @@ def create_app(await oauth_store_state.close()except Exception as e: # noqa: BLE001logger.warning("OAuth store close failed: %s", e)+ service_closed = not owns_serviceif owns_service and service:try:await service.close()+ service_closed = Truelogger.info("OpenVikingService closed")except asyncio.CancelledError as e:logger.warning(f"OpenVikingService close cancelled during shutdown: {e}")except Exception as e:logger.warning(f"OpenVikingService close failed during shutdown: {e}")+ # Draining workers still check identity/deletion state through the+ # auth plugin's account store. Retain it if service shutdown failed.+ auth_plugin_state = getattr(app.state, "auth_plugin", None)+ if service_closed and auth_plugin_state is not None:+ try:+ await auth_plugin_state.shutdown()+ except Exception as e: # noqa: BLE001+ logger.warning("Auth plugin shutdown failed: %s", e)if usage_reporter is not usage_reporter_unset and usage_reporter is not None:await usage_reporter.close()diff --git a/openviking/server/routers/tasks.py b/openviking/server/routers/tasks.pyindex e941f0f3d..3016ac9e1 100644--- a/openviking/server/routers/tasks.py+++ b/openviking/server/routers/tasks.py@@ -33,18 +33,21 @@ async def get_task():"""Get the status of a single background task."""tracker = get_task_tracker()+ get_task_record = tracker.get_with_events if include_events else tracker.getif _ctx.role == Role.ROOT:- task = await tracker.get(task_id)+ task = await get_task_record(task_id)if task is None:- task = await tracker.get(task_id, account_id=_ctx.account_id, user_id=_ctx.user.user_id)+ task = await get_task_record(+ task_id, account_id=_ctx.account_id, user_id=_ctx.user.user_id+ )if task is None:- task = await tracker.get(+ task = await get_task_record(task_id,account_id=SYSTEM_TASK_ACCOUNT_ID,user_id=SYSTEM_TASK_USER_ID,)else:- task = await tracker.get(+ task = await get_task_record(task_id,account_id=_ctx.account_id,user_id=_ctx.user.user_id,diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 08c8698bc..c8bcc855b 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -444,6 +444,7 @@ class OpenVikingService:returnself._ensure_data_dir_lock_acquired()+ await get_task_tracker().load()if self._vikingdb_manager is None:self._init_storage(@@ -658,7 +659,12 @@ class OpenVikingService:# Register durable cleanup work before restoring tracked tasks;# the deletion service binds consumers once auth is ready.self._queue_manager.get_queue(self._queue_manager.DATA_CLEANUP, allow_create=True)- restored_tasks = await self._queue_manager.prepare_task_tracking(get_task_tracker())+ tracker = get_task_tracker()+ await self._queue_manager.prepare_task_tracking(tracker)+ # Target reservations need recovery even when Work is already durable.+ restored_tasks = await self._queue_manager.get_queued_tasks(+ tracker, self._queue_manager.EXTERNAL_TASK+ )await self._external_task_service.restore_tasks(restored_tasks)if self._config.enable_watch_scheduler:@@ -765,6 +771,10 @@ class OpenVikingService:self._queue_manager = Nonelogger.info("Queue manager stopped")+ # Queue workers and scheduled producers persist their final Task/Work+ # transitions while stopping, so keep their store open until they drain.+ await get_task_tracker().close()+close_vlm_resolver = getattr(vlm_resolver, "close", None)if callable(close_vlm_resolver):result = close_vlm_resolver()diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.pyindex 671ac36ac..ef56e2375 100644--- a/openviking/service/reindex_executor.py+++ b/openviking/service/reindex_executor.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport asyncioimport time+from copy import deepcopyfrom dataclasses import dataclass, field, replacefrom typing import Any, Iterable, Optional@@ -26,7 +27,7 @@ from openviking.core.namespace import ()from openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContext-from openviking.service.task_tracker import get_task_tracker, run_tracked_operation+from openviking.service.task_tracker import TaskStatus, get_task_trackerfrom openviking.service.task_work_index import bind_task_context, get_task_contextfrom openviking.session.memory.utils.memory_file_utils import MemoryFileUtilsfrom openviking.storage.abstract_overview import body_for_preview, embedding_text_for_body@@ -210,50 +211,13 @@ class ReindexExecutor:raise InvalidArgumentError(f"recursive=false is not supported for namespace reindex target {uri}")- ingest_options = self._resolve_ingest_options(+ self._resolve_ingest_options(mode=mode,tags=tags,tag_mode=tag_mode,)tracker = get_task_tracker()- if wait:- task = await tracker.create_if_no_running(- REINDEX_TASK_TYPE,- uri,- account_id=ctx.account_id,- user_id=ctx.user.user_id,- )- if task is None:- raise OpenVikingError(- f"URI {uri} already has a reindex in progress",- code="CONFLICT",- details={"uri": uri},- )-- async def execute_run() -> dict[str, Any]:- return await self._run(- uri=uri,- object_type=object_type,- mode=mode,- force=force,- recursive=recursive,- ingest_options=ingest_options,- ctx=ctx,- )-- result, _task_id = await run_tracked_operation(- REINDEX_TASK_TYPE,- account_id=ctx.account_id,- user_id=ctx.user.user_id,- operation=execute_run,- wait=True,- resource_id=uri,- existing_task=task,- accept_failed_result=self._accept_partial_result,- )- return result-task = await tracker.create_if_no_running(REINDEX_TASK_TYPE,uri,@@ -303,7 +267,7 @@ class ReindexExecutor:lock_handoff=handoff,)queue_manager = get_queue_manager()- with bind_task_context(task.task_id, task.account_id, task.user_id):+ with bind_task_context(task.task_id, ctx.account_id, ctx.user.user_id):await queue_manager.enqueue(queue_manager.REINDEX, msg.to_dict())enqueued = Trueawait service.viking_fs._async_agfs.pathlock_handoff(lease)@@ -322,6 +286,27 @@ class ReindexExecutor:user_id=ctx.user.user_id,)raise+ if wait:+ terminal = await tracker.wait(+ task.task_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ result = deepcopy(terminal.result or {})+ if terminal.status == TaskStatus.FAILED and not self._accept_partial_result(result):+ raise OpenVikingError(+ terminal.error or "Task processing failed",+ code=result.get("code") or "PROCESSING_ERROR",+ details={"task_id": task.task_id, **result.get("details", {})},+ )+ if terminal.status == TaskStatus.CANCELLED:+ raise OpenVikingError(+ "Task processing was cancelled",+ code="PROCESSING_ERROR",+ details={"task_id": task.task_id, "status": "cancelled"},+ )+ result.pop("task_id", None)+ return resultreturn {"task_id": task.task_id,"status": "accepted",diff --git a/openviking/service/sql/task_store_init.sql b/openviking/service/sql/task_store_init.sqlnew file mode 100644index 000000000..0bcaf4e09--- /dev/null+++ b/openviking/service/sql/task_store_init.sql@@ -0,0 +1,76 @@+-- OpenViking MySQL Task/Work store schema.+-- Provision this schema before selecting storage.task_store.provider=mysql.+-- For a custom table prefix, replace ov_tasks consistently in all tables,+-- indexes, constraints, and the foreign-key target.+-- Use at most 38 ASCII letters/digits/underscores, starting with a letter,+-- so all derived identifiers remain within MySQL's 64-character limit.++CREATE TABLE `ov_tasks` (+ task_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ task_type VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ status VARCHAR(16) COLLATE ascii_bin NOT NULL,+ created_at DOUBLE NOT NULL,+ updated_at DOUBLE NOT NULL,+ resource_id TEXT COLLATE utf8mb4_bin NULL,+ account_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ user_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ meta JSON NULL,+ stage VARCHAR(255) NULL,+ result JSON NULL,+ error TEXT NULL,+ auth JSON NULL,+ processing_seconds DOUBLE NULL,+ reject_if_active BOOLEAN NOT NULL DEFAULT 0,+ is_internal BOOLEAN NOT NULL DEFAULT 0,+ active_business_key VARBINARY(32) NULL,+ PRIMARY KEY (task_id),+ UNIQUE KEY uq_ov_tasks_active_business_key (active_business_key),+ KEY ix_ov_tasks_owner_created (account_id, user_id, created_at, task_id),+ KEY ix_ov_tasks_account_created (account_id, created_at, task_id),+ KEY ix_ov_tasks_created (created_at, task_id),+ KEY ix_ov_tasks_owner_status (account_id, user_id, status),+ KEY ix_ov_tasks_owner_internal_created+ (account_id, user_id, is_internal, created_at, task_id),+ KEY ix_ov_tasks_expiry (status, updated_at, task_id)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;++CREATE TABLE `ov_tasks_works` (+ task_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ work_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ account_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ user_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ queue_name VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ state VARCHAR(16) COLLATE ascii_bin NOT NULL,+ requeue_count INT NOT NULL DEFAULT 0,+ error TEXT NULL,+ errors JSON NULL,+ context_count INT NOT NULL DEFAULT 0,+ enqueued_at DOUBLE NOT NULL,+ started_at DOUBLE NULL,+ finished_at DOUBLE NULL,+ updated_at DOUBLE NOT NULL,+ PRIMARY KEY (task_id, work_id),+ CONSTRAINT fk_ov_tasks_works_task+ FOREIGN KEY (task_id) REFERENCES `ov_tasks` (task_id)+ ON DELETE CASCADE,+ KEY ix_ov_tasks_works_state (task_id, state),+ KEY ix_ov_tasks_works_queue (task_id, queue_name, state),+ KEY ix_ov_tasks_works_owner (account_id, user_id, task_id)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;++CREATE TABLE `ov_tasks_execution_events` (+ task_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ seq INT NOT NULL,+ recorded_at VARCHAR(64) COLLATE ascii_bin NOT NULL,+ kind VARCHAR(64) COLLATE utf8mb4_bin NOT NULL,+ status VARCHAR(16) COLLATE ascii_bin NOT NULL,+ stage VARCHAR(128) NULL,+ operation TEXT NULL,+ error TEXT NULL,+ dropped_count INT NOT NULL DEFAULT 0,+ started_mid_task BOOLEAN NOT NULL DEFAULT 0,+ PRIMARY KEY (task_id, seq),+ CONSTRAINT fk_ov_tasks_execution_events_task+ FOREIGN KEY (task_id) REFERENCES `ov_tasks` (task_id)+ ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;diff --git a/openviking/service/task_domain.py b/openviking/service/task_domain.pyindex 6aa5e3d0f..ffadf1d6e 100644--- a/openviking/service/task_domain.py+++ b/openviking/service/task_domain.py@@ -13,6 +13,8 @@ from datetime import datetime, timezonefrom enum import Enumfrom typing import Any, Dict, Iterable, Optional+from openviking.service.task_events import append_task_event+class TaskStatus(str, Enum):PENDING = "pending"@@ -194,6 +196,8 @@ class WorkRecord:started_at: Optional[float] = Nonefinished_at: Optional[float] = Noneupdated_at: float = field(default_factory=time.time)+ account_id: Optional[str] = None+ user_id: Optional[str] = Nonedef is_open(self) -> bool:return self.state not in TERMINAL_WORK_STATES@@ -254,3 +258,92 @@ def first_work_error(works: Iterable[WorkRecord]) -> Optional[str]:(work.error for work in works if work.state == WorkState.FAILED and work.error),None,)+++def append_task_events(task: TaskRecord, previous: Optional[TaskRecord]) -> None:+ """Append lifecycle events shared by all TaskStore implementations."""+ recorded_at = datetime.now(timezone.utc).isoformat()+ if previous is None:+ kinds = ["created"]+ else:+ kinds = []+ if task.error is not None and previous.error is None:+ kinds.append("error_recorded")+ if task.status == TaskStatus.CANCELLED and previous.status != TaskStatus.CANCELLING:+ task.execution_events = append_task_event(+ task.execution_events,+ kind="status_changed",+ status=TaskStatus.CANCELLING.value,+ stage=sanitize_error(previous.stage) if previous.stage else None,+ recorded_at=recorded_at,+ )+ if task.status != previous.status:+ kinds.append("status_changed")+ if task.stage != previous.stage and task.status not in TERMINAL_TASK_STATUSES:+ kinds.append("stage_changed")++ stage = previous.stage if previous and task.status in TERMINAL_TASK_STATUSES else task.stage+ for kind in kinds:+ task.execution_events = append_task_event(+ task.execution_events,+ kind=kind,+ status=task.status.value,+ stage=sanitize_error(stage) if stage else None,+ error=sanitize_error(task.error)+ if kind == "error_recorded" and task.error+ else None,+ recorded_at=recorded_at,+ )+++def queue_result(summary: Optional[QueueWorkSummary]) -> Dict[str, Any]:+ """Project queue aggregates into the public Task result shape."""+ summary = summary or QueueWorkSummary()+ return {+ "processed": summary.processed,+ "requeue_count": summary.requeue_count,+ "error_count": summary.error_count,+ "errors": [{"message": error} for error in summary.errors[:MAX_QUEUE_ERROR_DETAILS]],+ }+++def finalize_task(task: TaskRecord, works: Iterable[WorkRecord]) -> bool:+ """Apply the shared Task terminal-state and result projection rules."""+ works = list(works)+ if task.status not in ACTIVE_TASK_STATUSES or any(work.is_open() for work in works):+ return False+ if task.status == TaskStatus.CANCELLING:+ task.status = TaskStatus.CANCELLED+ else:+ work_error = first_work_error(works)+ if work_error and task.error is None:+ task.error = sanitize_error(work_error)+ if task.error is not None:+ task.status = TaskStatus.FAILED+ elif task.result is not None:+ task.status = TaskStatus.COMPLETED+ else:+ task.error = "Task operation interrupted before its result was persisted"+ task.status = TaskStatus.FAILED+ if isinstance(task.result, dict):+ summary = summarize_works(works)+ projected = {+ queue_name: queue_result(summary.queues.get(queue_name))+ for queue_name in ("Semantic", "Embedding")+ }+ if any(work.queue_name in projected for work in works):+ task.result["queue_status"] = projected+ for queue_name, field_name in (+ ("Semantic", "semantic_status"),+ ("Embedding", "vector_status"),+ ):+ if task.result.get(field_name) == "queued":+ task.result[field_name] = (+ "failed"+ if projected.get(queue_name, {}).get("error_count", 0)+ else "complete"+ )+ task.stage = task.status.value+ task.auth = {}+ task.processing_seconds = processing_seconds(works)+ return Truediff --git a/openviking/service/task_store.py b/openviking/service/task_store.pyindex 77eb8654e..6b19fd387 100644--- a/openviking/service/task_store.py+++ b/openviking/service/task_store.py@@ -21,11 +21,9 @@ from openviking.pyagfs import AsyncAGFSClientfrom openviking.pyagfs.exceptions import AGFSAlreadyExistsError, AGFSNotFoundErrorfrom openviking.service.task_domain import (ACTIVE_TASK_STATUSES,- MAX_QUEUE_ERROR_DETAILS,TERMINAL_TASK_STATUSES,DeletedTask,DeleteExpiredResult,- QueueWorkSummary,TaskRecord,TaskRetentionPolicy,TaskStatus,@@ -33,7 +31,8 @@ from openviking.service.task_domain import (WorkRecoveryMode,WorkState,WorkSummary,- first_work_error,+ append_task_events,+ finalize_task,processing_seconds,sanitize_error,summarize_works,@@ -160,6 +159,14 @@ class TaskWorkStore(Protocol):user_id: Optional[str] = None,) -> Optional[TaskRecord]: ...+ async def get_task_with_events(+ self,+ task_id: str,+ *,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> Optional[TaskRecord]: ...+async def list(self,account_id: Optional[str] = None,@@ -441,7 +448,7 @@ class PersistentTaskStore(TaskWorkStore):if existing is not None:return self._copy_task(existing, self._work_sets.get(owner))stored = deepcopy(task)- self._append_events(stored, None)+ append_task_events(stored, None)await self._write_task(stored)with self._lock:self._task_cache[owner] = stored@@ -454,6 +461,24 @@ class PersistentTaskStore(TaskWorkStore):*,account_id: Optional[str] = None,user_id: Optional[str] = None,+ ) -> Optional[TaskRecord]:+ task = await self._load_task(task_id, account_id, user_id)+ if task is None:+ return None+ with self._lock:+ owner = self._find_cached_owner(task_id, account_id, user_id)+ if owner is None:+ return None+ task = self._copy_task(self._task_cache[owner], self._work_sets.get(owner))+ task.execution_events = None+ return task++ async def get_task_with_events(+ self,+ task_id: str,+ *,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,) -> Optional[TaskRecord]:task = await self._load_task(task_id, account_id, user_id)if task is None:@@ -588,7 +613,7 @@ class PersistentTaskStore(TaskWorkStore):task.auth = ({"enqueue_complete_work_ids": deepcopy(enqueue_markers)} if enqueue_markers else {})- self._try_finalize(task, work_set)+ finalize_task(task, work_set.works.values())return StoreOperationResult.applied()return await self._mutate_task(task_id, account_id, user_id, mutate)@@ -619,7 +644,7 @@ class PersistentTaskStore(TaskWorkStore):f"Task is already {task.status.value}",)task.status = TaskStatus.CANCELLING- self._try_finalize(task, work_set)+ finalize_task(task, work_set.works.values())return StoreOperationResult.applied()return await self._mutate_task(task_id, account_id, user_id, mutate)@@ -1038,13 +1063,15 @@ class PersistentTaskStore(TaskWorkStore):except (ValueError, TypeError, KeyError):continuewith self._lock:- tasks = [- self._copy_task(task, self._work_sets.get(owner))- for owner, task in self._task_cache.items()- for account, user, _ in (owner,)- if (account_id is None or account == account_id)- and (user_id is None or user == user_id)- ]+ tasks = []+ for owner, task in self._task_cache.items():+ account, user, _ = owner+ if (account_id is None or account == account_id) and (+ user_id is None or user == user_id+ ):+ copied = self._copy_task(task, self._work_sets.get(owner))+ copied.execution_events = None+ tasks.append(copied)tasks = [taskfor task in tasks@@ -1097,6 +1124,7 @@ class PersistentTaskStore(TaskWorkStore):cached = self._task_cache.get(owner)if cached is not None:record = self._copy_task(cached, self._work_sets.get(owner))+ record.execution_events = Nonekey = (record.created_at, record.task_id)if before is not None and key >= before:continue@@ -1371,7 +1399,7 @@ class PersistentTaskStore(TaskWorkStore):if not mutation.is_applied:return mutationcandidate.updated_at = TaskRecord.next_updated_at(candidate.updated_at)- self._append_events(candidate, previous)+ append_task_events(candidate, previous)snapshot = deepcopy(candidate)await self._write_task_and_publish(snapshot, owner, candidate)return mutation@@ -1425,7 +1453,7 @@ class PersistentTaskStore(TaskWorkStore):else:works[work_id] = mutation.workcandidate_work_set = _WorkSet(works, open_count)- finalized = self._try_finalize(candidate_task, candidate_work_set)+ finalized = finalize_task(candidate_task, candidate_work_set.works.values())if finalized:assert candidate_task is not None@@ -1433,7 +1461,7 @@ class PersistentTaskStore(TaskWorkStore):candidate_task.updated_at = TaskRecord.next_updated_at(candidate_task.updated_at)- self._append_events(candidate_task, previous)+ append_task_events(candidate_task, previous)snapshot = deepcopy(candidate_task)else:if mutation.changed:@@ -1475,51 +1503,6 @@ class PersistentTaskStore(TaskWorkStore):finally:del write_task, cancellation- def _try_finalize(self, task: TaskRecord, work_set: _WorkSet) -> bool:- if task.status not in ACTIVE_TASK_STATUSES or work_set.open_count:- return False- if task.status == TaskStatus.CANCELLING:- task.status = TaskStatus.CANCELLED- else:- work_error = first_work_error(work_set.works.values())- if work_error and task.error is None:- task.error = sanitize_error(work_error)- if task.error is not None:- task.status = TaskStatus.FAILED- elif task.result is not None:- task.status = TaskStatus.COMPLETED- else:- task.error = "Task operation interrupted before its result was persisted"- task.status = TaskStatus.FAILED- if isinstance(task.result, dict):- # QueueFS reconstructs only unacknowledged Work after restart. For this- # file backend, terminal Work history and its errors may therefore be- # absent from the final projection until Work itself becomes durable.- summary = summarize_works(work_set.works.values())- projected = {- queue_name: _queue_result(summary.queues.get(queue_name))- for queue_name in ("Semantic", "Embedding")- }- has_projected_work = any(- work.queue_name in projected for work in work_set.works.values()- )- if has_projected_work:- task.result["queue_status"] = projected- for queue_name, field_name in (- ("Semantic", "semantic_status"),- ("Embedding", "vector_status"),- ):- if task.result.get(field_name) == "queued":- task.result[field_name] = (- "failed"- if projected.get(queue_name, {}).get("error_count", 0)- else "complete"- )- task.stage = task.status.value- task.auth = {}- task.processing_seconds = processing_seconds(work_set.works.values())- return True-def _copy_task(self, task: TaskRecord, work_set: Optional[_WorkSet]) -> TaskRecord:copied = deepcopy(task)if copied.status in ACTIVE_TASK_STATUSES and work_set is not None:@@ -1573,43 +1556,6 @@ class PersistentTaskStore(TaskWorkStore):self._task_cache.setdefault(owner, task)self._work_sets.setdefault(owner, _WorkSet({}))- @staticmethod- def _append_events(task: TaskRecord, previous: Optional[TaskRecord]) -> None:- from datetime import datetime, timezone-- recorded_at = datetime.now(timezone.utc).isoformat()- if previous is None:- kinds = ["created"]- else:- kinds = []- if task.error is not None and previous.error is None:- kinds.append("error_recorded")- if task.status == TaskStatus.CANCELLED and previous.status != TaskStatus.CANCELLING:- task.execution_events = append_task_event(- task.execution_events,- kind="status_changed",- status=TaskStatus.CANCELLING.value,- stage=sanitize_error(previous.stage) if previous.stage else None,- recorded_at=recorded_at,- )- if task.status != previous.status:- kinds.append("status_changed")- if task.stage != previous.stage and task.status not in TERMINAL_TASK_STATUSES:- kinds.append("stage_changed")-- stage = previous.stage if previous and task.status in TERMINAL_TASK_STATUSES else task.stage- for kind in kinds:- task.execution_events = append_task_event(- task.execution_events,- kind=kind,- status=task.status.value,- stage=sanitize_error(stage) if stage else None,- error=sanitize_error(task.error)- if kind == "error_recorded" and task.error- else None,- recorded_at=recorded_at,- )-async def _read(self, path: str) -> Any:return await run_to_completion(lambda: self._agfs.read(path))@@ -1761,16 +1707,6 @@ def _inactive_task_result(task: TaskRecord, message: str) -> StoreOperationResul)-def _queue_result(summary: Optional[QueueWorkSummary]) -> Dict[str, Any]:- summary = summary or QueueWorkSummary()- return {- "processed": summary.processed,- "requeue_count": summary.requeue_count,- "error_count": summary.error_count,- "errors": [{"message": error} for error in summary.errors[:MAX_QUEUE_ERROR_DETAILS]],- }--def _task_to_payload(task: TaskRecord) -> Dict[str, Any]:return {**deepcopy(task._extra_fields),diff --git a/openviking/service/task_store_mysql.py b/openviking/service/task_store_mysql.pynew file mode 100644index 000000000..7ecc3014a--- /dev/null+++ b/openviking/service/task_store_mysql.py@@ -0,0 +1,1860 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Relational MySQL implementation of :class:`TaskWorkStore`."""++from __future__ import annotations++import hashlib+import os+import ssl as ssl_module+import time+from contextlib import asynccontextmanager+from copy import deepcopy+from datetime import datetime, timezone+from typing import Any, AsyncGenerator, Collection, Dict, Iterable, Optional++from sqlalchemy import and_, delete, exists, or_, select, update+from sqlalchemy.engine import URL+from sqlalchemy.exc import DBAPIError, IntegrityError+from sqlalchemy.ext.asyncio import (+ AsyncEngine,+ AsyncSession,+ async_sessionmaker,+ create_async_engine,+)++from openviking.service.task_domain import (+ ACTIVE_TASK_STATUSES,+ TERMINAL_TASK_STATUSES,+ DeletedTask,+ DeleteExpiredResult,+ TaskRecord,+ TaskRetentionPolicy,+ TaskStatus,+ WorkRecord,+ WorkRecoveryMode,+ WorkState,+ WorkSummary,+ append_task_events,+ finalize_task,+ processing_seconds,+ sanitize_error,+ summarize_works,+)+from openviking.service.task_events import append_task_event+from openviking.service.task_store import (+ DeleteTasksResult,+ StoreOperationCode,+ StoreOperationResult,+ TaskAlreadyActive,+ TaskDeletionBlocker,+ TaskStatsSnapshot,+ TaskWorkStore,+ _deep_merge,+)+from openviking.service.task_store_mysql_schema import (+ TaskStoreModels,+ make_task_store_models,+ validate_table_prefix,+)+from openviking.storage.mysql_runtime import (+ MySQLRuntime,+ get_shared_mysql_runtime,+ mysql_runtime_store,+ wait_mysql_cleanup,+)+from openviking.storage.mysql_session import MySQLAsyncSession+++def _business_key(+ account_id: str, user_id: str, task_type: str, resource_id: Optional[str]+) -> bytes:+ """Hash the guarded business key into a fixed-width unique-index value."""+ required = (account_id, user_id, task_type)+ encoded = [len(value.encode()).to_bytes(2, "big") + value.encode() for value in required]+ if resource_id is None:+ encoded.append(b"\x00")+ else:+ value = resource_id.encode()+ encoded.append(b"\x01" + len(value).to_bytes(2, "big") + value)+ return hashlib.sha256(b"".join(encoded)).digest()+++def _json_copy(value: Any) -> Any:+ return deepcopy(value) if value is not None else None+++def _utc_iso() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _not_found_result() -> StoreOperationResult:+ return StoreOperationResult.rejected(StoreOperationCode.NOT_FOUND)+++def _inactive_result(status: str, message: str) -> StoreOperationResult:+ if status in {item.value for item in TERMINAL_TASK_STATUSES}:+ return StoreOperationResult.rejected(+ StoreOperationCode.ALREADY_TERMINAL,+ f"{message}: task is already {status}",+ )+ return StoreOperationResult.rejected(+ StoreOperationCode.INVALID_STATE,+ f"{message}: task is {status}",+ )+++@mysql_runtime_store+class MySQLTaskWorkStore(TaskWorkStore):+ """Durable Task/Work storage with transaction-owned state transitions."""++ def __init__(+ self,+ *,+ params: dict[str, object] | None = None,+ runtime: MySQLRuntime | None = None,+ ) -> None:+ values = dict(params or {})+ table_prefix = validate_table_prefix(values.pop("table", "ov_tasks"))+ self._models: TaskStoreModels = make_task_store_models(table_prefix)+ self._resource_id = os.environ.get("OV_RESOURCE_ID", "").strip()+ self._url, self._engine_options = self._connection_options(values)+ self._mysql_runtime = runtime or get_shared_mysql_runtime()+ self._mysql_lease = False+ self._engine: AsyncEngine | None = None+ self._sessions: async_sessionmaker[AsyncSession] | None = None++ @staticmethod+ def _connection_options(values: dict[str, object]) -> tuple[URL, dict[str, object]]:+ allowed = {+ "user",+ "password",+ "database",+ "host",+ "port",+ "maxsize",+ "connect_timeout",+ "ssl",+ "unix_socket",+ }+ unknown = values.keys() - allowed+ if unknown:+ raise ValueError(f"Unknown MySQL task store parameters: {', '.join(sorted(unknown))}")+ missing = [name for name in ("user", "password", "database") if name not in values]+ if missing:+ raise ValueError(f"MySQL task store requires: {', '.join(missing)}")++ connect_args: dict[str, object] = {+ "connect_timeout": values.get("connect_timeout", 10),+ }+ if socket := values.get("unix_socket"):+ connect_args["unix_socket"] = socket+ ssl = values.get("ssl")+ if isinstance(ssl, dict):+ unknown_ssl = ssl.keys() - {"ca", "cert", "key", "check_hostname"}+ if unknown_ssl:+ raise ValueError(f"Unknown MySQL TLS options: {sorted(unknown_ssl)}")+ context = ssl_module.create_default_context(cafile=ssl.get("ca"))+ context.check_hostname = bool(ssl.get("check_hostname", True))+ if ssl.get("cert"):+ context.load_cert_chain(ssl["cert"], ssl.get("key"))+ connect_args["ssl"] = context+ elif ssl is True:+ connect_args["ssl"] = ssl_module.create_default_context()+ elif ssl not in (None, False):+ raise ValueError("ssl must be a boolean or TLS options mapping")++ url = URL.create(+ "mysql+aiomysql",+ username=str(values["user"]),+ password=str(values["password"]),+ host=str(values.get("host", "127.0.0.1")),+ port=int(str(values.get("port", 3306))),+ database=str(values["database"]),+ query={"charset": "utf8mb4"},+ )+ return url, {+ "pool_size": int(values.get("maxsize", 10)),+ "max_overflow": 0,+ "pool_pre_ping": True,+ "pool_recycle": 3600,+ "connect_args": connect_args,+ "isolation_level": "READ COMMITTED",+ }++ @property+ def work_recovery_mode(self) -> WorkRecoveryMode:+ return WorkRecoveryMode.DURABLE_STORE++ async def load(self) -> None:+ """Connect and verify that the manually provisioned schema is usable."""+ if self._engine is not None:+ return+ await self._mysql_runtime.acquire()+ self._mysql_lease = True++ async def cleanup_failed_load(engine: AsyncEngine | None = None) -> None:+ if engine is not None:+ await engine.dispose()+ if self._mysql_lease:+ self._mysql_lease = False+ await self._mysql_runtime.release()++ try:+ engine = create_async_engine(self._url, **self._engine_options)+ sessions: async_sessionmaker[AsyncSession] = async_sessionmaker(+ engine, class_=MySQLAsyncSession, expire_on_commit=False+ )+ async with sessions() as session:+ for model in (self._models.Task, self._models.Work, self._models.Event):+ await session.execute(select(*model.__table__.columns).limit(1))+ except ImportError:+ await wait_mysql_cleanup(cleanup_failed_load())+ raise RuntimeError("MySQL task storage requires openviking[mysql]") from None+ except DBAPIError as exc:+ await wait_mysql_cleanup(cleanup_failed_load(engine if "engine" in locals() else None))+ message = str(exc).lower()+ if any(+ marker in message+ for marker in ("unknown column", "doesn't exist", "does not exist")+ ):+ raise RuntimeError(+ "MySQL task schema is missing or incompatible; provision the configured "+ "Task/Work tables before starting OpenViking"+ ) from exc+ raise+ except BaseException:+ await wait_mysql_cleanup(cleanup_failed_load(engine if "engine" in locals() else None))+ raise+ self._engine = engine+ self._sessions = sessions++ async def close(self) -> None:+ async def cleanup() -> None:+ if self._engine is not None:+ await self._engine.dispose()+ self._engine = None+ self._sessions = None+ if self._mysql_lease:+ self._mysql_lease = False+ await self._mysql_runtime.release()++ await wait_mysql_cleanup(cleanup())++ @property+ def _session_factory(self) -> async_sessionmaker[AsyncSession]:+ if self._sessions is None:+ raise RuntimeError("MySQLTaskWorkStore.load() must be called before use")+ return self._sessions++ @staticmethod+ def _require_owner(account_id: Optional[str], user_id: Optional[str]) -> tuple[str, str]:+ if not account_id or not user_id:+ raise ValueError("MySQLTaskWorkStore requires account_id and user_id")+ return account_id, user_id++ @staticmethod+ def _task_query(+ Task: Any,+ task_id: str,+ account_id: Optional[str],+ user_id: Optional[str],+ ):+ predicates = [Task.task_id == task_id]+ if account_id is not None:+ predicates.append(Task.account_id == account_id)+ if user_id is not None:+ predicates.append(Task.user_id == user_id)+ return predicates++ @staticmethod+ def _work_query(+ Work: Any,+ task_id: str,+ work_id: Optional[str],+ account_id: Optional[str],+ user_id: Optional[str],+ ):+ predicates = [Work.task_id == task_id]+ if work_id is not None:+ predicates.append(Work.work_id == work_id)+ if account_id is not None:+ predicates.append(Work.account_id == account_id)+ if user_id is not None:+ predicates.append(Work.user_id == user_id)+ return predicates++ @staticmethod+ def _task_from_row(+ row: Any,+ works: Iterable[WorkRecord] = (),+ execution_events: Optional[dict] = None,+ ) -> TaskRecord:+ task = TaskRecord(+ task_id=row.task_id,+ task_type=row.task_type,+ status=TaskStatus(row.status),+ created_at=float(row.created_at),+ updated_at=float(row.updated_at),+ resource_id=row.resource_id,+ account_id=row.account_id,+ user_id=row.user_id,+ meta=_json_copy(row.meta) or {},+ stage=row.stage,+ result=_json_copy(row.result),+ error=row.error,+ auth=_json_copy(row.auth) or {},+ execution_events=_json_copy(execution_events),+ processing_seconds=(+ processing_seconds(works)+ if row.status in {item.value for item in ACTIVE_TASK_STATUSES}+ else row.processing_seconds+ ),+ )+ return task++ @staticmethod+ def _work_from_row(row: Any) -> WorkRecord:+ return WorkRecord(+ work_id=row.work_id,+ task_id=row.task_id,+ queue_name=row.queue_name,+ account_id=row.account_id,+ user_id=row.user_id,+ state=WorkState(row.state),+ requeue_count=int(row.requeue_count),+ error=row.error,+ errors=list(row.errors or ()),+ context_count=int(row.context_count),+ enqueued_at=float(row.enqueued_at),+ started_at=float(row.started_at) if row.started_at is not None else None,+ finished_at=float(row.finished_at) if row.finished_at is not None else None,+ updated_at=float(row.updated_at),+ )++ async def _load_task(+ self,+ session: AsyncSession,+ task_id: str,+ *,+ account_id: Optional[str],+ user_id: Optional[str],+ lock: bool = False,+ ) -> Any:+ Task = self._models.Task+ statement = select(Task).where(*self._task_query(Task, task_id, account_id, user_id))+ if lock:+ statement = statement.with_for_update()+ return await session.scalar(statement)++ async def _lock_task(+ self, session: AsyncSession, task_id: str, *, account_id: str, user_id: str+ ) -> bool:+ """Serialize Work closure with registration and deletion, Task before Work."""+ Task = self._models.Task+ return (+ await session.scalar(+ select(Task.task_id)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ ) is not None++ async def _task_exists(+ self,+ session: AsyncSession,+ task_id: str,+ *,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> bool:+ Task = self._models.Task+ return bool(+ await session.scalar(+ select(exists().where(*self._task_query(Task, task_id, account_id, user_id)))+ )+ )++ async def _has_open_work(self, session: AsyncSession, task_id: str) -> bool:+ Work = self._models.Work+ return bool(+ await session.scalar(+ select(+ exists().where(+ Work.task_id == task_id,+ Work.state.not_in(+ [WorkState.DONE.value, WorkState.FAILED.value]+ ),+ )+ )+ )+ )++ async def _works(+ self,+ session: AsyncSession,+ task_id: str,+ work_ids: Optional[Collection[str]] = None,+ *,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> list[WorkRecord]:+ Work = self._models.Work+ statement = select(Work).where(+ *self._work_query(Work, task_id, None, account_id, user_id)+ )+ if work_ids is not None:+ ids = set(work_ids)+ if not ids:+ return []+ statement = statement.where(Work.work_id.in_(ids))+ rows = (await session.scalars(statement)).all()+ return [self._work_from_row(row) for row in rows]++ async def _event_history(self, session: AsyncSession, task_id: str) -> Optional[dict]:+ Event = self._models.Event+ rows = (+ await session.scalars(+ select(Event).where(Event.task_id == task_id).order_by(Event.seq)+ )+ ).all()+ if not rows:+ return None+ latest = rows[-1]+ return {+ "items": [+ {+ "seq": int(row.seq),+ "recorded_at": row.recorded_at,+ "kind": row.kind,+ "status": row.status,+ "stage": row.stage,+ "operation": row.operation,+ "error": row.error,+ }+ for row in rows+ ],+ "dropped_count": int(latest.dropped_count),+ "started_mid_task": bool(latest.started_mid_task),+ }++ async def _store_event_history(+ self,+ session: AsyncSession,+ task_id: str,+ history: Optional[dict],+ ) -> None:+ if history is None:+ return+ Event = self._models.Event+ items = history["items"]+ if not items:+ return+ seqs = [int(item["seq"]) for item in items]+ existing = set(+ await session.scalars(+ select(Event.seq).where(Event.task_id == task_id, Event.seq.in_(seqs))+ )+ )+ metadata = {+ "dropped_count": int(history["dropped_count"]),+ "started_mid_task": bool(history["started_mid_task"]),+ }+ await session.execute(+ update(Event).where(Event.task_id == task_id).values(**metadata)+ )+ for item in items:+ if int(item["seq"]) in existing:+ continue+ session.add(+ Event(+ task_id=task_id,+ seq=int(item["seq"]),+ recorded_at=item["recorded_at"],+ kind=item["kind"],+ status=item["status"],+ stage=item["stage"],+ operation=item["operation"],+ error=item["error"],+ **metadata,+ )+ )+ await session.execute(+ delete(Event).where(Event.task_id == task_id, Event.seq < min(seqs))+ )++ async def _lock_work(self, session: AsyncSession, task_id: str, work_id: str) -> Any:+ Work = self._models.Work+ return await session.scalar(+ select(Work).where(Work.task_id == task_id, Work.work_id == work_id).with_for_update()+ )++ @asynccontextmanager+ async def _transaction(self) -> AsyncGenerator[AsyncSession, None]:+ async with self._session_factory() as session:+ async with session.begin():+ yield session++ async def create(self, task: TaskRecord, *, reject_if_active: bool = False) -> TaskRecord:+ account_id, user_id = self._require_owner(task.account_id, task.user_id)+ Task = self._models.Task+ now = time.time()+ stored = deepcopy(task)+ if stored.created_at <= 0:+ stored.created_at = now+ if stored.updated_at <= 0:+ stored.updated_at = stored.created_at+ stored.account_id = account_id+ stored.user_id = user_id+ stored._extra_fields = {}+ append_task_events(stored, None)+ row = Task(+ task_id=stored.task_id,+ task_type=stored.task_type,+ status=stored.status.value,+ created_at=stored.created_at,+ updated_at=stored.updated_at,+ resource_id=stored.resource_id,+ account_id=account_id,+ user_id=user_id,+ meta=_json_copy(stored.meta),+ stage=stored.stage,+ result=_json_copy(stored.result),+ error=stored.error,+ auth=_json_copy(stored.auth),+ processing_seconds=stored.processing_seconds,+ reject_if_active=reject_if_active,+ is_internal=bool(stored.meta.get("internal")),+ active_business_key=(+ _business_key(account_id, user_id, stored.task_type, stored.resource_id)+ if reject_if_active and stored.status in ACTIVE_TASK_STATUSES+ else None+ ),+ )+ try:+ async with self._transaction() as session:+ existing = await self._load_task(+ session,+ stored.task_id,+ account_id=None,+ user_id=None,+ lock=True,+ )+ if existing is not None:+ if existing.account_id != account_id or existing.user_id != user_id:+ raise ValueError(+ f"Task id already belongs to another owner: {stored.task_id}"+ )+ return self._task_from_row(+ existing,+ execution_events=await self._event_history(session, stored.task_id),+ )+ session.add(row)+ await self._store_event_history(session, stored.task_id, stored.execution_events)+ except IntegrityError as exc:+ if not self._is_duplicate_error(exc):+ raise+ async with self._session_factory() as session:+ existing = await self._load_task(+ session,+ stored.task_id,+ account_id=None,+ user_id=None,+ )+ if existing is not None:+ if existing.account_id != account_id or existing.user_id != user_id:+ raise ValueError(+ f"Task id already belongs to another owner: {stored.task_id}"+ )+ return self._task_from_row(+ existing,+ execution_events=await self._event_history(session, stored.task_id),+ )+ if reject_if_active:+ raise TaskAlreadyActive(stored.task_type, stored.resource_id) from exc+ raise+ return stored++ @staticmethod+ def _is_duplicate_error(exc: IntegrityError) -> bool:+ original = getattr(exc, "orig", None)+ args = getattr(original, "args", ())+ return bool(args and args[0] == 1062) or "duplicate" in str(exc).lower()++ async def _populate_processing_seconds(+ self, session: AsyncSession, tasks: list[TaskRecord]+ ) -> None:+ """Project active durations from batched, interval-only Work reads."""+ active = [task for task in tasks if task.status in ACTIVE_TASK_STATUSES]+ Work = self._models.Work+ now = time.time()+ for offset in range(0, len(active), 200):+ batch = active[offset : offset + 200]+ intervals: dict[str, list[WorkRecord]] = {task.task_id: [] for task in batch}+ rows = await session.execute(+ select(Work.task_id, Work.started_at, Work.finished_at).where(+ Work.task_id.in_(intervals),+ Work.started_at.is_not(None),+ )+ )+ for row in rows:+ intervals[row.task_id].append(+ WorkRecord(+ task_id=row.task_id,+ work_id="",+ queue_name="",+ started_at=float(row.started_at),+ finished_at=(+ float(row.finished_at) if row.finished_at is not None else None+ ),+ )+ )+ for task in batch:+ task.processing_seconds = processing_seconds(intervals[task.task_id], now=now)++ async def get_task(+ self,+ task_id: str,+ *,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> Optional[TaskRecord]:+ async with self._session_factory() as session:+ row = await self._load_task(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if row is None:+ return None+ task = self._task_from_row(row)+ await self._populate_processing_seconds(session, [task])+ return task++ async def get_task_with_events(+ self,+ task_id: str,+ *,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> Optional[TaskRecord]:+ async with self._session_factory() as session:+ row = await self._load_task(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if row is None:+ return None+ task = self._task_from_row(+ row, execution_events=await self._event_history(session, task_id)+ )+ await self._populate_processing_seconds(session, [task])+ return task++ async def list(+ self,+ account_id: Optional[str] = None,+ *,+ user_id: Optional[str] = None,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: Optional[int] = None,+ before: tuple[float, str] | None = None,+ include_internal: bool = True,+ q: Optional[str] = None,+ ) -> list[TaskRecord]:+ if limit is not None and limit <= 0:+ return []++ Task = self._models.Task++ def statement_for(cursor: tuple[float, str] | None, batch_limit: int):+ predicates = []+ if account_id is not None:+ predicates.append(Task.account_id == account_id)+ if user_id is not None:+ predicates.append(Task.user_id == user_id)+ if task_type is not None:+ predicates.append(Task.task_type == task_type)+ if status is not None:+ predicates.append(Task.status == status)+ if resource_id is not None:+ predicates.append(Task.resource_id == resource_id)+ if not include_internal:+ predicates.append(Task.is_internal.is_(False))+ if cursor is not None:+ predicates.append(+ or_(+ Task.created_at < cursor[0],+ and_(Task.created_at == cursor[0], Task.task_id < cursor[1]),+ )+ )+ return (+ select(Task)+ .where(*predicates)+ .order_by(Task.created_at.desc(), Task.task_id.desc())+ .limit(batch_limit)+ )++ async with self._session_factory() as session:+ if q is None:+ batch_size = limit if limit is not None else 200+ cursor = before+ result: list[TaskRecord] = []+ while True:+ rows = (await session.scalars(statement_for(cursor, batch_size))).all()+ tasks = [self._task_from_row(row) for row in rows]+ await self._populate_processing_seconds(session, tasks)+ result.extend(tasks)+ if limit is not None or len(rows) < batch_size:+ return result+ cursor = (float(rows[-1].created_at), rows[-1].task_id)++ from openviking.service.task_pagination import matches++ batch_size = max(100, min(1000, (limit or 100) * 2))+ cursor = before+ result = []+ while True:+ rows = (await session.scalars(statement_for(cursor, batch_size))).all()+ if not rows:+ break+ for row in rows:+ task = self._task_from_row(row)+ if matches(+ task.to_dict(),+ task_type=task_type,+ status=status,+ resource_id=resource_id,+ include_internal=include_internal,+ q=q,+ ):+ result.append(task)+ if limit is not None and len(result) >= limit:+ await self._populate_processing_seconds(session, result)+ return result+ cursor = (float(rows[-1].created_at), rows[-1].task_id)+ if len(rows) < batch_size:+ break+ await self._populate_processing_seconds(session, result)+ return result++ def snapshot_task_stats(self) -> TaskStatsSnapshot:+ """Return no stale process-local snapshot; callers use durable list APIs."""+ return {}++ async def delete_tasks(+ self,+ task_id: Optional[str] = None,+ *,+ account_id: str,+ user_id: Optional[str] = None,+ allow_active_types: Collection[str] = (),+ ) -> DeleteTasksResult:+ if not account_id:+ raise ValueError("Task deletion requires a non-empty account_id")+ if task_id is not None and not user_id:+ raise ValueError("Deleting one Task requires user_id")+ Task = self._models.Task+ async with self._transaction() as session:+ predicates = [Task.account_id == account_id]+ if task_id is not None:+ predicates.append(Task.task_id == task_id)+ if user_id is not None:+ predicates.append(Task.user_id == user_id)+ rows = (+ await session.scalars(+ select(Task).where(*predicates).order_by(Task.task_id).with_for_update()+ )+ ).all()+ allowed = set(allow_active_types)+ task_ids = [row.task_id for row in rows]+ open_task_ids = set()+ if task_ids:+ Work = self._models.Work+ open_task_ids = set(+ await session.scalars(+ select(Work.task_id)+ .where(+ Work.task_id.in_(task_ids),+ Work.state.not_in(+ [WorkState.DONE.value, WorkState.FAILED.value]+ ),+ )+ .distinct()+ )+ )+ blockers = []+ for row in rows:+ if row.task_type in allowed:+ continue+ if row.status in {status.value for status in ACTIVE_TASK_STATUSES}:+ code = StoreOperationCode.ACTIVE_TASK+ message = f"Cannot delete active task record: {row.task_id}({row.task_type})"+ elif row.task_id in open_task_ids:+ code = StoreOperationCode.OPEN_WORK+ message = f"Cannot delete active task record: {row.task_id}"+ else:+ continue+ blockers.append(+ TaskDeletionBlocker(+ row.task_id, row.account_id, row.user_id, row.task_type, code, message+ )+ )+ if blockers:+ active = [+ item for item in blockers if item.code is StoreOperationCode.ACTIVE_TASK+ ]+ if active:+ code = StoreOperationCode.ACTIVE_TASK+ message = "Cannot delete active task records: " + ", ".join(+ f"{item.task_id}({item.task_type})" for item in active+ )+ elif len(blockers) == 1:+ code, message = blockers[0].code, blockers[0].message+ else:+ code = StoreOperationCode.OPEN_WORK+ message = "Cannot delete active task records: " + ", ".join(+ item.task_id for item in blockers+ )+ return DeleteTasksResult(+ result=StoreOperationResult.rejected(code, message),+ blockers=tuple(blockers),+ )+ if task_id is not None and not rows:+ return DeleteTasksResult(+ result=StoreOperationResult.noop(StoreOperationCode.NOT_FOUND)+ )+ deleted = tuple(+ DeletedTask(row.task_id, row.account_id, row.user_id)+ for row in sorted(rows, key=lambda row: (row.account_id, row.user_id, row.task_id))+ )+ if task_ids:+ await session.execute(delete(Task).where(Task.task_id.in_(task_ids)))+ return DeleteTasksResult(deleted)++ async def delete_expired(+ self, policy: TaskRetentionPolicy, *, now: float, limit: int+ ) -> DeleteExpiredResult:+ if limit <= 0:+ return DeleteExpiredResult()+ Task = self._models.Task+ completed_cutoff = now - policy.completed_seconds+ failed_cutoff = now - policy.failed_seconds+ statement = (+ select(Task)+ .where(+ or_(+ and_(+ Task.status.in_([TaskStatus.COMPLETED.value, TaskStatus.CANCELLED.value]),+ Task.updated_at < completed_cutoff,+ ),+ and_(+ Task.status == TaskStatus.FAILED.value,+ Task.updated_at < failed_cutoff,+ ),+ )+ )+ .order_by(Task.updated_at, Task.task_id)+ .limit(limit)+ )+ async with self._transaction() as session:+ rows = (await session.scalars(statement.with_for_update())).all()+ deleted: list[DeletedTask] = []+ task_ids = [row.task_id for row in rows]+ open_task_ids = set()+ if task_ids:+ Work = self._models.Work+ open_task_ids = set(+ await session.scalars(+ select(Work.task_id)+ .where(+ Work.task_id.in_(task_ids),+ Work.state.not_in(+ [WorkState.DONE.value, WorkState.FAILED.value]+ ),+ )+ .distinct()+ )+ )+ for row in rows:+ if row.task_id in open_task_ids:+ continue+ await session.delete(row)+ deleted.append(DeletedTask(row.task_id, row.account_id, row.user_id))+ return DeleteExpiredResult(+ tuple(deleted),+ scanned=len(rows),+ scan_complete=len(rows) < limit,+ )++ async def _finalize_if_closed(+ self,+ session: AsyncSession,+ task_id: str,+ *,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> Optional[TaskRecord]:+ """Check for open Work under the Task lock held before any Work mutation."""+ row = await self._load_task(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ lock=True,+ )+ if row is None:+ return None+ if await self._has_open_work(session, task_id):+ return None+ works = await self._works(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ previous = self._task_from_row(+ row,+ works,+ execution_events=await self._event_history(session, task_id),+ )+ task = deepcopy(previous)+ if not finalize_task(task, works):+ return previous++ task.updated_at = TaskRecord.next_updated_at(previous.updated_at)+ append_task_events(task, previous)+ Task = self._models.Task+ await session.execute(+ update(Task)+ .where(Task.task_id == task_id)+ .values(+ status=task.status.value,+ updated_at=task.updated_at,+ stage=task.stage,+ result=_json_copy(task.result),+ error=task.error,+ auth=_json_copy(task.auth),+ processing_seconds=task.processing_seconds,+ active_business_key=None,+ )+ )+ await self._store_event_history(session, task_id, task.execution_events)+ return task++ async def start_task(+ self,+ task_id: str,+ *,+ stage: Optional[str],+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ row = await session.execute(+ select(Task.status, Task.stage, Task.updated_at)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = row.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in (TaskStatus.PENDING.value, TaskStatus.RUNNING.value):+ return _inactive_result(row.status, "Task cannot be started")++ previous = TaskRecord(+ task_id=task_id,+ task_type="",+ status=TaskStatus(row.status),+ stage=row.stage,+ execution_events=await self._event_history(session, task_id),+ )+ task = deepcopy(previous)+ task.status = TaskStatus.RUNNING+ if stage is not None:+ task.stage = stage+ append_task_events(task, previous)+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ status=task.status.value,+ stage=task.stage,+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ await self._store_event_history(session, task_id, task.execution_events)+ return StoreOperationResult.applied()++ async def update_stage(+ self,+ task_id: str,+ stage: str,+ *,+ meta: Optional[Dict[str, Any]],+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ query_result = await session.execute(+ select(+ Task.status,+ Task.stage,+ Task.meta,+ Task.updated_at,+ )+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = query_result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in {item.value for item in ACTIVE_TASK_STATUSES}:+ return _inactive_result(row.status, "Task stage cannot be updated")++ previous = TaskRecord(+ task_id=task_id,+ task_type="",+ status=TaskStatus(row.status),+ stage=row.stage,+ meta=_json_copy(row.meta) or {},+ execution_events=await self._event_history(session, task_id),+ )+ task = deepcopy(previous)+ task.stage = stage+ if meta:+ _deep_merge(task.meta, deepcopy(meta))+ append_task_events(task, previous)+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ stage=task.stage,+ meta=_json_copy(task.meta),+ is_internal=bool(task.meta.get("internal")),+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ await self._store_event_history(session, task_id, task.execution_events)+ return StoreOperationResult.applied()++ async def update_auth(+ self,+ task_id: str,+ values: Dict[str, Any],+ *,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ result = await session.execute(+ select(Task.status, Task.auth, Task.updated_at)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in {item.value for item in ACTIVE_TASK_STATUSES}:+ return _inactive_result(row.status, "Task auth cannot be updated")+ auth = _json_copy(row.auth) or {}+ _deep_merge(auth, deepcopy(values))+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ auth=auth,+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ return StoreOperationResult.applied()++ async def merge_meta(+ self,+ task_id: str,+ values: Dict[str, Any],+ *,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ result = await session.execute(+ select(Task.status, Task.meta, Task.updated_at)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in (TaskStatus.PENDING.value, TaskStatus.RUNNING.value):+ return _inactive_result(row.status, "Task meta cannot be updated")+ meta = _json_copy(row.meta) or {}+ _deep_merge(meta, deepcopy(values))+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ meta=meta,+ is_internal=bool(meta.get("internal")),+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ return StoreOperationResult.applied()++ async def record_event(+ self,+ task_id: str,+ kind: str,+ *,+ operation: Optional[str],+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ query_result = await session.execute(+ select(+ Task.status,+ Task.stage,+ Task.updated_at,+ )+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = query_result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in {item.value for item in ACTIVE_TASK_STATUSES}:+ return StoreOperationResult.noop(+ StoreOperationCode.ALREADY_TERMINAL,+ f"Task is already {row.status}",+ )+ events = append_task_event(+ await self._event_history(session, task_id),+ kind=kind,+ status=row.status,+ stage=sanitize_error(row.stage) if row.stage else None,+ operation=operation,+ )+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ await self._store_event_history(session, task_id, events)+ return StoreOperationResult.applied()++ async def record_outcome(+ self,+ task_id: str,+ *,+ result: Optional[Dict[str, Any]],+ error: Optional[str],+ resource_id: Optional[str],+ cancelled: bool,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ query_result = await session.execute(+ select(+ Task.status,+ Task.stage,+ Task.error,+ Task.resource_id,+ Task.auth,+ Task.updated_at,+ Task.task_type,+ Task.account_id,+ Task.user_id,+ Task.reject_if_active,+ )+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = query_result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in {item.value for item in ACTIVE_TASK_STATUSES}:+ return StoreOperationResult.noop(+ StoreOperationCode.ALREADY_TERMINAL,+ f"Task is already {row.status}",+ )++ values: dict[str, Any] = {}+ if result is not None:+ values["result"] = deepcopy(result)+ if resource_id is not None:+ values["resource_id"] = resource_id+ values["active_business_key"] = (+ _business_key(+ row.account_id,+ row.user_id,+ row.task_type,+ resource_id,+ )+ if row.reject_if_active+ else None+ )+ next_error = row.error+ if error and next_error is None:+ next_error = sanitize_error(error)+ values["error"] = next_error++ next_status = TaskStatus.CANCELLING if cancelled else TaskStatus(row.status)+ events = None+ if cancelled or (error and row.error is None):+ previous = TaskRecord(+ task_id=task_id,+ task_type=row.task_type,+ status=TaskStatus(row.status),+ stage=row.stage,+ error=row.error,+ execution_events=await self._event_history(session, task_id),+ )+ task = deepcopy(previous)+ task.status = next_status+ task.error = next_error+ append_task_events(task, previous)+ if cancelled:+ values["status"] = task.status.value+ events = task.execution_events++ markers = (row.auth or {}).get("enqueue_complete_work_ids")+ auth = _json_copy(row.auth) or {}+ if markers:+ auth["enqueue_complete_work_ids"] = deepcopy(markers)+ else:+ auth.pop("enqueue_complete_work_ids", None)+ values["auth"] = auth+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ **values,+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ await self._store_event_history(session, task_id, events)+ finalized = await self._finalize_if_closed(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if finalized is not None:+ return StoreOperationResult.applied()+ return StoreOperationResult.applied()++ async def request_cancellation(+ self,+ task_id: str,+ *,+ cancellable_types: Collection[str],+ allow_terminal: bool,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ result = await session.execute(+ select(+ Task.status,+ Task.task_type,+ Task.stage,+ Task.error,+ Task.updated_at,+ Task.resource_id,+ Task.account_id,+ Task.user_id,+ Task.reject_if_active,+ )+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status in (TaskStatus.CANCELLING.value, TaskStatus.CANCELLED.value):+ return StoreOperationResult.noop(+ StoreOperationCode.ALREADY_CANCELLED,+ f"Task is already {row.status}",+ )+ if row.task_type not in cancellable_types:+ return StoreOperationResult.rejected(+ StoreOperationCode.NOT_CANCELLABLE,+ f"Task type '{row.task_type}' does not support cancellation",+ )+ if row.status in {item.value for item in TERMINAL_TASK_STATUSES} and not allow_terminal:+ return StoreOperationResult.rejected(+ StoreOperationCode.ALREADY_TERMINAL,+ f"Task is already {row.status}",+ )++ previous = TaskRecord(+ task_id=task_id,+ task_type=row.task_type,+ status=TaskStatus(row.status),+ resource_id=row.resource_id,+ account_id=row.account_id,+ user_id=row.user_id,+ stage=row.stage,+ error=row.error,+ execution_events=await self._event_history(session, task_id),+ )+ task = deepcopy(previous)+ task.status = TaskStatus.CANCELLING+ append_task_events(task, previous)+ values: dict[str, Any] = {+ "status": task.status.value,+ }+ if row.reject_if_active:+ values["active_business_key"] = _business_key(+ row.account_id, row.user_id, row.task_type, row.resource_id+ )+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ **values,+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ await self._store_event_history(session, task_id, task.execution_events)+ finalized = await self._finalize_if_closed(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if finalized is not None:+ return StoreOperationResult.applied()+ return StoreOperationResult.applied()++ async def mark_enqueue_complete(+ self,+ task_id: str,+ work_id: str,+ *,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ result = await session.execute(+ select(Task.status, Task.auth, Task.updated_at)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .with_for_update()+ )+ row = result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status not in {item.value for item in ACTIVE_TASK_STATUSES}:+ return StoreOperationResult.noop(+ StoreOperationCode.ALREADY_TERMINAL,+ f"Task is already {row.status}",+ )+ completed = set((row.auth or {}).get("enqueue_complete_work_ids") or ())+ if work_id in completed:+ return StoreOperationResult.noop(StoreOperationCode.DUPLICATE)+ completed.add(work_id)+ auth = _json_copy(row.auth) or {}+ auth["enqueue_complete_work_ids"] = sorted(completed)+ await session.execute(+ update(Task)+ .where(*self._task_query(Task, task_id, account_id, user_id))+ .values(+ auth=auth,+ updated_at=TaskRecord.next_updated_at(row.updated_at),+ )+ )+ return StoreOperationResult.applied()++ async def is_enqueue_complete(+ self,+ task_id: str,+ work_id: str,+ *,+ account_id: str,+ user_id: str,+ ) -> bool:+ Task = self._models.Task+ async with self._session_factory() as session:+ auth = await session.scalar(+ select(Task.auth).where(*self._task_query(Task, task_id, account_id, user_id))+ )+ return bool(auth and work_id in set(auth.get("enqueue_complete_work_ids") or ()))++ async def add_work(+ self, work: WorkRecord, *, account_id: str, user_id: str+ ) -> StoreOperationResult:+ self._require_owner(account_id, user_id)+ Work = self._models.Work+ Task = self._models.Task+ async with self._transaction() as session:+ result = await session.execute(+ select(Task.status)+ .where(*self._task_query(Task, work.task_id, account_id, user_id))+ .with_for_update()+ )+ row = result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status in {+ item.value for item in TERMINAL_TASK_STATUSES+ } or row.status == TaskStatus.CANCELLING.value:+ return StoreOperationResult.rejected(+ StoreOperationCode.ALREADY_TERMINAL+ if row.status in {item.value for item in TERMINAL_TASK_STATUSES}+ else StoreOperationCode.INVALID_STATE,+ f"Task {work.task_id} is {row.status}; rejected work",+ )+ existing = await self._lock_work(session, work.task_id, work.work_id)+ if existing is not None:+ return StoreOperationResult.noop(StoreOperationCode.DUPLICATE)+ session.add(+ Work(+ task_id=work.task_id,+ work_id=work.work_id,+ account_id=account_id,+ user_id=user_id,+ queue_name=work.queue_name,+ state=work.state.value,+ requeue_count=work.requeue_count,+ error=work.error,+ errors=_json_copy(work.errors),+ context_count=work.context_count,+ enqueued_at=work.enqueued_at,+ started_at=work.started_at,+ finished_at=work.finished_at,+ updated_at=work.updated_at,+ )+ )+ return StoreOperationResult.applied()++ async def reconcile_delivery(+ self, work: WorkRecord, *, account_id: str, user_id: str+ ) -> StoreOperationResult:+ Task = self._models.Task+ async with self._transaction() as session:+ result = await session.execute(+ select(Task.status)+ .where(*self._task_query(Task, work.task_id, account_id, user_id))+ .with_for_update()+ )+ row = result.one_or_none()+ if row is None:+ return _not_found_result()+ if row.status in {item.value for item in TERMINAL_TASK_STATUSES}:+ return StoreOperationResult.noop(+ StoreOperationCode.ALREADY_TERMINAL,+ f"Task is already {row.status}",+ )+ existing = await self._lock_work(session, work.task_id, work.work_id)+ if existing is None:+ session.add(+ self._models.Work(+ task_id=work.task_id,+ work_id=work.work_id,+ account_id=account_id,+ user_id=user_id,+ queue_name=work.queue_name,+ state=work.state.value,+ requeue_count=work.requeue_count,+ error=work.error,+ errors=_json_copy(work.errors),+ context_count=work.context_count,+ enqueued_at=work.enqueued_at,+ started_at=work.started_at,+ finished_at=work.finished_at,+ updated_at=work.updated_at,+ )+ )+ return StoreOperationResult.applied()+ elif existing.state in {WorkState.PENDING.value, WorkState.RUNNING.value}:+ if existing.queue_name == work.queue_name:+ return StoreOperationResult.noop()+ await session.execute(+ update(self._models.Work)+ .where(+ self._models.Work.task_id == work.task_id,+ self._models.Work.work_id == work.work_id,+ )+ .values(queue_name=work.queue_name)+ )+ return StoreOperationResult.applied()+ return StoreOperationResult.noop()++ async def discard_work(+ self, task_id: str, work_id: str, *, account_id: str, user_id: str+ ) -> StoreOperationResult:+ Work = self._models.Work+ async with self._transaction() as session:+ if not await self._lock_task(session, task_id, account_id=account_id, user_id=user_id):+ return StoreOperationResult.noop(StoreOperationCode.NOT_FOUND)+ result = await session.execute(+ select(Work)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .with_for_update()+ )+ work = result.scalar_one_or_none()+ if work is None:+ return StoreOperationResult.noop(StoreOperationCode.NOT_FOUND)+ await session.delete(work)+ await session.flush()+ finalized = await self._finalize_if_closed(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if finalized is not None:+ return StoreOperationResult.applied()+ return StoreOperationResult.applied()++ async def get_work(+ self, task_id: str, work_id: str, *, account_id: str, user_id: str+ ) -> Optional[WorkRecord]:+ async with self._session_factory() as session:+ row = await session.scalar(+ select(self._models.Work).where(+ *self._work_query(+ self._models.Work,+ task_id,+ work_id,+ account_id,+ user_id,+ )+ )+ )+ return self._work_from_row(row) if row is not None else None++ async def get_works(+ self,+ task_id: str,+ work_ids: Collection[str],+ *,+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> Dict[str, WorkRecord]:+ async with self._session_factory() as session:+ selected = set(work_ids)+ if not selected:+ return {}+ Work = self._models.Work+ rows = (+ await session.scalars(+ select(Work).where(+ *self._work_query(Work, task_id, None, account_id, user_id),+ Work.work_id.in_(selected),+ )+ )+ ).all()+ return {row.work_id: self._work_from_row(row) for row in rows}++ async def start_work(+ self, task_id: str, work_id: str, *, account_id: str, user_id: str+ ) -> StoreOperationResult:+ Work = self._models.Work+ async with self._transaction() as session:+ result = await session.execute(+ select(Work.state, Work.started_at)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .with_for_update()+ )+ work = result.one_or_none()+ if work is None or work.state in {WorkState.DONE.value, WorkState.FAILED.value}:+ return StoreOperationResult.rejected(+ StoreOperationCode.WORK_NOT_OPEN,+ f"Work {work_id} is unavailable",+ )+ now = time.time()+ await session.execute(+ update(Work)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .values(+ state=WorkState.RUNNING.value,+ started_at=work.started_at or now,+ finished_at=None,+ updated_at=now,+ )+ )+ return StoreOperationResult.applied()++ async def finish_work(+ self,+ task_id: str,+ work_id: str,+ state: WorkState,+ *,+ error: Optional[str],+ errors: Optional[Collection[str]],+ context_count_delta: int,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ if state not in (WorkState.DONE, WorkState.FAILED):+ raise ValueError(f"Non-terminal Work state: {state}")+ Work = self._models.Work+ async with self._transaction() as session:+ if not await self._lock_task(session, task_id, account_id=account_id, user_id=user_id):+ return StoreOperationResult.noop(+ StoreOperationCode.WORK_NOT_OPEN,+ f"Work {work_id} is unavailable",+ )+ result = await session.execute(+ select(Work.state, Work.error, Work.context_count)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .with_for_update()+ )+ work = result.one_or_none()+ if work is None or work.state in {+ WorkState.DONE.value,+ WorkState.FAILED.value,+ }:+ return StoreOperationResult.noop(+ StoreOperationCode.WORK_NOT_OPEN,+ f"Work {work_id} is unavailable",+ )+ now = time.time()+ values: dict[str, Any] = {+ "state": state.value,+ "finished_at": now,+ "updated_at": now,+ }+ if error:+ values["error"] = sanitize_error(error)+ if state == WorkState.FAILED:+ details = [sanitize_error(str(value)) for value in errors or () if str(value)]+ values["errors"] = details or (+ [values.get("error", work.error)] if values.get("error", work.error) else []+ )+ if context_count_delta > 0:+ values["context_count"] = work.context_count + context_count_delta+ await session.execute(+ update(Work)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .values(**values)+ )+ finalized = await self._finalize_if_closed(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if finalized is not None:+ return StoreOperationResult.applied()+ return StoreOperationResult.applied()++ async def requeue_work(+ self,+ task_id: str,+ work_id: str,+ *,+ delta: int,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Work = self._models.Work+ async with self._transaction() as session:+ result = await session.execute(+ select(Work.state, Work.requeue_count)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .with_for_update()+ )+ work = result.one_or_none()+ if work is None or work.state in {WorkState.DONE.value, WorkState.FAILED.value}:+ return StoreOperationResult.noop(+ StoreOperationCode.WORK_NOT_OPEN,+ f"Work {work_id} is unavailable",+ )+ await session.execute(+ update(Work)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .values(+ state=WorkState.PENDING.value,+ requeue_count=work.requeue_count + max(delta, 0),+ started_at=None,+ finished_at=None,+ updated_at=time.time(),+ )+ )+ return StoreOperationResult.applied()++ async def record_work_error(+ self,+ task_id: str,+ work_id: str,+ error: str,+ *,+ account_id: str,+ user_id: str,+ ) -> StoreOperationResult:+ Work = self._models.Work+ async with self._transaction() as session:+ result = await session.execute(+ select(Work.error)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .with_for_update()+ )+ work = result.one_or_none()+ if work is None:+ return StoreOperationResult.noop(StoreOperationCode.WORK_NOT_OPEN)+ if work.error:+ return StoreOperationResult.noop()+ await session.execute(+ update(Work)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .values(error=sanitize_error(error), updated_at=time.time())+ )+ return StoreOperationResult.applied()++ async def settle_work(+ self, task_id: str, work_id: str, *, account_id: str, user_id: str+ ) -> StoreOperationResult:+ Work = self._models.Work+ async with self._transaction() as session:+ if not await self._lock_task(session, task_id, account_id=account_id, user_id=user_id):+ return StoreOperationResult.noop(StoreOperationCode.NOT_FOUND)+ result = await session.execute(+ select(Work.state, Work.error)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .with_for_update()+ )+ work = result.one_or_none()+ if work is None:+ return StoreOperationResult.noop(StoreOperationCode.NOT_FOUND)+ changed = False+ if work.state not in {WorkState.DONE.value, WorkState.FAILED.value}:+ settled_state = WorkState.FAILED.value if work.error else WorkState.DONE.value+ settled_at = time.time()+ changed = True+ await session.execute(+ update(Work)+ .where(*self._work_query(Work, task_id, work_id, account_id, user_id))+ .values(+ state=settled_state,+ finished_at=settled_at,+ updated_at=settled_at,+ )+ )+ finalized = await self._finalize_if_closed(+ session,+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if finalized is not None:+ return StoreOperationResult.applied()+ return StoreOperationResult.applied() if changed else StoreOperationResult.noop()++ async def get_task_status(+ self,+ task_id: str,+ *,+ account_id: str,+ user_id: str,+ ) -> Optional[TaskStatus]:+ Task = self._models.Task+ async with self._session_factory() as session:+ status = await session.scalar(+ select(Task.status).where(*self._task_query(Task, task_id, account_id, user_id))+ )+ return TaskStatus(status) if status is not None else None++ async def has_open_work(+ self,+ task_id: str,+ *,+ exclude_work_id: Optional[str],+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> bool:+ Work = self._models.Work+ async with self._session_factory() as session:+ predicates = list(+ self._work_query(Work, task_id, None, account_id, user_id)+ )+ predicates.append(+ Work.state.not_in([WorkState.DONE.value, WorkState.FAILED.value])+ )+ if exclude_work_id is not None:+ predicates.append(Work.work_id != exclude_work_id)+ return bool(await session.scalar(select(exists().where(*predicates))))++ async def summarize_works(+ self,+ task_id: str,+ *,+ work_ids: Optional[Collection[str]],+ account_id: Optional[str],+ user_id: Optional[str],+ ) -> WorkSummary:+ async with self._session_factory() as session:+ return summarize_works(+ await self._works(+ session,+ task_id,+ work_ids,+ account_id=account_id,+ user_id=user_id,+ )+ )++ async def filter_cancellation_requested(+ self,+ task_ids: Collection[str],+ *,+ account_id: str,+ user_id: str,+ ) -> set[str]:+ ids = set(task_ids)+ if not ids:+ return set()+ Task = self._models.Task+ async with self._session_factory() as session:+ rows = (+ await session.scalars(+ select(Task.task_id).where(+ Task.task_id.in_(ids),+ Task.account_id == account_id,+ Task.user_id == user_id,+ Task.status.in_([TaskStatus.CANCELLING.value, TaskStatus.CANCELLED.value]),+ )+ )+ ).all()+ return set(rows)++ async def is_cancellation_requested(+ self,+ task_id: str,+ *,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> bool:+ async with self._session_factory() as session:+ Task = self._models.Task+ return bool(+ await session.scalar(+ select(+ exists().where(+ *self._task_query(Task, task_id, account_id, user_id),+ Task.status.in_(+ [TaskStatus.CANCELLING.value, TaskStatus.CANCELLED.value]+ ),+ )+ )+ )+ )diff --git a/openviking/service/task_store_mysql_schema.py b/openviking/service/task_store_mysql_schema.pynew file mode 100644index 000000000..c959c11b0--- /dev/null+++ b/openviking/service/task_store_mysql_schema.py@@ -0,0 +1,205 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""SQLAlchemy models for the relational Task/Work store."""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any, Optional++from sqlalchemy import Boolean, ForeignKey, Index, Integer, String, Text, UniqueConstraint+from sqlalchemy.dialects.mysql import DOUBLE, JSON, VARBINARY+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column++# The longest derived name is ix_<prefix>_owner_internal_created (26 extra chars).+_MAX_TABLE_PREFIX_LENGTH = 64 - len("ix__owner_internal_created")+++def validate_table_prefix(value: object) -> str:+ if (+ not isinstance(value, str)+ or len(value) > _MAX_TABLE_PREFIX_LENGTH+ or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", value)+ ):+ raise ValueError(+ "MySQL task_store.table must start with a letter, contain only letters, "+ f"digits, or underscores, and be at most {_MAX_TABLE_PREFIX_LENGTH} characters"+ )+ return value+++@dataclass(frozen=True)+class TaskStoreModels:+ Base: type[DeclarativeBase]+ Task: Any+ Work: Any+ Event: Any+ table_prefix: str++ @property+ def table_names(self) -> tuple[str, str, str]:+ return self.Task.__tablename__, self.Work.__tablename__, self.Event.__tablename__+++def make_task_store_models(table_prefix: str = "ov_tasks") -> TaskStoreModels:+ """Build isolated mappings for one configured table namespace."""+ table_prefix = validate_table_prefix(table_prefix)+ work_table = f"{table_prefix}_works"+ event_table = f"{table_prefix}_execution_events"++ class Base(DeclarativeBase):+ pass++ class Task(Base):+ __tablename__ = table_prefix+ __table_args__ = (+ UniqueConstraint(+ "active_business_key",+ name=f"uq_{table_prefix}_active_business_key",+ ),+ Index(+ f"ix_{table_prefix}_owner_created",+ "account_id",+ "user_id",+ "created_at",+ "task_id",+ ),+ Index(+ f"ix_{table_prefix}_account_created",+ "account_id",+ "created_at",+ "task_id",+ ),+ Index(+ f"ix_{table_prefix}_created",+ "created_at",+ "task_id",+ ),+ Index(+ f"ix_{table_prefix}_owner_status",+ "account_id",+ "user_id",+ "status",+ ),+ Index(+ f"ix_{table_prefix}_owner_internal_created",+ "account_id",+ "user_id",+ "is_internal",+ "created_at",+ "task_id",+ ),+ Index(+ f"ix_{table_prefix}_expiry",+ "status",+ "updated_at",+ "task_id",+ ),+ {+ "mysql_engine": "InnoDB",+ "mysql_charset": "utf8mb4",+ "mysql_row_format": "DYNAMIC",+ },+ )++ task_id: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"), primary_key=True)+ task_type: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"))+ status: Mapped[str] = mapped_column(String(16, collation="ascii_bin"))+ created_at: Mapped[float] = mapped_column(DOUBLE)+ updated_at: Mapped[float] = mapped_column(DOUBLE)+ resource_id: Mapped[Optional[str]] = mapped_column(+ Text(collation="utf8mb4_bin"), nullable=True+ )+ account_id: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"))+ user_id: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"))+ meta: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)+ stage: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ result: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)+ error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ auth: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)+ processing_seconds: Mapped[Optional[float]] = mapped_column(DOUBLE, nullable=True)+ reject_if_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ is_internal: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ active_business_key: Mapped[Optional[bytes]] = mapped_column(VARBINARY(32), nullable=True)++ class Work(Base):+ __tablename__ = work_table+ __table_args__ = (+ Index(+ f"ix_{work_table}_state",+ "task_id",+ "state",+ ),+ Index(+ f"ix_{work_table}_queue",+ "task_id",+ "queue_name",+ "state",+ ),+ Index(+ f"ix_{work_table}_owner",+ "account_id",+ "user_id",+ "task_id",+ ),+ {+ "mysql_engine": "InnoDB",+ "mysql_charset": "utf8mb4",+ "mysql_row_format": "DYNAMIC",+ },+ )++ task_id: Mapped[str] = mapped_column(+ String(255, collation="utf8mb4_bin"),+ ForeignKey(+ f"{table_prefix}.task_id",+ ondelete="CASCADE",+ name=f"fk_{work_table}_task",+ ),+ primary_key=True,+ )+ work_id: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"), primary_key=True)+ account_id: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"))+ user_id: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"))+ queue_name: Mapped[str] = mapped_column(String(255, collation="utf8mb4_bin"))+ state: Mapped[str] = mapped_column(String(16, collation="ascii_bin"))+ requeue_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ errors: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)+ context_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ enqueued_at: Mapped[float] = mapped_column(DOUBLE)+ started_at: Mapped[Optional[float]] = mapped_column(DOUBLE, nullable=True)+ finished_at: Mapped[Optional[float]] = mapped_column(DOUBLE, nullable=True)+ updated_at: Mapped[float] = mapped_column(DOUBLE)++ class Event(Base):+ __tablename__ = event_table+ __table_args__ = (+ {+ "mysql_engine": "InnoDB",+ "mysql_charset": "utf8mb4",+ "mysql_row_format": "DYNAMIC",+ },+ )++ task_id: Mapped[str] = mapped_column(+ String(255, collation="utf8mb4_bin"),+ ForeignKey(+ f"{table_prefix}.task_id",+ ondelete="CASCADE",+ name=f"fk_{event_table}_task",+ ),+ primary_key=True,+ )+ seq: Mapped[int] = mapped_column(Integer, primary_key=True)+ recorded_at: Mapped[str] = mapped_column(String(64, collation="ascii_bin"))+ kind: Mapped[str] = mapped_column(String(64, collation="utf8mb4_bin"))+ status: Mapped[str] = mapped_column(String(16, collation="ascii_bin"))+ stage: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)+ operation: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ dropped_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ started_mid_task: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)++ return TaskStoreModels(Base, Task, Work, Event, table_prefix)diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.pyindex 508d9245f..e448a0668 100644--- a/openviking/service/task_tracker.py+++ b/openviking/service/task_tracker.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+import inspectimport reimport threadingimport time@@ -305,6 +306,22 @@ class TaskTracker:def work_recovery_mode(self) -> WorkRecoveryMode:return self._store.work_recovery_mode+ async def load(self) -> None:+ """Load backend resources without exposing backend transaction details."""+ loader = getattr(self._store, "load", None)+ if loader is not None:+ result = loader()+ if inspect.isawaitable(result):+ await result++ async def close(self) -> None:+ """Release backend resources owned by the tracker."""+ closer = getattr(self._store, "close", None)+ if closer is not None:+ result = closer()+ if inspect.isawaitable(result):+ await result+async def restore_work_tasks(self, owners: Dict[str, tuple[str, str]]) -> List[TaskRecord]:restored = []for task_id, (account_id, user_id) in owners.items():@@ -701,6 +718,17 @@ class TaskTracker:task = await self._store.get_task(task_id, account_id=account_id, user_id=user_id)return self._public(task) if task is not None else None+ async def get_with_events(+ self,+ task_id: str,+ account_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> Optional[TaskRecord]:+ task = await self._store.get_task_with_events(+ task_id, account_id=account_id, user_id=user_id+ )+ return self._public(task) if task is not None else None+async def get_task_status(self, task_id: str, *, account_id: str, user_id: str) -> Optional[TaskStatus]:@@ -723,11 +751,29 @@ class TaskTracker:with _consume_wait_budget(task_id, timeout) as remaining:deadline = None if remaining is None else time.monotonic() + remainingwhile 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_TASK_STATUSES:- return task+ if account_id is not None and user_id is not None:+ status = await self.get_task_status(+ task_id,+ account_id=account_id,+ user_id=user_id,+ )+ if status is None:+ raise KeyError(f"Task not found: {task_id}")+ if status in TERMINAL_TASK_STATUSES:+ 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}")+ return task+ else:+ 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_TASK_STATUSES:+ return taskremaining = None if deadline is None else deadline - time.monotonic()if remaining is not None and remaining <= 0:raise TimeoutError(f"Timed out waiting for Task {task_id}")@@ -830,7 +876,7 @@ class TaskTracker:task_type=task_type,status=status,resource_id=resource_id,- limit=None,+ limit=source_limit,before=before,include_internal=include_internal,q=q,@@ -868,7 +914,13 @@ class TaskTracker:account_id: str,user_id: str,) -> WorkRegistration:- work = WorkRecord(work_id=work_id, task_id=task_id, queue_name=queue_name)+ work = WorkRecord(+ work_id=work_id,+ task_id=task_id,+ queue_name=queue_name,+ account_id=account_id,+ user_id=user_id,+ )async def register() -> WorkRegistration:try:@@ -901,7 +953,13 @@ class TaskTracker:account_id: str,user_id: str,) -> None:- work = WorkRecord(work_id=work_id, task_id=task_id, queue_name=queue_name)+ work = WorkRecord(+ work_id=work_id,+ task_id=task_id,+ queue_name=queue_name,+ account_id=account_id,+ user_id=user_id,+ )await self._store.reconcile_delivery(work, account_id=account_id, user_id=user_id)async def get_work_state(diff --git a/openviking/session/session.py b/openviking/session/session.pyindex 9bf02dc20..b8eb62284 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -34,6 +34,7 @@ from openviking.message.part import TextPart, ToolPartfrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.error_mapping import map_exceptionfrom openviking.server.identity import RequestContext, Role+from openviking.service.task_work_index import bind_task_contextfrom openviking.session import working_memory as wmfrom openviking.session.archive_store import (ArchiveStore,@@ -1140,9 +1141,8 @@ class Session:async def _write_phase1_ready_marker(self,archive_uri: str,- lease_ref: Optional[Any] = None,) -> None:- """Persist that Phase 1 is ready using an optional held PathLock lease."""+ """Persist that Phase 1 is ready under the marker file's own lock."""phase1 = await self._read_phase1_meta(archive_uri)phase1.update({@@ -1150,7 +1150,7 @@ class Session:"ready_at": get_current_timestamp(),})- await self._merge_archive_meta(archive_uri, {"phase1": phase1}, lease_ref=lease_ref)+ await self._merge_archive_meta(archive_uri, {"phase1": phase1})async def _archive_file_exists(self, archive_uri: str, file_name: str) -> bool:try:@@ -1165,9 +1165,9 @@ class Session:async def _ensure_phase1_ready(self, archive_uri: str) -> bool:"""Verify or recover a queued Phase 1 before Phase 2 consumes it.- New commits enqueue while holding the session lock and before rewriting- root messages. A consumer therefore acquires the same lock, then either- observes ``phase1.status=ready`` in archive metadata or+ New commits persist the archive intent and rewrite root messages while+ holding the Session lock. A consumer therefore acquires the same lock,+ then either observes ``phase1.status=ready`` in archive metadata ordeterministically reconciles a process crash from the persisted intent."""marker = await self._read_phase1_meta(archive_uri)@@ -1322,9 +1322,10 @@ class Session:Phase 1 (Archive prep, path-lock protected): Split messages intoarchive/retain parts, persist a recoverable intent and archive raw,- enqueue Phase 2, then publish the retained root state with- ``phase1.status=ready``. Uses a distributed filesystem lock across- workers and processes.+ then publish the retained root state with ``phase1.status=ready``.+ Task registration and QueueFS publication happen after the Session+ lock under a short archive publication lease. Uses a distributed+ filesystem lock across workers and processes.Phase 2 (Memory extraction): Runs through the persistent QueueFS queue.Args:@@ -1428,6 +1429,7 @@ class Session:lease = await self._viking_fs._async_agfs.pathlock_acquire_exact(session_path, timeout_secs=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS)+ publication_lease: Optional[Any] = Nonetry:self._messages = await self._read_live_messages_strict()await self._load_meta()@@ -1636,12 +1638,6 @@ class Session:},)- phase1_stage = "queue_enqueue"- await get_queue_manager().enqueue(- QueueManager.SESSION_COMMIT,- queue_msg.to_dict(),- )-phase1_stage = "phase1_persist"self._messages = retained_messagesawait self._write_to_agfs_async(messages=self._messages)@@ -1665,6 +1661,17 @@ class Session:# never see a stale state.self._meta.last_auto_commit_at = get_current_timestamp()await self._save_meta()+ # Keep a separate archive lease while Task/Work publication runs+ # outside the Session lock. A later archive must not interpret+ # this intentional registration window as an orphan.+ phase1_stage = "publication_lease"+ archive_path = self._viking_fs._uri_to_path(archive_uri, ctx=self.ctx)+ publication_lease = (+ await self._viking_fs._async_agfs.pathlock_acquire_exact(+ archive_path,+ timeout_secs=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS,+ )+ )await self._write_phase1_ready_marker(archive_uri)if record_idle_commit_success:previous_accepted_at = self._meta.last_idle_commit_accepted_at@@ -1680,6 +1687,8 @@ class Session:self.session_id,exc_info=True,)+ if reset_context:+ await self._append_context_reset_archive()except Exception as e:logger.error(f"[commit] Failed during {phase1_stage}: {e}")# Whether the queue write failed or a queued Phase 1 stopped@@ -1698,35 +1707,84 @@ class Session:)self._messages = original_messagesself._compression.compression_index -= 1+ if publication_lease is not None:+ try:+ await self._viking_fs._async_agfs.pathlock_release(publication_lease)+ except Exception:+ logger.exception(+ "Failed to release archive publication lease: %s",+ archive_uri,+ )+ publication_lease = Noneraise- if reset_context:- await self._append_context_reset_archive()finally:await self._viking_fs._async_agfs.pathlock_release(lease)- # Lock released; Phase 1 intent, queue item, retained root, metadata and- # ready metadata are all durable.+ # Lock released; Phase 1 intent, retained root, metadata and ready+ # metadata are durable before Task-store or QueueFS latency.self._compression.original_count += len(messages_to_archive)logger.info(f"Archived: {len(messages_to_archive)} messages → {archive_uri}/")- # Registration must not hold the session lock or roll back published Phase 1.+ # Registration and enqueue must not hold the session lock or roll back+ # published Phase 1. Task must exist before middleware registers Queue Work.+ tracker = get_task_tracker()try:- await get_task_tracker().create(- "session_commit",- resource_id=self.session_id,- account_id=self.ctx.account_id,- user_id=self.ctx.user.user_id,- task_id=task_id,- )- except Exception as exc:- error = map_exception(exc) or InternalError(str(exc))- error.details.update(- task_id=task_id,- archive_uri=archive_uri,- archived=True,- stage="task_tracker_create",- )- raise error+ try:+ await tracker.create(+ "session_commit",+ resource_id=self.session_id,+ account_id=self.ctx.account_id,+ user_id=self.ctx.user.user_id,+ task_id=task_id,+ )+ except Exception as exc:+ error = map_exception(exc) or InternalError(str(exc))+ error.details.update(+ task_id=task_id,+ archive_uri=archive_uri,+ archived=True,+ stage="task_tracker_create",+ )+ raise error++ try:+ with bind_task_context(+ task_id,+ self.ctx.account_id,+ self.ctx.user.user_id,+ ):+ await get_queue_manager().enqueue(+ QueueManager.SESSION_COMMIT,+ queue_msg.to_dict(),+ )+ except Exception as exc:+ try:+ await tracker.fail(+ task_id,+ str(exc),+ account_id=self.ctx.account_id,+ user_id=self.ctx.user.user_id,+ )+ except Exception:+ logger.exception("Failed to persist Task failure: %s", task_id)+ error = map_exception(exc) or InternalError(str(exc))+ error.details.update(+ task_id=task_id,+ archive_uri=archive_uri,+ archived=True,+ stage="queue_enqueue",+ )+ raise error+ finally:+ if publication_lease is not None:+ try:+ await self._viking_fs._async_agfs.pathlock_release(publication_lease)+ except Exception:+ logger.exception(+ "Failed to release archive publication lease: %s",+ archive_uri,+ )+ publication_lease = Nonereturn {"session_id": self.session_id,@@ -2586,9 +2644,8 @@ class Session:blocked_by: str = "",skipped: bool = True,completed_memory_steps: Optional[Dict[str, List[str]]] = None,- lease_ref: Optional[Any] = None,) -> None:- """Persist a terminal failure marker for the archive."""+ """Persist a terminal failure marker under the marker file's own lock."""if not self._viking_fs:returnpayload = {@@ -2604,7 +2661,6 @@ class Session:uri=f"{archive_uri}/.failed.json",content=json.dumps(payload, ensure_ascii=False),ctx=self.ctx,- lease_ref=lease_ref,)async def get_session_context(self, token_budget: int = 128_000) -> Dict[str, Any]:@@ -2843,23 +2899,47 @@ class Session:if await tracker.has_work(str(task_id)):return False- error = "Session commit queue work is missing"- await self._write_failed_marker(- predecessor_uri,- stage="queue_missing",- error=error,- )- await tracker.fail(- str(task_id),- error,- account_id=self.ctx.account_id,- user_id=self.ctx.user.user_id,- )- logger.warning(- "Skipped orphaned Session archive without QueueFS work: %s",- predecessor_uri,- )- return True+ # A ready archive can still be between Task creation and QueueFS+ # publication. The producer holds this lease until that publication+ # attempt has settled; defer rather than declaring an orphan.+ predecessor_path = self._viking_fs._uri_to_path(predecessor_uri, ctx=self.ctx)+ publication_lease = None+ try:+ publication_lease = await self._viking_fs._async_agfs.pathlock_acquire_exact(+ predecessor_path,+ timeout_secs=0.0,+ )+ except Exception:+ logger.debug(+ "Predecessor archive is still being published; requeueing: %s",+ predecessor_uri,+ exc_info=True,+ )+ return False++ try:+ if await tracker.has_work(str(task_id)):+ return False++ error = "Session commit queue work is missing"+ await self._write_failed_marker(+ predecessor_uri,+ stage="queue_missing",+ error=error,+ )+ await tracker.fail(+ str(task_id),+ error,+ account_id=self.ctx.account_id,+ user_id=self.ctx.user.user_id,+ )+ logger.warning(+ "Skipped orphaned Session archive without QueueFS work: %s",+ predecessor_uri,+ )+ return True+ finally:+ await self._viking_fs._async_agfs.pathlock_release(publication_lease)async def _prepare_phase2_archive_messages(self,diff --git a/openviking/storage/mysql_runtime.py b/openviking/storage/mysql_runtime.pynew file mode 100644index 000000000..7921199b4--- /dev/null+++ b/openviking/storage/mysql_runtime.py@@ -0,0 +1,263 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Shared event-loop runtime for asynchronous MySQL stores."""++from __future__ import annotations++import asyncio+import inspect+import threading+from collections.abc import Awaitable, Callable+from concurrent.futures import Future+from functools import wraps+from threading import Event, Thread+from typing import Any, TypeVar++T = TypeVar("T")+_Operation = Callable[[], Awaitable[T]]+++async def wait_mysql_cleanup(operation: Awaitable[T]) -> T:+ """Wait for database cleanup to finish before propagating cancellation."""+ cleanup = asyncio.ensure_future(operation)+ try:+ return await asyncio.shield(cleanup)+ except asyncio.CancelledError:+ while not cleanup.done():+ try:+ await asyncio.shield(cleanup)+ except asyncio.CancelledError:+ continue+ except BaseException:+ break+ cleanup.result()+ raise+++class MySQLRuntime:+ """Run MySQL store operations on one private event loop.++ Individual stores create their own SQLAlchemy engine and pool on this+ loop. The runtime only owns loop affinity and lifecycle.+ """++ def __init__(self) -> None:+ self._state_lock = threading.Lock()+ self._loop: asyncio.AbstractEventLoop | None = None+ self._thread: Thread | None = None+ self._ready: Event | None = None+ self._stopped: Event | None = None+ self._stopping = False+ self._leases = 0+ self._operations = 0++ def in_runtime_loop(self) -> bool:+ try:+ return asyncio.get_running_loop() is self._loop+ except RuntimeError:+ return False++ async def run(self, operation: _Operation[T]) -> T:+ """Run an operation, including cancellation cleanup, on the private loop."""+ caller_loop = asyncio.get_running_loop()+ with self._state_lock:+ self._operations += 1+ on_runtime = caller_loop is self._loop+ if on_runtime:+ try:+ return await operation()+ finally:+ self._operation_finished()++ # Keep the loop alive from admission through the actual Task completion.+ # Cancelling a run_coroutine_threadsafe Future does not wait for that Task.+ result: Future[T] = Future()+ task: asyncio.Task[T] | None = None+ cancel_requested = False++ def finished(completed: asyncio.Task[T]) -> None:+ self._operation_finished()+ try:+ result.set_result(completed.result())+ except BaseException as exc:+ result.set_exception(exc)++ def start() -> None:+ nonlocal task+ try:+ task = loop.create_task(self._invoke(operation))+ except BaseException as exc:+ self._operation_finished()+ result.set_exception(exc)+ return+ task.add_done_callback(finished)+ if cancel_requested:+ task.cancel()++ def cancel() -> None:+ nonlocal cancel_requested+ cancel_requested = True+ if task is not None and not task.done():+ task.cancel()++ try:+ while True:+ loop = await self._ensure_loop()+ with self._state_lock:+ if loop is self._loop and not self._stopping:+ loop.call_soon_threadsafe(start)+ break+ except BaseException:+ self._operation_finished()+ raise++ wrapped = asyncio.wrap_future(result)+ try:+ return await asyncio.shield(wrapped)+ except asyncio.CancelledError:+ with self._state_lock:+ if loop is self._loop and not self._stopping:+ loop.call_soon_threadsafe(cancel)+ # Repeated caller cancellation must not interrupt rollback/dispose.+ # Only the runtime Task's done callback acknowledges completion.+ while not wrapped.done():+ try:+ await asyncio.shield(wrapped)+ except asyncio.CancelledError:+ continue+ except BaseException:+ break+ try:+ wrapped.result()+ except BaseException:+ pass+ raise++ async def acquire(self) -> None:+ """Keep the private loop alive for one loaded MySQL store."""+ await self.run(self._acquire_on_loop)++ async def release(self) -> None:+ """Release one store; stop only after all admitted operations finish."""+ await self.run(self._release_on_loop)++ async def _invoke(self, operation: _Operation[T]) -> T:+ return await operation()++ async def _acquire_on_loop(self) -> None:+ with self._state_lock:+ self._leases += 1++ async def _release_on_loop(self) -> None:+ with self._state_lock:+ if self._leases <= 0:+ raise RuntimeError("MySQLRuntime lease underflow")+ self._leases -= 1++ def _operation_finished(self) -> None:+ with self._state_lock:+ self._operations -= 1+ self._stop_if_idle_locked()++ def _stop_if_idle_locked(self) -> None:+ if self._leases or self._operations or self._loop is None or self._stopping:+ return+ self._stopping = True+ self._loop.call_soon_threadsafe(self._loop.stop)++ async def _ensure_loop(self) -> asyncio.AbstractEventLoop:+ while True:+ wait_ready: Event | None = None+ wait_stopped: Event | None = None+ with self._state_lock:+ if self._loop is not None and self._loop.is_running() and not self._stopping:+ return self._loop+ if self._stopping:+ wait_stopped = self._stopped+ elif self._thread is not None:+ wait_ready = self._ready+ else:+ ready = Event()+ stopped = Event()+ thread = Thread(+ target=self._thread_main,+ args=(ready, stopped),+ name="openviking-mysql",+ daemon=True,+ )+ self._ready = ready+ self._stopped = stopped+ self._thread = thread+ thread.start()+ wait_ready = ready++ if wait_stopped is not None:+ await asyncio.to_thread(wait_stopped.wait)+ elif wait_ready is not None:+ await asyncio.to_thread(wait_ready.wait)++ def _thread_main(self, ready: Event, stopped: Event) -> None:+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ with self._state_lock:+ self._loop = loop+ self._stop_if_idle_locked()+ loop.call_soon(ready.set)+ try:+ loop.run_forever()+ finally:+ 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.close()+ with self._state_lock:+ if self._loop is loop:+ self._loop = None+ self._thread = None+ self._ready = None+ self._stopped = None+ self._stopping = False+ stopped.set()+++_shared_runtime: MySQLRuntime | None = None+_shared_runtime_lock = threading.Lock()+++def get_shared_mysql_runtime() -> MySQLRuntime:+ """Return the process-wide loop runtime used by MySQL stores."""+ global _shared_runtime+ with _shared_runtime_lock:+ if _shared_runtime is None:+ _shared_runtime = MySQLRuntime()+ return _shared_runtime+++def mysql_runtime_store(cls: type[T]) -> type[T]:+ """Dispatch public async store methods to the store's MySQL runtime."""+ for name, method in list(vars(cls).items()):+ if name.startswith("_") or not inspect.iscoroutinefunction(method):+ continue++ @wraps(method)+ async def dispatch(self: Any, *args: Any, _method=method, _name=name, **kwargs: Any):+ runtime: MySQLRuntime = self._mysql_runtime++ async def invoke():+ if _name in ("load", "close"):+ loop = asyncio.get_running_loop()+ lifecycle = getattr(self, "_mysql_lifecycle_lock", None)+ if lifecycle is None or lifecycle[0] is not loop:+ lifecycle = (loop, asyncio.Lock())+ self._mysql_lifecycle_lock = lifecycle+ async with lifecycle[1]:+ return await _method(self, *args, **kwargs)+ return await _method(self, *args, **kwargs)++ return await runtime.run(invoke)++ setattr(cls, name, dispatch)+ return clsdiff --git a/openviking/storage/mysql_session.py b/openviking/storage/mysql_session.pynew file mode 100644index 000000000..9cea014dc--- /dev/null+++ b/openviking/storage/mysql_session.py@@ -0,0 +1,14 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""SQLAlchemy session cleanup for the shared MySQL runtime."""++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from openviking.storage.mysql_runtime import wait_mysql_cleanup+++class MySQLAsyncSession(AsyncSession):+ async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:+ await wait_mysql_cleanup(self.close())diff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.pyindex 6a29f9b6a..0785df7e7 100644--- a/openviking/storage/queuefs/queue_manager.py+++ b/openviking/storage/queuefs/queue_manager.py@@ -189,6 +189,32 @@ class QueueManager:)return await tracker.restore_work_tasks(owners)+ async def get_queued_tasks(self, tracker: Any, queue_name: str) -> list[Any]:+ """Read Tasks referenced by a queue's unacknowledged deliveries."""+ from openviking.service.task_work_index import extract_task_metadata++ queue = self._queues.get(queue_name)+ if queue is None:+ return []+ tasks = []+ seen: set[tuple[str, str, str]] = set()+ for message in await queue.snapshot():+ metadata = extract_task_metadata(message)+ if metadata is None or not metadata.account_id or not metadata.user_id:+ continue+ key = (metadata.task_id, metadata.account_id, metadata.user_id)+ if key in seen:+ continue+ seen.add(key)+ task = await tracker.get(+ metadata.task_id,+ account_id=metadata.account_id,+ user_id=metadata.user_id,+ )+ if task is not None:+ tasks.append(task)+ return tasks+def setup_standard_queues(self,vector_store: Any,@@ -427,10 +453,16 @@ class QueueManager:stop_event.set()if self.EMBEDDING not in self._queue_threads:self._embedding_worker_stopped.set()+ alive_workers = []for name, thread in self._queue_threads.items():thread.join(timeout=10.0)if thread.is_alive():logger.warning(f"[QueueManager] Worker thread {name} did not exit in time")+ alive_workers.append(name)+ if alive_workers:+ # Keep queues and dependencies available for pending finalizers and+ # let the caller retry shutdown once the workers have terminated.+ raise RuntimeError(f"Queue workers did not stop: {', '.join(alive_workers)}")self._queue_threads.clear()self._queue_stop_events.clear()diff --git a/openviking/storage/queuefs/reindex_processor.py b/openviking/storage/queuefs/reindex_processor.pyindex 192c53a51..4632ef224 100644--- a/openviking/storage/queuefs/reindex_processor.py+++ b/openviking/storage/queuefs/reindex_processor.py@@ -20,6 +20,7 @@ from openviking.telemetry import (resolve_telemetry,unregister_telemetry,)+from openviking_cli.exceptions import OpenVikingErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_logger@@ -162,7 +163,13 @@ class ReindexProcessor(DequeueHandlerBase):return ProcessResult.success()except Exception as exc:await tracker.fail(- msg.task_id, str(exc), account_id=ctx.account_id, user_id=ctx.user.user_id+ msg.task_id,+ str(exc),+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ result={"code": exc.code, "details": exc.details}+ if isinstance(exc, OpenVikingError)+ else None,)return ProcessResult.failed(str(exc))finally:diff --git a/openviking_cli/utils/config/storage_config.py b/openviking_cli/utils/config/storage_config.pyindex d9e01d653..4b4f6aedc 100644--- a/openviking_cli/utils/config/storage_config.py+++ b/openviking_cli/utils/config/storage_config.py@@ -15,6 +15,22 @@ from .vectordb_config import VectorDBBackendConfiglogger = get_logger(__name__)+class TaskStoreConfig(BaseModel):+ """Durable Task/Work backend selection."""++ provider: str = "file"+ params: Dict[str, Any] = Field(default_factory=dict)++ @model_validator(mode="after")+ def normalize_provider(self):+ self.provider = self.provider.strip().lower()+ if self.provider not in {"file", "mysql"}:+ raise ValueError(+ f"storage.task_store.provider must be 'file' or 'mysql', got {self.provider!r}"+ )+ return self++class StorageConfig(BaseModel):"""Configuration for storage backend.@@ -50,6 +66,11 @@ class StorageConfig(BaseModel):description="Where parsers write intermediate artifacts (agfs temp or local dir)",)+ task_store: TaskStoreConfig = Field(+ default_factory=TaskStoreConfig,+ description="Persistent Task/Work storage backend",+ )+params: Dict[str, Any] = Field(default_factory=dict, description="Additional storage-specific parameters")@@ -119,7 +140,16 @@ class StorageConfig(BaseModel):def build_task_tracker(self, agfs: Any):"""Build the persistent TaskTracker from storage config."""- from openviking.service.task_store import PersistentTaskStore+ from openviking.service.task_store import TaskWorkStorefrom openviking.service.task_tracker import TaskTracker- return TaskTracker(store=PersistentTaskStore(agfs))+ store: TaskWorkStore+ if self.task_store.provider == "mysql":+ from openviking.service.task_store_mysql import MySQLTaskWorkStore++ store = MySQLTaskWorkStore(params=self.task_store.params)+ else:+ from openviking.service.task_store import PersistentTaskStore++ store = PersistentTaskStore(agfs)+ return TaskTracker(store=store)diff --git a/pyproject.toml b/pyproject.tomlindex 94f5172e4..50ed47e43 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -102,8 +102,9 @@ gateway-fast = ["httptools>=0.6",]mysql = [- "aiomysql>=0.2.0,<1",- "SQLAlchemy[asyncio]>=2.0.54,<2.1",+ "aiomysql>=0.2.0,<1",+ "PyMySQL>=1.1,<1.2",+ "SQLAlchemy[asyncio]>=2.0.54,<2.1",]redis-mysql = ["aiomysql>=0.2.0,<1",diff --git a/tests/agfs/test_viking_fs_git.py b/tests/agfs/test_viking_fs_git.pyindex b6eba66ff..8a18b7485 100644--- a/tests/agfs/test_viking_fs_git.py+++ b/tests/agfs/test_viking_fs_git.py@@ -650,6 +650,34 @@ class _MemTaskStore(PersistentTaskStore):return await super().create(task, reject_if_active=reject_if_active)+async def restore_reindex_queue(vfs, monkeypatch):+ from types import SimpleNamespace++ from openviking.storage.queuefs.queue_manager import QueueManager+ from openviking.storage.queuefs.reindex_processor import ReindexProcessor++ vfs.agfs.mount("queuefs", "/queue", {"backend": "memory"})+ manager = QueueManager(agfs=vfs.agfs)+ queue = manager.get_queue("Reindex", ReindexProcessor(vfs), allow_create=True)+ service = SimpleNamespace(viking_fs=vfs, _vlm_resolver=None, _vector_config_resolver=None)+ monkeypatch.setattr("openviking.service.reindex_executor.get_service", lambda: service)+ monkeypatch.setattr("openviking.server.dependencies.get_service", lambda: service)+ monkeypatch.setattr("openviking.storage.queuefs.get_queue_manager", lambda: manager)++ async def consume():+ while True:+ await queue.dequeue()+ await asyncio.sleep(0.001)++ worker = asyncio.create_task(consume())+ try:+ yield+ finally:+ worker.cancel()+ await asyncio.gather(worker, return_exceptions=True)++@pytest.mark.asyncioasync def test_restore_schedules_reindex_for_derived_only_change(vfs, monkeypatch):"""When a restore only changes a directory `.abstract.md` (source file@@ -843,7 +871,7 @@ async def test_restore_relations_json_has_no_vector_side_effect(vfs, monkeypatch@pytest.mark.asyncio-async def test_restore_returns_pollable_task_id(vfs, monkeypatch):+async def test_restore_returns_pollable_task_id(vfs, monkeypatch, restore_reindex_queue):"""An applied restore with vector side-effects returns a ``task_id`` thatcan be polled without leaving an orphaned admin reindex task."""@@ -927,6 +955,7 @@ async def test_restore_returns_pollable_task_id(vfs, monkeypatch):async def test_restore_task_registration_failure_falls_back_to_file_reindex(vfs,monkeypatch,+ restore_reindex_queue,):from openviking.service.reindex_executor import ReindexExecutorfrom openviking.service.task_tracker import TaskStatus, TaskTracker, set_task_trackerdiff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.pyindex 852c1fee9..333b055a2 100644--- a/tests/server/test_admin_rebuild_api.py+++ b/tests/server/test_admin_rebuild_api.py@@ -1,5 +1,6 @@"""Tests for reindex admin endpoint and executor behavior."""+import jsonfrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -175,67 +176,114 @@ async def test_reindex_root_requires_explicit_account(admin_client: httpx.AsyncC@pytest.mark.asyncio-async def test_reindex_resource_vectors_only_wait_true(monkeypatch):- from openviking.server.routers.content import ReindexRequest, reindex-- seen = {}+async def test_reindex_resource_vectors_only_wait_true(tmp_path, monkeypatch):+ import asyncio- class FakeService:- async def reindex(- self,- *,- uri,- mode,- wait,- ctx,- tags=None,- tag_mode="replace",- ):- seen["uri"] = uri- seen["mode"] = mode- seen["wait"] = wait- seen["ctx"] = ctx- seen["tags"] = tags- seen["tag_mode"] = tag_mode- return {- "status": "completed",- "uri": uri,- "object_type": "resource",- "mode": mode,- "rebuilt_records": 1,- "scanned_records": 1,- "unsupported_records": 0,- "failed_records": 0,- "duration_ms": 12,- "warnings": [],- }+ import ragfs_python- ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice"),- role=Role.ROOT,+ from openviking.server.routers.content import ReindexRequest, reindex+ from openviking.service.reindex_executor import ReindexExecutor+ from openviking.service.task_store import PersistentTaskStore+ from openviking.service.task_tracker import TaskStatus, TaskTracker+ from openviking.storage.queuefs.embedding_msg import EmbeddingMsg+ from openviking.storage.queuefs.named_queue import DequeueHandlerBase+ from openviking.storage.queuefs.queue_manager import QueueManager+ from openviking.storage.queuefs.reindex_processor import ReindexProcessor+ from openviking.storage.viking_fs import VikingFS++ agfs = ragfs_python.RAGFSBindingClient()+ agfs.mount("localfs", "/local", {"local_dir": str(tmp_path)})+ agfs.mount("queuefs", "/queue", {"backend": "memory"})+ fs = VikingFS(agfs=agfs)+ tracker = TaskTracker(PersistentTaskStore(agfs))+ monkeypatch.setattr("openviking.service.task_tracker._instance", tracker)+ manager = QueueManager(agfs)+ queue = manager.get_queue("Reindex", ReindexProcessor(fs), allow_create=True)+ child_enqueued, child_started, release_child = asyncio.Event(), asyncio.Event(), asyncio.Event()++ class EmbeddingHandler(DequeueHandlerBase):+ async def on_dequeue(self, data):+ child_started.set()+ await release_child.wait()+ return ProcessResult.success({"vector_written": True})++ embedding = manager.get_queue("Embedding", EmbeddingHandler(), allow_create=True)+ ctx = RequestContext(user=UserIdentifier("test", "alice"), role=Role.ROOT)+ owner = {"account_id": ctx.account_id, "user_id": ctx.user.user_id}+ uri = "viking://resources/demo.md"+ service = SimpleNamespace(+ viking_fs=fs,+ vikingdb_manager=SimpleNamespace(has_queue_manager=True),+ _vlm_resolver=None,+ _vector_config_resolver=None,+ reindex=ReindexExecutor().execute,)- request = ReindexRequest(- uri="viking://resources/demo",- mode="vectors_only",- wait=True,- tags=["Team=Search", "env=prod"],- tag_mode="append",+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: service)+ monkeypatch.setattr("openviking.service.reindex_executor.get_service", lambda: service)+ monkeypatch.setattr("openviking.server.dependencies.get_service", lambda: service)+ monkeypatch.setattr("openviking.storage.queuefs.get_queue_manager", lambda: manager)++ async def rebuild(_self, *, uri, mode, run):+ assert mode == "vectors_only"+ assert run.ingest_options.search_tags == ["team=search", "env=prod"]+ assert run.ingest_options.search_tag_mode == "append"+ await embedding.enqueue(+ EmbeddingMsg(message="source", context_data={"uri": uri, "account_id": ctx.account_id})+ )+ run.counters.scanned_records = run.counters.rebuilt_records = 1+ child_enqueued.set()++ monkeypatch.setattr(ReindexExecutor, "_reindex_resource", rebuild)+ await fs.write_file(uri, "source", ctx=ctx)+ request = asyncio.create_task(+ reindex(+ body=ReindexRequest(+ uri=uri,+ mode="vectors_only",+ wait=True,+ tags=["Team=Search", "env=prod"],+ tag_mode="append",+ ),+ ctx=ctx,+ ))-- monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())- response = await reindex(body=request, ctx=ctx)-- assert response.status == "ok"- assert response.result["status"] == "completed"- assert response.result["object_type"] == "resource"- assert response.result["rebuilt_records"] == 1- assert seen["uri"] == "viking://resources/demo"- assert seen["mode"] == "vectors_only"- assert seen["wait"] is True- assert seen["ctx"] == ctx- assert seen["tags"] == ["Team=Search", "env=prod"]- assert seen["tag_mode"] == "append"- assert "reason" not in response.result+ processing = child = None+ try:+ deadline = asyncio.get_running_loop().time() + 2+ while not (messages := await queue.snapshot()):+ if request.done():+ request.result()+ assert asyncio.get_running_loop().time() < deadline+ await asyncio.sleep(0.001)+ task_id = json.loads(messages[0]["data"])["task_id"]+ while (await tracker.get(task_id, **owner)).stage != "queued":+ assert asyncio.get_running_loop().time() < deadline+ await asyncio.sleep(0.001)+ processing = asyncio.create_task(queue.dequeue())+ await asyncio.wait_for(child_enqueued.wait(), 2)+ child = asyncio.create_task(embedding.dequeue())+ await asyncio.wait_for(child_started.wait(), 2)+ assert not request.done()+ assert (await tracker.get(task_id, **owner)).status is TaskStatus.RUNNING+ release_child.set()+ await asyncio.wait_for(asyncio.gather(processing, child), 2)+ response = await asyncio.wait_for(request, 2)+ assert response.status == "ok"+ assert response.result["status"] == "completed"+ assert response.result["object_type"] == "resource"+ assert response.result["rebuilt_records"] == 1+ assert response.result["failed_records"] == 0+ assert "task_id" not in response.result+ assert (await tracker.get(task_id, **owner)).status is TaskStatus.COMPLETED+ assert await queue.snapshot() == await embedding.snapshot() == []+ finally:+ release_child.set()+ pending = [task for task in (request, processing, child) if task is not None]+ for task in pending:+ if not task.done():+ task.cancel()+ await asyncio.gather(*pending, return_exceptions=True)+ agfs.close()@pytest.mark.asynciodiff --git a/tests/server/test_compile_studio.py b/tests/server/test_compile_studio.pyindex 0b5891d07..51c93f68c 100644--- a/tests/server/test_compile_studio.py+++ b/tests/server/test_compile_studio.py@@ -67,15 +67,33 @@ def test_cursor_is_bound_to_identity_and_filters():@pytest.mark.asyncioasync def test_concurrent_submission_retry_and_restart(monkeypatch):+ import ragfs_python+import openviking.service.external_task_service as module+ from openviking.service.external_task_service import ExternalTaskSnapshot+ from openviking.storage.queuefs.queue_manager import QueueManageragfs = _FakeAgfs()store = PersistentTaskStore(agfs)tracker = TaskTracker(store)monkeypatch.setattr(module, "get_task_tracker", lambda: tracker)- monkeypatch.setattr(module, "get_queue_manager", lambda: SimpleNamespace(enqueue=AsyncMock()))+ monkeypatch.setattr("openviking.service.task_tracker.get_task_tracker", lambda: tracker)+ transport = ragfs_python.RAGFSBindingClient()+ transport.mount("queuefs", "/queue", {"backend": "memory"})+ manager = QueueManager(transport)+ manager.get_queue(manager.EXTERNAL_TASK, allow_create=True)+ monkeypatch.setattr(module, "get_queue_manager", lambda: manager)+ provider = SimpleNamespace(+ task_type="compile",+ task_id_prefix="cmp_",+ serialization_key=lambda payload: payload["to"],+ poll_interval_seconds=0.001,+ poll_max_attempts=1,+ submit=AsyncMock(return_value="external-task"),+ get=AsyncMock(return_value=ExternalTaskSnapshot(status="completed", result={"done": True})),+ )service = ExternalTaskService()- service.register(SimpleNamespace(task_type="compile", task_id_prefix="cmp_"))+ service.register(provider)ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)params = {"resource_id": None,@@ -84,15 +102,38 @@ async def test_concurrent_submission_retry_and_restart(monkeypatch):"ctx": ctx,"idempotency_key": "test-submission-123",}- results = await asyncio.gather(*(service.create("compile", **params) for _ in range(5)))- assert len({t.task_id for t in results}) == 1- tracker = TaskTracker(store)- again = await service.create("compile", **params)- assert again.task_id == results[0].task_id- with pytest.raises(ConflictError):- await service.create("compile", **{**params, "payload": {"to": "different"}})- other = RequestContext(user=UserIdentifier("acme", "bob"), role=Role.USER)- assert (await service.create("compile", **{**params, "ctx": other})).task_id != again.task_id+ try:+ results = await asyncio.gather(*(service.create("compile", **params) for _ in range(5)))+ assert len({t.task_id for t in results}) == 1+ tracker = TaskTracker(PersistentTaskStore(agfs))+ again = await service.create("compile", **params)+ assert again.task_id == results[0].task_id+ with pytest.raises(ConflictError):+ await service.create("compile", **{**params, "payload": {"to": "different"}})+ other = RequestContext(user=UserIdentifier("acme", "bob"), role=Role.USER)+ waiting = await service.create("compile", **{**params, "ctx": other})+ assert waiting.task_id != again.task_id++ owner = {"account_id": ctx.account_id, "user_id": ctx.user.user_id}+ await tracker.start(again.task_id, stage="polling", **owner)+ await tracker.update_task_auth(again.task_id, {"external_task_id": "submitted"}, **owner)+ tracker = TaskTracker(PersistentTaskStore(agfs))+ service = ExternalTaskService()+ service.register(provider)+ await manager.prepare_task_tracking(tracker)+ recovered = await manager.get_queued_tasks(tracker, manager.EXTERNAL_TASK)+ assert {task.task_id for task in recovered} == {again.task_id, waiting.task_id}+ await service.restore_tasks(recovered)++ assert not await service.execute(waiting.task_id, other.account_id, other.user.user_id)+ provider.submit.assert_not_awaited()+ assert await service.execute(again.task_id, ctx.account_id, ctx.user.user_id)+ assert await service.execute(waiting.task_id, other.account_id, other.user.user_id)+ assert (await tracker.get(waiting.task_id, account_id="acme", user_id="bob")).result == {+ "done": True+ }+ finally:+ transport.close()@pytest.mark.asynciodiff --git a/tests/service/test_task_work_contract.py b/tests/service/test_task_work_contract.pyindex 3dd66266e..975e24aa5 100644--- a/tests/service/test_task_work_contract.py+++ b/tests/service/test_task_work_contract.py@@ -3,7 +3,11 @@"""Observable Task/Work lifecycle and persistence contracts."""import asyncio+import json+import os+from pathlib import Pathfrom unittest.mock import Mock, create_autospec+from uuid import uuid4import pytest@@ -57,31 +61,91 @@ async def test_task_work_wait_includes_recovered_and_later_enqueued_work(tracker@pytest.mark.asyncio-async def test_requeue_keeps_logical_work_until_completion(tracker):- assert await tracker.register_work("task", "work", "Semantic", **OWNER)- assert (- await tracker.register_work("task", "work", "Semantic", **OWNER)- is WorkRegistration.EXISTING- )- await tracker.complete("task", {"done": True}, **OWNER)- await tracker.start_work("task", "work", **OWNER)- await tracker.mark_work_requeued("task", "work", **OWNER)- assert (await tracker.get("task", **OWNER)).status is TaskStatus.RUNNING-- await tracker.start_work("task", "work", **OWNER)- await tracker.mark_work_done("task", "work", **OWNER)- completed = await tracker.wait("task", timeout=0, **OWNER)- assert completed.status is TaskStatus.COMPLETED- assert completed.result["queue_status"]["Semantic"] == {- "processed": 1,- "requeue_count": 1,- "error_count": 0,- "errors": [],- }- assert (- await tracker.register_work("task", "late", "Semantic", **OWNER)- is WorkRegistration.REJECTED- )+async def test_mysql_requeue_and_concurrent_completion_are_durable():+ raw = os.environ.get("OV_TEST_MYSQL")+ if not raw:+ pytest.skip("Set OV_TEST_MYSQL to exercise the shared Task/Work contract")+ sqlalchemy = pytest.importorskip("sqlalchemy.ext.asyncio")+ pytest.importorskip("aiomysql")+ from openviking.service import task_store_mysql++ params = {**json.loads(raw), "table": f"ov_contract_{uuid4().hex[:12]}"}+ first = task_store_mysql.MySQLTaskWorkStore(params=params)+ second = task_store_mysql.MySQLTaskWorkStore(params=params)+ admin = sqlalchemy.create_async_engine(first._url, **first._engine_options)+ schema = Path(task_store_mysql.__file__).parent / "sql/task_store_init.sql"+ writer, observer = TaskTracker(first), TaskTracker(second)+ try:+ async with admin.begin() as connection:+ for statement in schema.read_text().replace("ov_tasks", params["table"]).split(";"):+ if "CREATE TABLE" in statement:+ await connection.exec_driver_sql(statement)+ await first.load()+ await second.load()+ uri = "viking://resources/" + "/".join(["directory" * 4] * 8)+ candidates = await asyncio.gather(+ writer.create_if_no_running("content_write", uri, **OWNER),+ observer.create_if_no_running("content_write", uri, **OWNER),+ )+ assert sum(task is not None for task in candidates) == 1+ task_id = next(task.task_id for task in candidates if task is not None)+ assert await observer.get(task_id, account_id="other", user_id=OWNER["user_id"]) is None+ assert await observer.get(task_id, account_id=OWNER["account_id"], user_id="other") is None++ await writer.start(task_id, **OWNER)+ await writer.register_work(task_id, "semantic", "Semantic", **OWNER)+ await observer.register_work(task_id, "embedding", "Embedding", **OWNER)+ assert (+ await observer.register_work(task_id, "semantic", "Semantic", **OWNER)+ is WorkRegistration.EXISTING+ )+ await writer.complete(task_id, {"done": True}, **OWNER)+ await writer.start_work(task_id, "semantic", **OWNER)+ await observer.mark_work_requeued(task_id, "semantic", **OWNER)+ assert (await observer.get(task_id, **OWNER)).status is TaskStatus.RUNNING+ await writer.start_work(task_id, "semantic", **OWNER)++ # The last two Work items can finish on different worker event loops.+ await asyncio.gather(+ writer.mark_work_done(task_id, "semantic", **OWNER),+ asyncio.to_thread(+ lambda: asyncio.run(observer.mark_work_done(task_id, "embedding", **OWNER))+ ),+ )+ completed = await observer.wait(task_id, timeout=0, **OWNER)+ assert completed.status is TaskStatus.COMPLETED+ assert completed.resource_id == uri+ assert completed.result["queue_status"]["Semantic"] == {+ "processed": 1,+ "requeue_count": 1,+ "error_count": 0,+ "errors": [],+ }+ assert completed.result["queue_status"]["Embedding"]["processed"] == 1+ await writer.mark_work_failed(task_id, "semantic", "late failure", **OWNER)+ assert (+ await observer.register_work(task_id, "late", "Semantic", **OWNER)+ is WorkRegistration.REJECTED+ )++ await first.close()+ await second.close()+ await second.load()+ restored = await observer.get_with_events(task_id, **OWNER)+ assert restored.status is TaskStatus.COMPLETED+ assert restored.result == completed.result+ assert restored.execution_events["items"][-1]["status"] == "completed"+ assert (+ await observer.build_queue_status(task_id, **OWNER) == completed.result["queue_status"]+ )+ assert await observer.delete_tasks(**OWNER) == 1+ assert await observer.get(task_id, **OWNER) is None+ finally:+ await first.close()+ await second.close()+ async with admin.begin() as connection:+ await connection.run_sync(first._models.Base.metadata.drop_all)+ await admin.dispose()@pytest.mark.asynciodiff --git a/tests/session/test_session_retention_integration.py b/tests/session/test_session_retention_integration.pyindex 93cfc37b6..7bb3bb44d 100644--- a/tests/session/test_session_retention_integration.py+++ b/tests/session/test_session_retention_integration.py@@ -11,7 +11,9 @@ import pytestfrom openviking.message import Message, TextPart, ToolPartfrom openviking.models.vlm.base import ToolCall, VLMResponse+from openviking.pyagfs import get_binding_clientfrom openviking.pyagfs.exceptions import AGFSIoError+from openviking.service.task_domain import TaskStatusfrom openviking.service.task_store import PersistentTaskStorefrom openviking.service.task_tracker import TaskTracker, get_task_trackerfrom openviking.session import working_memory as wm@@ -24,8 +26,7 @@ from openviking.session.checkpoints import (from openviking.session.memory.constants import AGENT_EVOLUTION_MEMORY_TYPESfrom openviking.session.session import Session, _ArchiveSummaryResultfrom openviking.storage.viking_fs import VikingFS-from openviking_cli.exceptions import UnavailableError-from tests.utils.mock_agfs import MockLocalAGFS+from openviking_cli.exceptions import InternalError, UnavailableErrorasync def _write_archive(@@ -334,7 +335,7 @@ async def test_phase2_defers_live_predecessor_and_skips_missing_queue_work()tracker = get_task_tracker()live_work = {"task-1", "task-2"}- monkeypatch.setattr(tracker, "has_work", live_work.__contains__)+ monkeypatch.setattr(tracker, "has_work", AsyncMock(side_effect=live_work.__contains__))assert not await session._can_run_archive(3)@@ -1725,21 +1726,16 @@ async def test_add_waits_for_commit_root_rewrite_and_remains_live(]-async def test_queue_enqueue_failure_marks_archive_failed_and_keeps_raw_durable(+async def test_queue_enqueue_failure_keeps_published_archive_and_fails_task(client,monkeypatch,):- """The failed marker is authoritative and the raw file stays durable.-- Terminal-stop means ``get_session_context`` no longer replays that raw as- logical live; recovery goes through Phase 2 roll-forward instead.- """session = client(session_id="queue_enqueue_failure_recovery_test")await session.ensure_exists()session.add_message("user", [TextPart("do not lose me")])class FailingQueueManager:- async def enqueue(self, *_args, **_kwargs):+ async def enqueue(self, _queue_name, data):raise RuntimeError("queue unavailable")monkeypatch.setattr(@@ -1747,26 +1743,27 @@ async def test_queue_enqueue_failure_marks_archive_failed_and_keeps_raw_durable(lambda: FailingQueueManager(),)- with pytest.raises(RuntimeError, match="queue unavailable"):+ with pytest.raises(InternalError, match="queue unavailable") as error:await session.commit_async(record_idle_commit_success=True)states = await session._archives.scan_states()- context = await session.get_session_context()- failed = json.loads(- await session._viking_fs.read_file(- f"{states[0].archive_uri}/.failed.json",- ctx=session.ctx,- )+ task = await get_task_tracker().get(+ error.value.details["task_id"],+ account_id=session.ctx.account_id,+ user_id=session.ctx.user.user_id,)- assert states[0].state == "failed"- assert failed["stage"] == "queue_enqueue"- # Raw stays durable on disk, and this message is also still live in root- # because the failed commit never trimmed it.+ assert error.value.details["archived"] is True+ assert error.value.details["stage"] == "queue_enqueue"+ assert task is not None and task.status is TaskStatus.FAILED+ assert states[0].state == "pending"+ assert (await session._read_phase1_meta(states[0].archive_uri))["status"] == "ready"raw = await session._archives.read_messages(states[0].archive_uri)assert [message.content for message in raw] == ["do not lose me"]- assert [message["parts"][0]["text"] for message in context["messages"]] == ["do not lose me"]- assert context["stats"]["failedArchives"] == 1- assert session.meta.last_idle_commit_accepted_at == ""+ assert await session._read_live_messages_strict() == []+ assert not await session._viking_fs.exists(+ f"{states[0].archive_uri}/.failed.json",+ ctx=session.ctx,+ )async def test_phase1_root_rewrite_failure_marks_orphan_archive_failed(@@ -1808,37 +1805,68 @@ async def test_phase1_root_rewrite_failure_marks_orphan_archive_failed(assert [message["parts"][0]["text"] for message in context["messages"]] == ["retained tail"]-async def test_phase1_publishes_and_unlocks_before_task_registration(tmp_path, monkeypatch):- fs = VikingFS(agfs=MockLocalAGFS(root_path=tmp_path))- tracker = TaskTracker(PersistentTaskStore(fs.agfs))- monkeypatch.setattr("openviking.service.task_tracker.get_task_tracker", lambda: tracker)+async def test_commit_publication_failure_does_not_block_following_archive(tmp_path, monkeypatch):+ client_type, _ = get_binding_client()+ agfs = client_type()+ agfs.mount("localfs", "/local", {"local_dir": str(tmp_path)})+ agfs.mount("queuefs", "/queue", {"backend": "memory"})+ fs = VikingFS(agfs=agfs)+ tracker = TaskTracker(PersistentTaskStore(agfs))+ monkeypatch.setattr("openviking.service.task_tracker._instance", tracker)monkeypatch.setattr("openviking.session.session._enabled_memory_types", lambda: set())- session = Session(viking_fs=fs, session_id="phase1_publish_order_test")- await session.ensure_exists()- await session.add_message_async("user", [TextPart("archive me")])-- async def enqueue(_queue_name, data):- assert len(await session._read_live_messages_strict()) == 1- assert (await session._read_phase1_meta(data["archive_uri"]))["status"] == "preparing"-- async def create_task(task, *, reject_if_active=False):- lease = await fs._async_agfs.pathlock_acquire_tree(- fs._uri_to_path(session.uri, ctx=session.ctx)- )- await fs._async_agfs.pathlock_release(lease)- raise AGFSIoError("task store unavailable")-- monkeypatch.setattr(tracker._store, "create", create_task)- monkeypatch.setattr(- "openviking.storage.queuefs.get_queue_manager", lambda: SimpleNamespace(enqueue=enqueue)- )- with pytest.raises(UnavailableError, match="task store unavailable") as error:- await session.commit_async()- archive_uri = error.value.details["archive_uri"]- assert error.value.details["archived"] is True- assert (await session._read_phase1_meta(archive_uri))["status"] == "ready"- assert await session._read_live_messages_strict() == []- assert not await fs.exists(f"{archive_uri}/.failed.json", ctx=session.ctx)+ from openviking.storage.queuefs.queue_manager import QueueManager++ manager = QueueManager(agfs)+ queue = manager.get_queue("SessionCommit", allow_create=True)+ monkeypatch.setattr("openviking.storage.queuefs.get_queue_manager", lambda: manager)+ first = Session(viking_fs=fs, session_id="publication_failure")+ await first.ensure_exists()+ await first.add_message_async("user", [TextPart("archive me")])+ creating, release = asyncio.Event(), asyncio.Event()+ original_create = tracker._store.create++ async def fail_first_registration(task, **kwargs):+ if not creating.is_set():+ creating.set()+ await release.wait()+ raise AGFSIoError("task store unavailable")+ return await original_create(task, **kwargs)++ monkeypatch.setattr(tracker._store, "create", fail_first_registration)+ first_commit = asyncio.create_task(first.commit_async())+ try:+ await asyncio.wait_for(creating.wait(), 2)+ assert await first._read_live_messages_strict() == []+ second = Session(viking_fs=fs, session_id=first.session_id)+ await second.load()+ await second.add_message_async("user", [TextPart("follow-up archive")])+ result = await second.commit_async()+ assert result["status"] == "accepted"+ assert result["archive_uri"].endswith("/archive_002")+ assert len(await queue.snapshot()) == 1+ assert not await second._can_run_archive(2)+ first_archive = f"{first.uri}/history/archive_001"+ assert not await fs.exists(f"{first_archive}/.failed.json", ctx=first.ctx)++ release.set()+ with pytest.raises(UnavailableError, match="task store unavailable") as error:+ await first_commit+ assert error.value.details["archived"] is True+ assert error.value.details["stage"] == "task_tracker_create"+ assert error.value.details["archive_uri"] == first_archive+ assert [+ message.content for message in await first._archives.read_messages(first_archive)+ ] == ["archive me"]+ # The same predecessor must become skippable after its publisher fails.+ assert await second._can_run_archive(2)+ failed = json.loads(await fs.read_file(f"{first_archive}/.failed.json", ctx=first.ctx))+ assert failed["stage"] == "queue_missing"+ finally:+ release.set()+ if not first_commit.done():+ first_commit.cancel()+ await asyncio.gather(first_commit, return_exceptions=True)+ agfs.close()async def test_interrupted_phase1_recovers_when_root_rewrite_is_durable(@@ -1867,7 +1895,11 @@ async def test_interrupted_phase1_recovers_when_root_rewrite_is_durable(min_raw_tail_steps=1,)await session._write_to_agfs_async(messages=[original[1]])- monkeypatch.setattr(get_task_tracker(), "has_work", lambda task_id: task_id == "synthetic")+ monkeypatch.setattr(+ get_task_tracker(),+ "has_work",+ AsyncMock(side_effect=lambda task_id: task_id == "synthetic"),+ )assert await session._ensure_phase1_ready(archive_uri)assert (await session._read_phase1_meta(archive_uri))["status"] == "ready"diff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.pyindex e06d8dbae..4dc592149 100644--- a/tests/test_task_tracker.py+++ b/tests/test_task_tracker.py@@ -1206,8 +1206,8 @@ async def test_execution_events_survive_restart_and_preserve_reported_facts():await tracker.start(task.task_id, stage="parsing", **owner)await tracker.record_event(task.task_id, "waiting_for_descendants", operation="work-1", **owner)await tracker.fail(task.task_id, "provider rejected sk-testsecret123", **owner)- before = (await tracker.get(task.task_id, **owner)).to_dict(include_events=True)- restored = (await TaskTracker(store=store).get(task.task_id, **owner)).to_dict(+ before = (await tracker.get_with_events(task.task_id, **owner)).to_dict(include_events=True)+ restored = (await TaskTracker(store=store).get_with_events(task.task_id, **owner)).to_dict(include_events=True)assert restored == before@@ -1237,10 +1237,10 @@ async def test_terminal_event_waits_for_owned_work(tracker, outcome):await getattr(tracker, outcome)(task.task_id, {"done": True} if outcome == "complete" else "error", **owner)- snapshot = await tracker.get(task.task_id, **owner)+ snapshot = await tracker.get_with_events(task.task_id, **owner)assert snapshot.status == TaskStatus.RUNNINGawait tracker.mark_work_done(task.task_id, "child-work", **owner)- snapshot = await tracker.get(task.task_id, **owner)+ snapshot = await tracker.get_with_events(task.task_id, **owner)last = snapshot.execution_events["items"][-1]assert last["kind"] == "status_changed"assert last["status"] == ("completed" if outcome == "complete" else "failed")@@ -1257,7 +1257,7 @@ async def test_legacy_tasks_do_not_get_invented_history():reader = TaskTracker(store=PersistentTaskStore(agfs))assert (await reader.get(task.task_id, **_owner_kwargs())).execution_events is Noneawait reader.start(task.task_id, **_owner_kwargs())- history = (await reader.get(task.task_id, **_owner_kwargs())).execution_events+ history = (await reader.get_with_events(task.task_id, **_owner_kwargs())).execution_eventsassert history["started_mid_task"] is Trueassert [event["kind"] for event in history["items"]] == ["status_changed"]@@ -1270,7 +1270,7 @@ async def test_event_history_is_bounded_and_reports_truncation(tracker, stage_prfor index in range(80):await tracker.update_stage(task.task_id, f"{index}:{stage_prefix}", **_owner_kwargs())await tracker.complete(task.task_id, {"done": True}, **_owner_kwargs())- history = (await tracker.get(task.task_id, **_owner_kwargs())).execution_events+ history = (await tracker.get_with_events(task.task_id, **_owner_kwargs())).execution_eventsassert len(history["items"]) <= MAX_TASK_EVENTSassert len(json.dumps(history).encode()) <= MAX_TASK_EVENT_BYTESassert history["dropped_count"] + len(history["items"]) == 82@@ -1284,7 +1284,7 @@ async def test_process_events_respect_owner_and_terminal_boundaries(tracker):task.task_id, "waiting_for_descendants", account_id="acme", user_id="bob")assert (- await tracker.get(task.task_id, **_owner_kwargs())+ await tracker.get_with_events(task.task_id, **_owner_kwargs())).execution_events == task.execution_eventswith pytest.raises(ValueError, match="Unknown task process event"):await tracker.record_event(task.task_id, "completed", **_owner_kwargs())@@ -1293,7 +1293,7 @@ async def test_process_events_respect_owner_and_terminal_boundaries(tracker):task.task_id, "waiting_for_descendants", operation="Bearer secret", **_owner_kwargs())await tracker.cancel(task.task_id, **_owner_kwargs())- cancelled = await tracker.get(task.task_id, **_owner_kwargs())+ cancelled = await tracker.get_with_events(task.task_id, **_owner_kwargs())assert [event["status"] for event in cancelled.execution_events["items"]] == ["pending","cancelling",@@ -1301,7 +1301,7 @@ async def test_process_events_respect_owner_and_terminal_boundaries(tracker):]await tracker.record_event(task.task_id, "waiting_for_descendants", **_owner_kwargs())assert (- await tracker.get(task.task_id, **_owner_kwargs())+ await tracker.get_with_events(task.task_id, **_owner_kwargs())).execution_events == cancelled.execution_eventsdiff --git a/uv.lock b/uv.lockindex 2b554c17e..8d10374dc 100644--- a/uv.lock+++ b/uv.lock@@ -3674,6 +3674,7 @@ local-embed = []mysql = [{ name = "aiomysql" },+ { name = "pymysql" },{ name = "sqlalchemy", extra = ["asyncio"] },]ocr = [@@ -3787,6 +3788,7 @@ requires-dist = [{ name = "pydantic", specifier = ">=2.0.0" },{ name = "pydantic-settings", marker = "extra == 'bot'", specifier = ">=2.0.0" },{ name = "pygments", marker = "extra == 'bot'", specifier = ">=2.16.0" },+ { name = "pymysql", marker = "extra == 'mysql'", specifier = ">=1.1,<1.2" },{ name = "pytesseract", marker = "extra == 'ocr'", specifier = ">=0.3.10" },{ name = "pytest", marker = "extra == 'test'", specifier = ">=7.0.0" },{ name = "pytest-asyncio", marker = "extra == 'test'", specifier = ">=0.21.0" },@@ -4890,11 +4892,11 @@ crypto = [[[package]]name = "pymysql"-version = "1.2.3"+version = "1.1.3"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/b1/d4/c15b459e25a23767d2f4065ef40968920320f04e302889574310c21c96a3/pymysql-1.2.3.tar.gz", hash = "sha256:d5b288529782e536ae171866df3ca9dc4f6cbfb3cc2f18e6f837fbb90dbc262b", size = 50629, upload-time = "2026-09-17T12:22:49.146Z" }+sdist = { url = "https://files.pythonhosted.org/packages/7f/ec/8d45c920e90445f0b75c590b32851853ed319763b0d8dff8d283052da8cf/pymysql-1.1.3.tar.gz", hash = "sha256:e70ebf2047a4edf6138cf79c68ad418ef620af65900aa585c5e8bfc95044d43a", size = 48207, upload-time = "2026-05-01T09:09:54.532Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/a9/4b/0a906d8184f011ff8dbd4722743783867589b33269d2c5fff238d636fdcb/pymysql-1.2.3-py3-none-any.whl", hash = "sha256:14f1c68e2ed859243ae5ca41ffbe677027fc46bc136a9f0be8a4e928e5e7415a", size = 46740, upload-time = "2026-09-17T12:22:47.826Z" },+ { url = "https://files.pythonhosted.org/packages/8e/dc/9085f3d6f497e9b25fb40d6e8ecef3ddbb5cf977a949b933624a299f5c16/pymysql-1.1.3-py3-none-any.whl", hash = "sha256:8164ba62c552f6105f3b11753352d0f16b90d1703ba67d81923d5a8a5d1c5289", size = 45356, upload-time = "2026-05-01T09:09:53.316Z" },][[package]]