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
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
"""
Resource watch scheduler.
Provides scheduled task execution for watch tasks.
"""
import asyncio
import threading
from datetime import datetime
from typing import Any, Dict, Optional, Set
from openviking.connector.auth import (
is_external_feishu_auth,
restore_feishu_request,
)
from openviking.connector.delegate import ConnectorDelegate
from openviking.resource.feishu_watch_auth import (
FeishuOAuthClient,
FeishuTokenRefreshError,
apply_feishu_refreshed_token,
feishu_auth_state_needs_refresh,
is_feishu_auth_state,
)
from openviking.resource.git_watch_auth import (
git_http_auth_config_from_state,
is_git_http_auth_state,
)
from openviking.resource.uri_mutation_coordinator import UriMutationCoordinator
from openviking.resource.watch_manager import WatchManager, WatchTask
from openviking.server.error_mapping import is_not_found_error
from openviking.server.identity import RequestContext, Role
from openviking.service.resource_service import ResourceService
from openviking.utils.git_auth import GIT_AUTH_FAILED
from openviking_cli.exceptions import NotFoundError
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
class WatchScheduler:
"""Scheduled task scheduler for resource watch tasks.
Periodically checks for due tasks and executes them by calling ResourceService.
Implements concurrency control to skip tasks that are already executing.
Handles execution failures gracefully without affecting next scheduling.
Manages the lifecycle of WatchManager internally.
"""
DEFAULT_CHECK_INTERVAL = 60.0
DEFAULT_TASK_TIMEOUT = 3 * 60 * 60
DEFAULT_GIT_PROBE_TIMEOUT = 30.0
def __init__(
self,
resource_service: ResourceService,
viking_fs: Optional[Any] = None,
check_interval: float = DEFAULT_CHECK_INTERVAL,
max_concurrency: int = 4,
task_timeout: float = DEFAULT_TASK_TIMEOUT,
uri_mutation_coordinator: Optional[UriMutationCoordinator] = None,
runtime_config_manager: Optional[Any] = None,
):
"""Initialize WatchScheduler.
Args:
resource_service: ResourceService instance for executing tasks
viking_fs: VikingFS instance for WatchManager persistence (optional)
check_interval: Interval in seconds between scheduler checks (default: 60)
"""
self._resource_service = resource_service
self._viking_fs = viking_fs
self._uri_mutation_coordinator = uri_mutation_coordinator or UriMutationCoordinator()
self._runtime_config_manager = runtime_config_manager
if check_interval <= 0:
raise ValueError("check_interval must be > 0")
if max_concurrency <= 0:
raise ValueError("max_concurrency must be > 0")
if task_timeout <= 0:
raise ValueError("task_timeout must be > 0")
self._check_interval = check_interval
self._max_concurrency = max_concurrency
self._task_timeout = task_timeout
self._semaphore = asyncio.Semaphore(max_concurrency)
self._watch_manager: Optional[WatchManager] = None
self._running = False
self._scheduler_task: Optional[asyncio.Task] = None
self._executing_tasks: Set[str] = set()
self._execution_tasks: Dict[asyncio.Task, WatchTask] = {}
self._lock = threading.Lock()
@property
def watch_manager(self) -> Optional[WatchManager]:
"""Get the WatchManager instance."""
return self._watch_manager
async def start(self) -> None:
"""Start the scheduler.
Creates a background task that periodically checks for due tasks.
Initializes the WatchManager and loads persisted tasks.
"""
if self._running:
logger.warning("[WatchScheduler] Scheduler is already running")
return
# Initialize WatchManager
self._watch_manager = WatchManager(
viking_fs=self._viking_fs,
uri_mutation_coordinator=self._uri_mutation_coordinator,
)
await self._watch_manager.initialize()
logger.info("[WatchScheduler] WatchManager initialized")
self._running = True
self._scheduler_task = asyncio.create_task(self._run_scheduler())
logger.info(f"[WatchScheduler] Started with check interval {self._check_interval}s")
async def stop(self) -> None:
"""Stop the scheduler.
Cancels the background task and waits for it to complete.
Cleans up the WatchManager.
"""
if not self._running:
logger.warning("[WatchScheduler] Scheduler is not running")
return
self._running = False
if self._scheduler_task:
self._scheduler_task.cancel()
try:
await self._scheduler_task
except asyncio.CancelledError:
pass
self._scheduler_task = None
execution_tasks = list(self._execution_tasks)
for task in execution_tasks:
task.cancel()
if execution_tasks:
await asyncio.gather(*execution_tasks, return_exceptions=True)
self._execution_tasks.clear()
# Clean up WatchManager
if self._watch_manager:
self._watch_manager = None
logger.info("[WatchScheduler] WatchManager cleaned up")
logger.info("[WatchScheduler] Stopped")
async def schedule_task(self, task_id: str) -> bool:
"""Schedule a single task for immediate execution.
Args:
task_id: ID of the task to schedule
Returns:
True if task was scheduled, False if task is already executing or not found
"""
if not self._watch_manager:
logger.warning("[WatchScheduler] WatchManager is not initialized")
return False
task = await self._watch_manager.get_task(task_id)
if not task:
logger.warning(f"[WatchScheduler] Task {task_id} not found")
return False
if not self._try_mark_executing(task_id):
logger.info(f"[WatchScheduler] Task {task_id} is already executing, skipping")
return False
execution = asyncio.current_task()
self._execution_tasks[execution] = task
try:
async with self._semaphore:
await self._execute_task(task)
return True
finally:
self._execution_tasks.pop(execution, None)
self._discard_executing(task_id)
async def delete_tasks(self, account_id: str, user_id: str | None = None) -> None:
"""Remove an identity's watches and settle their current executions."""
manager = self._watch_manager
if manager is None:
return
actor_user_id = user_id or "root"
for watch in await manager.get_all_tasks(account_id, actor_user_id, Role.ROOT):
if watch.account_id == account_id and (user_id is None or watch.user_id == user_id):
await manager.delete_task(watch.task_id, account_id, actor_user_id, Role.ROOT)
executions = [
execution
for execution, watch in self._execution_tasks.items()
if watch.account_id == account_id and (user_id is None or watch.user_id == user_id)
]
for execution in executions:
execution.cancel()
if executions:
await asyncio.gather(*executions, return_exceptions=True)
async def _run_scheduler(self) -> None:
"""Background task loop that periodically checks and executes due tasks.
This method runs continuously until the scheduler is stopped.
"""
logger.info("[WatchScheduler] Scheduler loop started")
while self._running:
try:
await self._check_and_execute_due_tasks()
except Exception as e:
logger.error(f"[WatchScheduler] Error in scheduler loop: {e}", exc_info=True)
try:
sleep_seconds = self._check_interval
if self._watch_manager:
next_time = await self._watch_manager.get_next_execution_time()
if next_time is not None:
now = datetime.now()
# Floor at 1s: a due task that is still executing (or held by
# an in-flight first round) would otherwise spin this loop.
sleep_seconds = min(
self._check_interval,
max(1.0, (next_time - now).total_seconds()),
)
await asyncio.sleep(sleep_seconds)
except asyncio.CancelledError:
break
logger.info("[WatchScheduler] Scheduler loop ended")
async def _check_and_execute_due_tasks(self) -> None:
"""Check for due tasks and execute them.
This method is called periodically by the scheduler loop.
"""
if not self._watch_manager:
return
due_tasks = await self._watch_manager.get_due_tasks()
if not due_tasks:
return
logger.info(f"[WatchScheduler] Found {len(due_tasks)} due tasks")
tasks_to_run = []
for task in due_tasks:
if not self._try_mark_executing(task.task_id):
logger.info(f"[WatchScheduler] Task {task.task_id} is already executing, skipping")
continue
tasks_to_run.append(task)
async def run_one(t) -> None:
try:
async with self._semaphore:
await self._execute_task(t)
finally:
self._discard_executing(t.task_id)
for due_task in tasks_to_run:
execution = asyncio.create_task(run_one(due_task))
self._execution_tasks[execution] = due_task
execution.add_done_callback(self._on_execution_done)
def _on_execution_done(self, task: asyncio.Task[None]) -> None:
self._execution_tasks.pop(task, None)
if task.cancelled():
return
error = task.exception()
if error is not None:
logger.error(
"[WatchScheduler] Unhandled watch execution error",
exc_info=(type(error), error, error.__traceback__),
)
async def _execute_task(self, task) -> None:
"""Execute a task only after confirming its target URI is stable."""
if not self._watch_manager:
return
candidate = task
while True:
stable_account_id = candidate.account_id
stable_to_uri = candidate.to_uri
async with self._uri_mutation_coordinator.access(
stable_account_id,
[stable_to_uri],
):
current = await self._watch_manager.get_task(
candidate.task_id,
account_id=candidate.account_id,
user_id=candidate.user_id,
role=getattr(candidate, "original_role", None) or str(Role.USER),
)
if current is None:
logger.info(
f"[WatchScheduler] Task {candidate.task_id} disappeared before execution"
)
return
if current.account_id != stable_account_id or current.to_uri != stable_to_uri:
candidate = current
continue
stable_task = current.model_copy(deep=True)
await self._execute_stable_task(stable_task)
return
async def _execute_stable_task(self, task) -> None:
"""Execute a single watch task.
Calls ResourceService.refresh_resource to re-process the resource.
Handles errors gracefully and updates execution time regardless of success/failure.
Deactivates tasks when resources no longer exist.
Args:
task: WatchTask to execute
"""
logger.info(f"[WatchScheduler] Executing task {task.task_id}")
cancelled = False
should_deactivate = False
execution_task_id = None
execution_status = None
execution_error = None
execution_code = None
probed_checkpoint: Optional[Dict[str, Any]] = None
refreshed_checkpoint: Optional[Dict[str, Any]] = None
skipped_unchanged = False
try:
auth_state = getattr(task, "auth_state", None)
connector_watch = ConnectorDelegate.is_watch_auth_state(auth_state)
if not connector_watch and not self._check_resource_exists(task.path):
should_deactivate = True
execution_error = f"Resource path does not exist: {task.path}"
logger.warning(
f"[WatchScheduler] Task {task.task_id}: {execution_error}. "
"Deactivating task."
)
else:
from openviking_cli.session.user_id import UserIdentifier
user = UserIdentifier(
account_id=task.account_id,
user_id=task.user_id,
)
role_value = getattr(task, "original_role", None) or str(Role.USER)
try:
role = Role(role_value)
except Exception:
role = Role.USER
ctx = RequestContext(
user=user,
role=role,
bypass_acl=True,
)
# Connector targets are materialized by the plugin's own writes: an
# empty first round leaves ``to`` absent and a deleted target is simply
# rebuilt next round, so only native watches are tied to its existence.
if task.to_uri and not connector_watch:
target_exists = await self._check_target_uri_exists(task.to_uri, ctx)
if target_exists is False:
should_deactivate = True
execution_error = f"Watched target URI does not exist: {task.to_uri}"
logger.warning(
f"[WatchScheduler] Task {task.task_id}: {execution_error}. "
"Deactivating task."
)
if not should_deactivate:
processor_kwargs = dict(getattr(task, "processor_kwargs", {}) or {})
processor_kwargs.pop("build_index", None)
processor_kwargs.pop("summarize", None)
if is_external_feishu_auth(auth_state):
ctx.api_key, processor_kwargs["args"] = await restore_feishu_request(
self._resource_service._connector, auth_state, path=task.path, ctx=ctx
)
elif is_feishu_auth_state(auth_state):
try:
auth_state = await self._prepare_feishu_auth_state(task, auth_state)
processor_kwargs["feishu_access_token"] = auth_state["access_token"]
except FeishuTokenRefreshError as e:
if e.permanent:
should_deactivate = True
execution_error = str(e)
logger.error(
f"[WatchScheduler] Task {task.task_id} permanent Feishu "
f"token refresh failure: {e}. Deactivating task."
)
else:
raise
elif is_git_http_auth_state(auth_state):
processor_kwargs["auth_config"] = git_http_auth_config_from_state(
auth_state,
task.path,
)
elif connector_watch:
(
api_key,
add_type,
connector_args,
connector_auth_config,
) = await self._resource_service._connector.restore_watch_request(
auth_state,
account_id=task.account_id,
path=task.path,
)
ctx.api_key = api_key
processor_kwargs["add_type"] = add_type
processor_kwargs["args"] = connector_args
# Cheap source-version gate for native git watches: skip the full
# clone/parse refresh while the watched branch tip is unchanged.
# Probe failures fail open to a normal refresh.
if not should_deactivate and not connector_watch:
probed_checkpoint = await self._probe_git_checkpoint(
task.path,
processor_kwargs,
ctx=ctx,
instruction=task.instruction,
)
if probed_checkpoint is not None:
# Reuse the probed revision as an immutable download
# target so GitAccessor.access() skips its own
# ls-remote probe on the actual refresh.
processor_kwargs["git_head_sha_hint"] = probed_checkpoint[
"head_sha"
]
stored_checkpoint = getattr(task, "source_checkpoint", None) or {}
if (
probed_checkpoint is not None
and stored_checkpoint == probed_checkpoint
and stored_checkpoint.get("kind") == "git"
):
skipped_unchanged = True
execution_status = "completed"
# No new ingestion runs: keep the last real task id so
# record_execution does not null out the public field.
execution_task_id = task.last_task_id
logger.info(
f"[WatchScheduler] Task {task.task_id} source unchanged at "
f"{probed_checkpoint.get('head_sha')}, skipping refresh"
)
if not should_deactivate and not skipped_unchanged:
refresh_kwargs = {}
if connector_watch:
refresh_kwargs["connector_states"] = getattr(task, "connector_states", None)
# Re-resolve managed credentials every round so refreshed
# tokens stay current; watches persist only the reference.
if connector_auth_config:
refresh_kwargs["connector_auth_config"] = connector_auth_config
result = await self._resource_service.refresh_resource(
path=task.path,
ctx=ctx,
to=task.to_uri,
to_is_directory=getattr(task, "to_is_directory", None),
parent=task.parent_uri,
reason=task.reason,
instruction=task.instruction,
build_index=getattr(task, "build_index", True),
summarize=getattr(task, "summarize", False),
processing_mode=getattr(task, "processing_mode", "semantic_and_vectors"),
watch_interval=task.watch_interval,
enforce_public_remote_targets=True,
**refresh_kwargs,
**processor_kwargs,
)
execution_code = result.get("code")
execution_task_id = result.get("task_id")
result_status = str(result.get("status") or "").lower()
# Synchronous deployments (no queue manager) return the
# terminal result directly: extract its revision checkpoint
# here. Async submissions carry no meta yet and get
# overridden by the task_tracker.wait result below.
refreshed_checkpoint = (
self._resource_service._initial_source_checkpoint(
result.get("meta"),
instruction=task.instruction,
)
)
if execution_task_id and result_status not in {
"completed",
"failed",
"cancelled",
"error",
}:
from openviking.service.task_tracker import get_task_tracker
task_tracker = get_task_tracker()
try:
ingestion_task = await task_tracker.wait(
execution_task_id,
account_id=task.account_id,
user_id=task.user_id,
timeout=self._task_timeout,
)
except asyncio.TimeoutError:
execution_error = (
f"ingestion task timed out after {self._task_timeout:g}s"
)
result_status = "failed"
try:
await task_tracker.cancel(
execution_task_id,
account_id=task.account_id,
user_id=task.user_id,
)
except Exception:
logger.exception(
"[WatchScheduler] Failed to cancel timed-out ingestion "
"task %s",
execution_task_id,
)
else:
result_status = ingestion_task.status.value
execution_error = ingestion_task.error
ingestion_result = getattr(ingestion_task, "result", None) or {}
execution_code = ingestion_result.get("code")
refreshed_checkpoint = (
self._resource_service._initial_source_checkpoint(
ingestion_result.get("meta"),
instruction=task.instruction,
)
)
if result_status in {"failed", "error"}:
execution_status = "failed"
if execution_error is None:
execution_error = result.get("error")
if execution_error is None and result.get("errors"):
execution_error = "; ".join(
str(error) for error in result["errors"]
)
execution_error = execution_error or "watch ingestion failed"
logger.warning(
f"[WatchScheduler] Task {task.task_id} execution finished with "
"a failed ingestion task"
)
elif result_status == "cancelled":
execution_status = "cancelled"
else:
execution_status = "completed"
if connector_watch and "connector_states" in result:
await self._watch_manager.update_connector_states(
task.task_id,
result["connector_states"],
)
if refreshed_checkpoint is not None:
# Persist the revision actually imported. ZIP downloads
# report their immutable target SHA; clone fallbacks
# report the checked-out local HEAD.
#
# Design intent: the checkpoint tracks the *source
# revision* only. A non-None checkpoint means the
# code was fetched and parsed successfully (the
# accessor only emits resolved_head_sha after a
# successful access()). Downstream semantic/embedding
# queue failures are post-processing concerns with
# their own retry paths; they must NOT block the
# source checkpoint, otherwise an unchanged HEAD
# would re-trigger a full clone+parse on every tick
# just to retry indexing. Queue health is surfaced
# via queue_status and does not gate source-version
# skip logic.
await self._watch_manager.update_source_checkpoint(
task.task_id,
refreshed_checkpoint,
)
logger.info(
f"[WatchScheduler] Task {task.task_id} executed successfully, "
f"result: {result.get('root_uri', 'N/A')}"
)
except asyncio.CancelledError:
cancelled = True
raise
except FileNotFoundError as e:
should_deactivate = True
execution_error = f"Resource not found: {e}"
execution_status = "failed"
logger.error(
f"[WatchScheduler] Task {task.task_id} resource not found: {e}. Deactivating task."
)
except Exception as e:
execution_status = "failed"
execution_error = str(e) or type(e).__name__
execution_code = getattr(e, "code", None)
logger.error(
f"[WatchScheduler] Task {task.task_id} execution failed, "
f"error_type={type(e).__name__}"
)
finally:
try:
if not cancelled:
if execution_status == "failed" and execution_code == GIT_AUTH_FAILED:
should_deactivate = True
if should_deactivate:
execution_status = "failed"
await asyncio.shield(
self._watch_manager.record_execution(
task.task_id,
status=execution_status or "completed",
execution_task_id=execution_task_id,
error=execution_error,
)
)
if should_deactivate:
await asyncio.shield(
self._watch_manager.update_task(
task_id=task.task_id,
account_id=task.account_id,
user_id=task.user_id,
role=getattr(task, "original_role", None) or str(Role.USER),
is_active=False,
)
)
logger.info(
f"[WatchScheduler] Deactivated task {task.task_id}: {execution_error}"
)
else:
logger.info(
f"[WatchScheduler] Updated execution time for task {task.task_id}"
)
except Exception as e:
logger.error(
f"[WatchScheduler] Failed to update task {task.task_id}: {e}",
exc_info=True,
)
async def hold_execution(self, task_id: str) -> bool:
"""Mark *task_id* as executing outside the scheduler.
Used while an import's first round runs so a due tick does not start an
overlapping run; release with :meth:`release_execution`.
"""
held = self._try_mark_executing(task_id)
logger.debug(f"[WatchScheduler] hold_execution task_id={task_id} held={held}")
return held
async def release_execution(self, task_id: str) -> None:
self._discard_executing(task_id)
logger.debug(f"[WatchScheduler] release_execution task_id={task_id}")
def _try_mark_executing(self, task_id: str) -> bool:
with self._lock:
if task_id in self._executing_tasks:
return False
self._executing_tasks.add(task_id)
return True
def _discard_executing(self, task_id: str) -> None:
with self._lock:
self._executing_tasks.discard(task_id)
async def _probe_git_checkpoint(
self,
path: str,
processor_kwargs: Dict[str, Any],
*,
ctx: RequestContext,
instruction: str,
) -> Optional[Dict[str, Any]]:
"""Return the watched git revision as a source checkpoint.
Commit-only sources resolve locally from the supplied commit. Returns
None for non-git sources and branch probe failures (fail open).
"""
from openviking.parse.accessors.git_accessor import GitAccessor
from openviking.utils.code_hosting_utils import is_git_repo_url
if not path or not is_git_repo_url(path):
return None
try:
probe_kwargs = dict(processor_kwargs)
if probe_kwargs.get("auth_config") is None:
resource_processor = getattr(self._resource_service, "_resource_processor", None)
if resource_processor is not None:
github_token = await resource_processor.github_token_for(path, ctx)
if github_token:
probe_kwargs["auth_config"] = {"token": github_token}
probed = await asyncio.wait_for(
GitAccessor().probe_git_remote_head(path, **probe_kwargs),
timeout=self.DEFAULT_GIT_PROBE_TIMEOUT,
)
except Exception as e:
logger.warning(
f"[WatchScheduler] git head probe failed for {path}: {e}; "
"falling back to full refresh"
)
return None
if probed is None:
return None
_, head_sha = probed
return {
"kind": "git",
"head_sha": head_sha,
"instruction": instruction,
}
async def _prepare_feishu_auth_state(
self,
task,
auth_state: Dict[str, Any],
) -> Dict[str, Any]:
if not feishu_auth_state_needs_refresh(auth_state):
return auth_state
refresh_token = auth_state.get("refresh_token")
if self._runtime_config_manager is None:
raise RuntimeError("Runtime config manager is not initialized")
from openviking.config.feishu import get_effective_feishu_config
config = await get_effective_feishu_config(
self._runtime_config_manager,
task.account_id,
)
refreshed = await FeishuOAuthClient.from_auth_state(
auth_state, config=config
).refresh_user_access_token(refresh_token)
updated = apply_feishu_refreshed_token(auth_state, refreshed)
if self._watch_manager is not None:
await self._watch_manager.update_auth_state(task.task_id, updated)
return updated
def _check_resource_exists(self, path: str) -> bool:
"""Check if a resource path exists.
Args:
path: Resource path to check
Returns:
True if resource exists or is a URL, False otherwise
"""
if path.startswith(("http://", "https://", "git@", "ssh://", "git://")):
return True
from pathlib import Path
try:
return Path(path).exists()
except Exception as e:
logger.warning(f"[WatchScheduler] Failed to check path existence {path}: {e}")
return False
async def _check_target_uri_exists(self, uri: str, ctx: RequestContext) -> Optional[bool]:
if self._viking_fs is None:
return True
try:
await self._viking_fs.stat(uri, ctx=ctx, skip_count=True)
return True
except NotFoundError:
return False
except Exception as e:
if is_not_found_error(e):
return False
logger.warning(f"[WatchScheduler] Failed to check target URI existence {uri}: {e}")
return None
@property
def is_running(self) -> bool:
"""Check if the scheduler is running."""
return self._running
@property
def executing_tasks(self) -> Set[str]:
"""Get the set of currently executing task IDs."""
with self._lock:
return self._executing_tasks.copy()