Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(scheduler): concurrent run dispatch so one hung turn can't stall delivery (#346)

Call White9bd85892f815
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 1a3847969..bca4188be 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -1021,6 +1021,12 @@ class TaskExecutionStore:
class ScheduledTaskService:
"""Controller-owned runtime that executes persisted scheduled tasks."""
+ # Upper bound on claimed requests executing concurrently. The drain loop
+ # never blocks waiting on an execution: when this many are in flight it
+ # simply leaves the rest queued and re-checks on the next tick. This caps
+ # fan-out without re-introducing head-of-line blocking.
+ _MAX_CONCURRENT_EXECUTIONS = 8
+
def __init__(
self,
controller,
@@ -1035,6 +1041,15 @@ class ScheduledTaskService:
self._job_signatures: Dict[str, tuple[Any, ...]] = {}
self._running = False
self._watch_store_restart_count = 0
+ # Claimed requests currently executing, keyed by request id, so a
+ # single slow/hung turn can't stall delivery of every other request.
+ self._inflight_executions: Dict[str, "asyncio.Task[Any]"] = {}
+ # Canonical conversation keys with an execution in flight. Used to
+ # serialize turns per session (never two at once for the same
+ # conversation) while still running different sessions concurrently.
+ self._inflight_sessions: set[str] = set()
+ # Cache of session_id -> canonical lock key (resolution hits SQLite).
+ self._session_lock_cache: Dict[str, str] = {}
self.request_store.recover_processing()
def validate_platform(self, platform: str) -> None:
@@ -1083,6 +1098,20 @@ class ScheduledTaskService:
except asyncio.CancelledError:
pass
self._reconcile_task = None
+ # Cancel any in-flight executions so shutdown is clean. Cancellation is
+ # caught by ``_execute_claimed_request``, which requeues the run, so it
+ # is picked up again on the next start (and ``recover_processing`` on
+ # init backstops anything left ``running`` after a hard crash).
+ inflight = list(self._inflight_executions.values())
+ for task in inflight:
+ task.cancel()
+ for task in inflight:
+ try:
+ await task
+ except (asyncio.CancelledError, Exception):
+ pass
+ self._inflight_executions.clear()
+ self._inflight_sessions.clear()
self.scheduler.shutdown(wait=False)
async def _watch_store(self) -> None:
@@ -1167,11 +1196,109 @@ class ScheduledTaskService:
await self._execute_claimed_request(request)
async def _drain_requests(self) -> None:
+ # Claim eligible pending requests and dispatch each as its own task,
+ # then return immediately. The previous implementation awaited every
+ # execution inline in this loop, so one turn that hung (e.g. an agent
+ # backend that never returns) blocked the loop forever and every
+ # later request piled up in ``queued``. Dispatching concurrently keeps
+ # delivery flowing: a stuck turn only holds up its own session.
for pending in self.request_store.list_pending():
+ if len(self._inflight_executions) >= self._MAX_CONCURRENT_EXECUTIONS:
+ # At capacity — leave the rest queued and retry next tick.
+ # Crucially we never await here, so the loop can't be stalled.
+ break
+ if pending.id in self._inflight_executions:
+ continue
+ lock_key = self._execution_lock_key(pending)
+ if lock_key is not None and lock_key in self._inflight_sessions:
+ # A turn for this conversation is already running; keep this
+ # one queued so we never run two turns for one session at once.
+ # The next drain tick picks it up once the session frees.
+ continue
request = self.request_store.claim(pending.id)
if request is None:
continue
- await self._execute_claimed_request(request)
+ self._spawn_execution(request, lock_key)
+
+ def _execution_lock_key(self, request: TaskExecutionRequest) -> Optional[str]:
+ """Canonical conversation identity for per-session single-flight.
+
+ Resolves task-only and session-id-only requests down to one canonical
+ key so any two requests targeting the same conversation serialize,
+ regardless of which identifier form they carry:
+
+ - ``scheduled``/``task_run`` rows may carry only a ``task_id``; the
+ real target lives on the task definition (mirrors
+ ``_execute_claimed_request``).
+ - a ``session_id`` is resolved to its canonical session key, so it
+ matches a legacy/watch run that only carries that ``session_key``.
+
+ Returns ``None`` for ``create_per_run`` (fresh session each time) and
+ unkeyable requests.
+ """
+ session_policy = request.session_policy
+ session_id = request.session_id
+ session_key = request.session_key
+ task_id = request.task_id
+ if request.request_type in {"task_run", "scheduled"} and task_id:
+ task = self.store.get_task(task_id)
+ if task is not None:
+ session_policy = task.session_policy or session_policy
+ session_id = task.session_id or session_id
+ session_key = task.session_key or session_key
+ if session_policy == "create_per_run":
+ return None
+ if session_id:
+ return self._canonical_session_lock(session_id, session_key)
+ if session_key:
+ return self._normalize_session_key(session_key)
+ if task_id:
+ return f"task:{task_id}"
+ return None
+
+ def _canonical_session_lock(self, session_id: str, session_key: Optional[str]) -> str:
+ cached = self._session_lock_cache.get(session_id)
+ if cached is not None:
+ return cached
+ try:
+ resolved = resolve_session_id_target(session_id)
+ key = f"key:{resolved.session_key.to_key()}"
+ except Exception:
+ # avibe/web sessions (no IM scope) or unresolved ids: fall back to a
+ # carried session key if present, else the id is its own identity.
+ key = self._normalize_session_key(session_key) if session_key else f"sid:{session_id}"
+ self._session_lock_cache[session_id] = key
+ return key
+
+ @staticmethod
+ def _normalize_session_key(session_key: str) -> str:
+ try:
+ return f"key:{parse_session_key(session_key).to_key()}"
+ except Exception:
+ return f"key:{session_key}"
+
+ def _spawn_execution(self, request: TaskExecutionRequest, lock_key: Optional[str]) -> None:
+ if lock_key is not None:
+ self._inflight_sessions.add(lock_key)
+ task = asyncio.create_task(self._execute_claimed_request(request))
+ self._inflight_executions[request.id] = task
+ task.add_done_callback(
+ lambda finished, rid=request.id, key=lock_key: self._on_execution_done(rid, key, finished)
+ )
+
+ def _on_execution_done(
+ self, request_id: str, lock_key: Optional[str], task: "asyncio.Task[Any]"
+ ) -> None:
+ self._inflight_executions.pop(request_id, None)
+ if lock_key is not None:
+ self._inflight_sessions.discard(lock_key)
+ # ``_execute_claimed_request`` already records failures and requeues on
+ # cancellation; this only surfaces unexpected crashes in the wrapper.
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.error("Claimed request %s crashed: %r", request_id, exc, exc_info=exc)
async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:
error: Optional[str] = None
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 939a99d0a..7caf347f2 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -887,12 +887,22 @@ def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:
)
service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)
- try:
- asyncio.run(service._drain_requests())
- except asyncio.CancelledError:
- pass
- else:
- raise AssertionError("expected CancelledError")
+ async def _exercise() -> None:
+ # The drain now dispatches concurrently and returns immediately, so
+ # the CancelledError surfaces on the spawned execution task rather
+ # than out of _drain_requests itself. Awaiting it lets the requeue
+ # path (in _execute_claimed_request) run.
+ await service._drain_requests()
+ execution = service._inflight_executions.get(request.id)
+ assert execution is not None
+ try:
+ await execution
+ except asyncio.CancelledError:
+ pass
+ else:
+ raise AssertionError("expected CancelledError on the execution task")
+
+ asyncio.run(_exercise())
reloaded = ScheduledTaskStore(path)
updated = reloaded.get_task(task.id)
@@ -1242,3 +1252,204 @@ def test_watch_store_does_not_respawn_after_stop(tmp_path: Path) -> None:
assert first_task.cancelled() or first_task.done()
asyncio.run(_exercise())
+
+
+def test_drain_does_not_block_on_hung_execution(tmp_path: Path) -> None:
+ """A turn that never returns must not stall delivery of other sessions.
+
+ Regression for watch follow-up runs piling up in ``queued`` after one
+ execution hung: the drain loop used to await each execution inline.
+ """
+
+ async def _exercise() -> None:
+ store = TaskExecutionStore(tmp_path / "reqs")
+ hung = store.enqueue_hook_send(session_key="slack::channel::A", prompt="hangs")
+ fast = store.enqueue_hook_send(session_key="slack::channel::B", prompt="fast")
+
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=store,
+ )
+
+ started: list[str] = []
+ never = asyncio.Event()
+
+ async def fake_execute(request):
+ started.append(request.id)
+ if request.id == hung.id:
+ await never.wait() # simulate an agent turn that never returns
+ return
+ service.request_store.complete(request, ok=True)
+
+ service._execute_claimed_request = fake_execute # type: ignore[assignment]
+
+ # Should return promptly even though one execution hangs forever.
+ await asyncio.wait_for(service._drain_requests(), timeout=1.0)
+ # Let the fast execution finish.
+ await asyncio.sleep(0.05)
+
+ assert hung.id in started and fast.id in started
+ # Fast session delivered despite the hung one still in flight.
+ assert [item["id"] for item in store.list_runs(status="succeeded")] == [fast.id]
+ assert hung.id in service._inflight_executions
+ assert "key:slack::channel::A" in service._inflight_sessions
+ assert "key:slack::channel::B" not in service._inflight_sessions
+
+ # Cleanup: release the hung task.
+ never.set()
+ hung_task = service._inflight_executions.get(hung.id)
+ if hung_task is not None:
+ await hung_task
+
+ asyncio.run(_exercise())
+
+
+def test_drain_serializes_executions_per_session(tmp_path: Path) -> None:
+ """Two requests for the same session never run concurrently; the second
+ stays queued until the first finishes."""
+
+ async def _exercise() -> None:
+ store = TaskExecutionStore(tmp_path / "reqs")
+ first = store.enqueue_hook_send(session_key="slack::channel::A", prompt="first")
+ second = store.enqueue_hook_send(session_key="slack::channel::A", prompt="second")
+
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=store,
+ )
+
+ started: list[str] = []
+ gate = asyncio.Event()
+
+ async def fake_execute(request):
+ started.append(request.id)
+ await gate.wait()
+ service.request_store.complete(request, ok=True)
+
+ service._execute_claimed_request = fake_execute # type: ignore[assignment]
+
+ await asyncio.wait_for(service._drain_requests(), timeout=1.0)
+ await asyncio.sleep(0.05)
+
+ # Only the first claimed; the second stays queued behind the same session.
+ assert started == [first.id]
+ assert [item["id"] for item in store.list_runs(status="queued")] == [second.id]
+
+ # Release the first; a second drain now picks up the queued one.
+ gate.set()
+ first_task = service._inflight_executions.get(first.id)
+ if first_task is not None:
+ await first_task
+ await asyncio.wait_for(service._drain_requests(), timeout=1.0)
+ await asyncio.sleep(0.05)
+ assert started == [first.id, second.id]
+ second_task = service._inflight_executions.get(second.id)
+ if second_task is not None:
+ await second_task
+
+ asyncio.run(_exercise())
+
+
+def test_drain_serializes_session_id_against_matching_session_key(tmp_path: Path, monkeypatch) -> None:
+ """A session_id-only run must serialize against a key-only run for the
+ same conversation: the session id is resolved to its canonical key before
+ gating (otherwise the disjoint identifiers would run concurrently)."""
+
+ from core.scheduled_tasks import ParsedSessionKey
+
+ def fake_resolve(session_id, *, db_path=None):
+ # Both runs resolve to the same canonical session key.
+ return SimpleNamespace(
+ session_key=ParsedSessionKey(platform="slack", scope_type="channel", scope_id="C123")
+ )
+
+ monkeypatch.setattr("core.scheduled_tasks.resolve_session_id_target", fake_resolve)
+
+ async def _exercise() -> None:
+ store = TaskExecutionStore(tmp_path / "reqs")
+ by_id = store.enqueue_hook_send(session_key="", session_id="sesX", prompt="id only")
+ by_key = store.enqueue_hook_send(session_key="slack::channel::C123", prompt="key only")
+
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=store,
+ )
+
+ started: list[str] = []
+ gate = asyncio.Event()
+
+ async def fake_execute(request):
+ started.append(request.id)
+ await gate.wait()
+ service.request_store.complete(request, ok=True)
+
+ service._execute_claimed_request = fake_execute # type: ignore[assignment]
+
+ await asyncio.wait_for(service._drain_requests(), timeout=1.0)
+ await asyncio.sleep(0.05)
+
+ # session_id run resolves to slack::channel::C123 — same as the key-only
+ # run — so the second is held behind the shared canonical key.
+ assert started == [by_id.id]
+ assert [item["id"] for item in store.list_runs(status="queued")] == [by_key.id]
+
+ gate.set()
+ for run_id in (by_id.id, by_key.id):
+ task = service._inflight_executions.get(run_id)
+ if task is not None:
+ await task
+
+ asyncio.run(_exercise())
+
+
+def test_drain_serializes_task_only_scheduled_runs(tmp_path: Path) -> None:
+ """Scheduled runs that carry only a task_id resolve their target off the
+ task definition before gating, so two runs for the same task/session do
+ not run concurrently."""
+
+ async def _exercise() -> None:
+ task_store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = task_store.add_task(
+ session_key="slack::channel::D",
+ prompt="digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+ store = TaskExecutionStore(tmp_path / "reqs")
+ # Task-only requests: no session_id/session_key, just the task_id.
+ first = store.enqueue_task_run(task.id)
+ second = store.enqueue_task_run(task.id)
+
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(controller=controller, store=task_store, request_store=store)
+
+ started: list[str] = []
+ gate = asyncio.Event()
+
+ async def fake_execute(request):
+ started.append(request.id)
+ await gate.wait()
+ service.request_store.complete(request, ok=True)
+
+ service._execute_claimed_request = fake_execute # type: ignore[assignment]
+
+ await asyncio.wait_for(service._drain_requests(), timeout=1.0)
+ await asyncio.sleep(0.05)
+
+ assert started == [first.id]
+ assert [item["id"] for item in store.list_runs(status="queued")] == [second.id]
+
+ gate.set()
+ for run_id in (first.id, second.id):
+ t = service._inflight_executions.get(run_id)
+ if t is not None:
+ await t
+
+ asyncio.run(_exercise())