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.

feat(runtime): supervise Harness work lanes (#1173)

Call White4a892fd67bd8
diff --git a/core/controller.py b/core/controller.py
index 081d8b905..e4d9ab2a3 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -195,6 +195,7 @@ class Controller:
self._im_run_exception: Optional[BaseException] = None
self._shutdown_requested = False
self._shutdown_task: asyncio.Task[None] | None = None
+ self._runtime_work_shutdown_task: asyncio.Task[None] | None = None
self._shutdown_tainted = False
self._service_lock_safe_to_release = False
self._runtime_work_shutdown_grace_seconds = (
@@ -241,7 +242,9 @@ class Controller:
self.runtime_ownership = RuntimeOwnershipProvider(
self.session_turns._sqlite_engine()
)
- self.runtime_work_supervisor = RuntimeWorkSupervisor()
+ self.runtime_work_supervisor = RuntimeWorkSupervisor(
+ on_lease_lost=lambda: self.request_shutdown("service lease lost")
+ )
self._runtime_work_tokens = [
self.runtime_work_supervisor.register(
RuntimeWorkLane.SESSION_DELIVERIES,
@@ -283,6 +286,9 @@ class Controller:
# Consolidated message dispatcher
self.message_dispatcher = ConsolidatedMessageDispatcher(self)
self.scheduled_task_service = ScheduledTaskService(self)
+ self._runtime_work_tokens.extend(
+ self.scheduled_task_service.register_controller_runtime_work_lanes()
+ )
self.watch_service = ManagedWatchService(self)
self.runtime_command_watcher = RuntimeCommandWatcher(self)
self.show_git_checkpoint_service = ShowGitCheckpointService()
@@ -1607,33 +1613,27 @@ class Controller:
"""Join passive recovery owners before allowing the loop to stop."""
logger.info("Controller shutdown started: %s", reason)
- supervisor = getattr(self, "runtime_work_supervisor", None)
- stop_supervisor = getattr(supervisor, "stop", None)
try:
- if callable(stop_supervisor):
- stop_task = asyncio.create_task(
- stop_supervisor(),
- name="controller-runtime-work-stop",
- )
- grace = max(
- 0.0,
- float(
- getattr(
- self,
- "_runtime_work_shutdown_grace_seconds",
- _RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS,
- )
- ),
- )
- done, _ = await asyncio.wait({stop_task}, timeout=grace)
- if not done:
- self._shutdown_tainted = True
- logger.critical(
- "Runtime work shutdown exceeded %.1fs; retaining the "
- "service lease until exact workers join",
- grace,
+ stop_task = self._begin_runtime_work_stack_shutdown()
+ grace = max(
+ 0.0,
+ float(
+ getattr(
+ self,
+ "_runtime_work_shutdown_grace_seconds",
+ _RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS,
)
- await asyncio.shield(stop_task)
+ ),
+ )
+ done, _ = await asyncio.wait({stop_task}, timeout=grace)
+ if not done:
+ self._shutdown_tainted = True
+ logger.critical(
+ "Runtime work shutdown exceeded %.1fs; retaining the "
+ "service lease until exact workers join",
+ grace,
+ )
+ await asyncio.shield(stop_task)
except Exception:
self._shutdown_tainted = True
logger.exception("Controller shutdown could not join runtime work")
@@ -1642,6 +1642,81 @@ class Controller:
if loop is not None and loop.is_running():
loop.call_soon(loop.stop)
+ def _begin_runtime_work_stack_shutdown(self) -> asyncio.Task[None]:
+ task = getattr(self, "_runtime_work_shutdown_task", None)
+ if task is None:
+ task = asyncio.create_task(
+ self._stop_runtime_work_stack(),
+ name="controller-runtime-work-stack-stop",
+ )
+ self._runtime_work_shutdown_task = task
+ return task
+
+ async def _join_runtime_work_stack_shutdown(self) -> None:
+ await asyncio.shield(self._begin_runtime_work_stack_shutdown())
+
+ async def _stop_runtime_work_stack(self) -> None:
+ """Stop lane consumers before disposing their shared executor."""
+
+ supervisor = getattr(self, "runtime_work_supervisor", None)
+ quiesce = getattr(supervisor, "quiesce", None)
+ if callable(quiesce):
+ quiesce()
+
+ # Controller-generation lanes can still be finishing work after
+ # quiesce. Join them before ScheduledTaskService releases durable Turn
+ # owners; otherwise a delivery-recovery worker can admit a new Turn
+ # immediately after the final owner snapshot.
+ controller_tokens = tuple(getattr(self, "_runtime_work_tokens", ()))
+ if controller_tokens:
+ begin_unregister = getattr(supervisor, "begin_unregister", None)
+ if not callable(begin_unregister):
+ self._shutdown_tainted = True
+ raise RuntimeError(
+ "runtime work supervisor cannot join controller lanes"
+ )
+ controller_lane_joins = [
+ begin_unregister(token) for token in controller_tokens
+ ]
+ self._runtime_work_tokens = []
+ controller_results = await asyncio.gather(
+ *controller_lane_joins,
+ return_exceptions=True,
+ )
+ controller_errors = [
+ result
+ for result in controller_results
+ if isinstance(result, BaseException)
+ ]
+ if controller_errors:
+ self._shutdown_tainted = True
+ raise RuntimeError(
+ "controller runtime work lane shutdown failed"
+ ) from controller_errors[0]
+
+ service_stops: list[asyncio.Task[None]] = []
+ for service_name in ("scheduled_task_service", "watch_service"):
+ service = getattr(self, service_name, None)
+ stop = getattr(service, "stop", None)
+ if callable(stop):
+ service_stops.append(
+ asyncio.create_task(
+ stop(),
+ name=f"controller-{service_name}-stop",
+ )
+ )
+ results = await asyncio.gather(*service_stops, return_exceptions=True)
+ errors = [result for result in results if isinstance(result, BaseException)]
+ stop_supervisor = getattr(supervisor, "stop", None)
+ if callable(stop_supervisor):
+ try:
+ await stop_supervisor()
+ except BaseException as exc: # noqa: BLE001
+ errors.append(exc)
+ if errors:
+ self._shutdown_tainted = True
+ raise RuntimeError("runtime work stack shutdown failed") from errors[0]
+
def run(self):
"""Run the controller"""
logger.info("Starting Claude Proxy Controller with platforms: %s", ", ".join(self.enabled_platforms))
@@ -1794,12 +1869,10 @@ class Controller:
self.cleanup_task = None
_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")
- _stop_loop_coroutine(self.scheduled_task_service.stop(), "Scheduled task service")
- supervisor = getattr(self, "runtime_work_supervisor", None)
- stop_supervisor = getattr(supervisor, "stop", None)
- if callable(stop_supervisor):
- _stop_loop_coroutine(stop_supervisor(), "Runtime work supervisor")
- _stop_loop_coroutine(self.watch_service.stop(), "Watch service")
+ _stop_loop_coroutine(
+ self._join_runtime_work_stack_shutdown(),
+ "Runtime work stack",
+ )
_stop_loop_coroutine(self.runtime_command_watcher.stop(), "Runtime command watcher")
model_hub_turn_gateway = getattr(self, "model_hub_turn_gateway", None)
if model_hub_turn_gateway is not None:
diff --git a/core/inbox_events.py b/core/inbox_events.py
index fc21bcd0a..84ebc39fc 100644
--- a/core/inbox_events.py
+++ b/core/inbox_events.py
@@ -22,6 +22,7 @@ logger = logging.getLogger(__name__)
RUNS_UPDATED_EVENT = "runs.updated"
VAULTS_UPDATED_EVENT = "vaults.updated"
QUEUE_UPDATED_EVENT = "queue.updated"
+DEFINITIONS_UPDATED_EVENT = "definitions.updated"
WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT = "workbench.events.bridge.status"
_CONTROLLER_PROCESS = False
@@ -157,3 +158,22 @@ def vaults_updated_payload(
def publish_run_updated(**kwargs: Any) -> None:
bus.publish(RUNS_UPDATED_EVENT, run_updated_payload(**kwargs))
+
+
+def publish_definitions_updated(*, definition_type: str) -> None:
+ """Publish a payload-free scheduling hint after a definition commit."""
+
+ payload = {"definition_type": str(definition_type or "")}
+ bus.publish(DEFINITIONS_UPDATED_EVENT, payload)
+ if is_controller_process():
+ return
+ try:
+ from vibe import internal_client
+
+ internal_client.publish_event_sync(
+ DEFINITIONS_UPDATED_EVENT,
+ payload,
+ timeout=1.5,
+ )
+ except Exception:
+ logger.debug("definitions.updated bridge publish failed", exc_info=True)
diff --git a/core/internal_server.py b/core/internal_server.py
index 3a2655fb2..084b236ca 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -785,6 +785,7 @@ def create_app(controller: "Controller") -> FastAPI:
same Controller -> UI-server -> browser SSE path.
"""
from core.inbox_events import (
+ DEFINITIONS_UPDATED_EVENT,
QUEUE_UPDATED_EVENT,
RUNS_UPDATED_EVENT,
VAULTS_UPDATED_EVENT,
@@ -797,6 +798,7 @@ def create_app(controller: "Controller") -> FastAPI:
event_type = str(payload.get("type") or "").strip()
data = payload.get("data")
if event_type not in {
+ DEFINITIONS_UPDATED_EVENT,
QUEUE_UPDATED_EVENT,
RUNS_UPDATED_EVENT,
VAULTS_UPDATED_EVENT,
diff --git a/core/runtime_recovery.py b/core/runtime_recovery.py
index b0c527af7..17e28f0a0 100644
--- a/core/runtime_recovery.py
+++ b/core/runtime_recovery.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Callable
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from core.runtime_work import RuntimeWorkItem
@@ -48,9 +48,13 @@ class FallbackRequestRecoveryHandler:
store: "SQLiteBackgroundTaskStore",
*,
live_claims: Callable[[], frozenset[str]] | None = None,
+ partition_key: Callable[[dict[str, Any]], str] | None = None,
) -> None:
self.store = store
self._live_claims = live_claims or frozenset
+ self._partition_key = partition_key or (
+ lambda row: str(row["id"])
+ )
def scan(
self,
@@ -62,20 +66,28 @@ class FallbackRequestRecoveryHandler:
live_claims = self._live_claims()
rows, has_more = self.store.scan_claimed_pre_execution_runs(
limit=limit,
- occupied=occupied | live_claims,
+ # Store exclusion is by Run id. Supervisor occupancy is by the
+ # canonical execution partition and is applied after mapping below.
+ occupied=live_claims,
cursor=cursor,
)
return [
- RuntimeWorkItem(str(row["id"]), row)
+ RuntimeWorkItem(
+ self._partition_key(row),
+ row,
+ cursor_key=str(row["id"]),
+ )
for row in rows
], has_more
async def process(self, item: RuntimeWorkItem) -> bool:
+ return await asyncio.to_thread(self.process_sync, item)
+
+ def process_sync(self, item: RuntimeWorkItem) -> bool:
row = item.observation
if str(row["id"]) in self._live_claims():
return True
- return await asyncio.to_thread(
- self.store.recover_claimed_pre_execution_run,
+ return self.store.recover_claimed_pre_execution_run(
run_id=str(row["id"]),
expected_status=str(row["status"]),
expected_updated_at=str(row["updated_at"]),
diff --git a/core/runtime_work.py b/core/runtime_work.py
index 5086302ab..47219d6d4 100644
--- a/core/runtime_work.py
+++ b/core/runtime_work.py
@@ -5,20 +5,33 @@ from __future__ import annotations
import asyncio
import logging
import threading
+import time
from collections.abc import Awaitable, Callable
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Protocol
-
-from core.inbox_events import QUEUE_UPDATED_EVENT, RUNS_UPDATED_EVENT, bus
+from functools import partial
+from typing import Any, Protocol, TypeVar
+
+from core.inbox_events import (
+ DEFINITIONS_UPDATED_EVENT,
+ QUEUE_UPDATED_EVENT,
+ RUNS_UPDATED_EVENT,
+ VAULTS_UPDATED_EVENT,
+ bus,
+)
from vibe import runtime
logger = logging.getLogger(__name__)
+_T = TypeVar("_T")
+
_DEFAULT_RECONCILE_INTERVAL_SECONDS = 30.0
_DEFAULT_LANE_CAPACITY = 4
_DEFAULT_SCAN_PAGE_SIZE = 32
+_DEFAULT_SCAN_CONTINUATION_PAGES = 8
_DEFAULT_RETRY_BACKOFF_SECONDS = 1.0
+_DEFAULT_OVERDUE_SECONDS = 30.0
class RuntimeWorkLane(str, Enum):
@@ -37,6 +50,10 @@ class RuntimeWorkLane(str, Enum):
class RuntimeWorkItem:
partition_key: str
observation: Any
+ cursor_key: str | None = None
+ rearm_after_process: bool = True
+ defer_until_partition_release: bool = False
+ cursor_only: bool = False
class RuntimeWorkHandler(Protocol):
@@ -69,15 +86,33 @@ class _Registration:
handler: RuntimeWorkHandler
event: asyncio.Event = field(default_factory=asyncio.Event)
coordinator: asyncio.Task[None] | None = None
- workers: dict[str, asyncio.Task[None]] = field(default_factory=dict)
+ workers: dict[str, asyncio.Task[Any]] = field(default_factory=dict)
+ worker_started_at: dict[str, float] = field(default_factory=dict)
+ backoff_deadlines: dict[str, float] = field(default_factory=dict)
+ backoff_task: asyncio.Task[None] | None = None
+ expired_backoff_rewind_pending: bool = False
+ scan_continuation_task: asyncio.Task[None] | None = None
+ rewind_after_partitions: set[str] = field(default_factory=set)
+ scan_started_at: float | None = None
scan_cursor: str | None = None
+ rewind_requested: bool = False
unregister_task: asyncio.Task[None] | None = None
live: bool = True
_EVENT_LANES = {
QUEUE_UPDATED_EVENT: (RuntimeWorkLane.SESSION_DELIVERIES,),
- RUNS_UPDATED_EVENT: (RuntimeWorkLane.REQUESTS,),
+ RUNS_UPDATED_EVENT: (
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ RuntimeWorkLane.STALE_RUNS,
+ ),
+ VAULTS_UPDATED_EVENT: (RuntimeWorkLane.VAULT_CALLBACKS,),
+ DEFINITIONS_UPDATED_EVENT: (
+ RuntimeWorkLane.TASK_DEFINITIONS,
+ RuntimeWorkLane.WATCH_DEFINITIONS,
+ ),
}
@@ -90,33 +125,59 @@ class RuntimeWorkSupervisor:
reconcile_interval: float = _DEFAULT_RECONCILE_INTERVAL_SECONDS,
lane_capacity: int = _DEFAULT_LANE_CAPACITY,
scan_page_size: int = _DEFAULT_SCAN_PAGE_SIZE,
+ scan_continuation_pages: int = _DEFAULT_SCAN_CONTINUATION_PAGES,
retry_backoff: float = _DEFAULT_RETRY_BACKOFF_SECONDS,
retry_wait: Callable[[float], Awaitable[None]] | None = None,
reconcile_wait: Callable[[float], Awaitable[None]] | None = None,
+ overdue_seconds: float = _DEFAULT_OVERDUE_SECONDS,
+ monotonic: Callable[[], float] = time.monotonic,
+ on_lease_lost: Callable[[], None] | None = None,
) -> None:
self._reconcile_interval = max(0.001, float(reconcile_interval))
self._lane_capacity = max(1, int(lane_capacity))
self._scan_page_size = max(1, int(scan_page_size))
+ self._scan_continuation_pages = max(1, int(scan_continuation_pages))
+ self._backoff_partition_limit = (
+ min(self._lane_capacity, self._scan_page_size)
+ * self._scan_continuation_pages
+ )
self._retry_backoff = max(0.001, float(retry_backoff))
self._retry_wait = retry_wait or asyncio.sleep
self._reconcile_wait = reconcile_wait or asyncio.sleep
+ self._overdue_seconds = max(0.001, float(overdue_seconds))
+ self._monotonic = monotonic
+ self._on_lease_lost = on_lease_lost
self._registrations: dict[RuntimeWorkLane, _Registration] = {}
self._generations: dict[RuntimeWorkLane, int] = {}
self._loop: asyncio.AbstractEventLoop | None = None
self._active = False
+ self._quiescing = False
self._stopping = False
self._subscription_id: int | None = None
self._reconcile_task: asyncio.Task[None] | None = None
self._stop_task: asyncio.Task[None] | None = None
+ self._delayed_wakes: dict[
+ RuntimeWorkRegistrationToken,
+ asyncio.TimerHandle,
+ ] = {}
self._pending_lock = threading.Lock()
self._pending_lanes: set[RuntimeWorkLane] = set()
+ self._pending_rewinds: set[RuntimeWorkLane] = set()
self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
+ self._sync_executor = ThreadPoolExecutor(
+ max_workers=max(8, self._lane_capacity * len(RuntimeWorkLane)),
+ thread_name_prefix="runtime-work",
+ )
+ self._sync_futures: set[asyncio.Future[Any]] = set()
+ self._sync_executor_stopped = False
def register(
self,
lane: RuntimeWorkLane,
handler: RuntimeWorkHandler,
) -> RuntimeWorkRegistrationToken:
+ if self._quiescing or self._stopping:
+ raise RuntimeError("runtime work supervisor is stopping")
existing = self._registrations.get(lane)
if existing is not None:
raise RuntimeError(f"runtime work lane already registered: {lane.value}")
@@ -148,6 +209,9 @@ class RuntimeWorkSupervisor:
# longer re-arm this lane or a later replacement registration.
registration.live = False
registration.event.set()
+ delayed = self._delayed_wakes.pop(token, None)
+ if delayed is not None:
+ delayed.cancel()
registration.unregister_task = asyncio.create_task(
self._finish_unregister(registration),
name=f"runtime-work-unregister:{token.lane.value}",
@@ -161,6 +225,15 @@ class RuntimeWorkSupervisor:
workers = tuple(registration.workers.values())
if workers:
await asyncio.gather(*workers, return_exceptions=True)
+ backoff = registration.backoff_task
+ if backoff is not None:
+ backoff.cancel()
+ await asyncio.gather(backoff, return_exceptions=True)
+ registration.backoff_deadlines.clear()
+ continuation = registration.scan_continuation_task
+ if continuation is not None:
+ continuation.cancel()
+ await asyncio.gather(continuation, return_exceptions=True)
if self._registrations.get(registration.token.lane) is registration:
self._registrations.pop(registration.token.lane, None)
@@ -169,6 +242,8 @@ class RuntimeWorkSupervisor:
return
if self._stopping:
raise RuntimeError("runtime work supervisor is stopping")
+ if self._quiescing:
+ raise RuntimeError("runtime work supervisor is quiescing")
self._loop = asyncio.get_running_loop()
self._active = True
self._subscription_id = bus.subscribe_callback(self._on_bus_event)
@@ -177,48 +252,294 @@ class RuntimeWorkSupervisor:
registration.event.set()
with self._pending_lock:
pending = tuple(self._pending_lanes)
+ rewinds = tuple(self._pending_rewinds)
self._pending_lanes.clear()
+ self._pending_rewinds.clear()
self._notify_on_loop(pending)
+ self._notify_on_loop(rewinds, True)
self._reconcile_task = asyncio.create_task(
self._reconcile_loop(),
name="runtime-work-reconcile",
)
- def notify(self, *lanes: RuntimeWorkLane) -> None:
+ def notify(
+ self,
+ *lanes: RuntimeWorkLane,
+ reset_cursor: bool = False,
+ ) -> None:
if not lanes:
return
+ if self._quiescing or self._stopping:
+ return
loop = self._loop
if not self._active or loop is None or loop.is_closed():
with self._pending_lock:
self._pending_lanes.update(lanes)
+ if reset_cursor:
+ self._pending_rewinds.update(lanes)
return
try:
current = asyncio.get_running_loop()
except RuntimeError:
current = None
if current is loop:
- self._notify_on_loop(lanes)
+ self._notify_on_loop(lanes, reset_cursor)
return
try:
- loop.call_soon_threadsafe(self._notify_on_loop, tuple(lanes))
+ loop.call_soon_threadsafe(
+ self._notify_on_loop,
+ tuple(lanes),
+ reset_cursor,
+ )
except RuntimeError:
# A closing generation may lose a hint; the next controller's
# startup reconciliation is the durable recovery boundary.
pass
+ def notify_after(
+ self,
+ token: RuntimeWorkRegistrationToken,
+ delay: float,
+ ) -> None:
+ """Coalesce a generation-scoped future eligibility wake."""
+
+ loop = self._loop
+ if not self._active or loop is None or loop.is_closed():
+ return
+ bounded_delay = max(0.0, float(delay))
+ try:
+ current = asyncio.get_running_loop()
+ except RuntimeError:
+ current = None
+ if current is loop:
+ self._notify_after_on_loop(token, bounded_delay)
+ return
+ try:
+ loop.call_soon_threadsafe(
+ self._notify_after_on_loop,
+ token,
+ bounded_delay,
+ )
+ except RuntimeError:
+ pass
+
+ def _notify_after_on_loop(
+ self,
+ token: RuntimeWorkRegistrationToken,
+ delay: float,
+ ) -> None:
+ registration = self._registrations.get(token.lane)
+ if (
+ registration is None
+ or registration.token != token
+ or not registration.live
+ or not self._active
+ or self._stopping
+ ):
+ return
+ if delay <= 0:
+ registration.event.set()
+ return
+ loop = self._loop
+ if loop is None:
+ return
+ deadline = loop.time() + delay
+ existing = self._delayed_wakes.get(token)
+ if existing is not None and not existing.cancelled():
+ if existing.when() <= deadline:
+ return
+ existing.cancel()
+ self._delayed_wakes[token] = loop.call_at(
+ deadline,
+ self._fire_delayed_wake,
+ token,
+ )
+
+ def _fire_delayed_wake(self, token: RuntimeWorkRegistrationToken) -> None:
+ self._delayed_wakes.pop(token, None)
+ registration = self._registrations.get(token.lane)
+ if (
+ registration is not None
+ and registration.token == token
+ and registration.live
+ and self._active
+ and not self._stopping
+ ):
+ registration.rewind_requested = True
+ registration.event.set()
+
+ async def run_in_partition(
+ self,
+ lane: RuntimeWorkLane,
+ partition_key: str,
+ operation: Callable[[], Awaitable[_T]],
+ ) -> _T:
+ """Run a live domain owner under the same lease as recovered work.
+
+ Activity output has both a live consumer and a restart consumer. The
+ durable Registry remains authoritative; this lease only prevents those
+ two consumers from claiming or emitting for one runtime concurrently.
+ """
+
+ partition = str(partition_key or "").strip()
+ registration = self._registrations.get(lane)
+ loop = self._loop
+ if not partition:
+ return await operation()
+ if self._quiescing or self._stopping:
+ raise RuntimeError("runtime work partition is stopping")
+ if registration is None:
+ if self._active:
+ raise RuntimeError("runtime work partition is unavailable")
+ return await operation()
+ if not registration.live:
+ raise RuntimeError("runtime work partition is stopping")
+ if not self._active or loop is None:
+ return await operation()
+ if asyncio.get_running_loop() is not loop:
+ raise RuntimeError("runtime work partitions belong to the controller loop")
+
+ current = asyncio.current_task()
+ assert current is not None
+ owner_task: asyncio.Task[_T] | None = None
+ while True:
+ self._require_live_partition_admission(registration)
+ owner = registration.workers.get(partition)
+ if owner is current:
+ return await operation()
+ if owner is None:
+ owner_task = asyncio.create_task(
+ operation(),
+ name=f"runtime-work-live:{lane.value}:{partition}",
+ )
+ registration.workers[partition] = owner_task
+ registration.worker_started_at[partition] = self._monotonic()
+ owner_task.add_done_callback(
+ partial(
+ self._release_live_partition,
+ registration,
+ partition,
+ )
+ )
+ break
+ await asyncio.gather(asyncio.shield(owner), return_exceptions=True)
+ if owner.done() and registration.workers.get(partition) is owner:
+ registration.workers.pop(partition, None)
+ registration.worker_started_at.pop(partition, None)
+ self._rewind_after_partition_release(registration, partition)
+
+ assert owner_task is not None
+ return await asyncio.shield(owner_task)
+
+ def _require_live_partition_admission(
+ self,
+ registration: _Registration,
+ ) -> None:
+ if (
+ not registration.live
+ or not self._active
+ or self._quiescing
+ or self._stopping
+ ):
+ raise RuntimeError("runtime work partition is stopping")
+ if not self._owns_service_instance():
+ self._stop_for_lost_lease()
+ raise RuntimeError("runtime work partition is stopping")
+
+ def _release_live_partition(
+ self,
+ registration: _Registration,
+ partition: str,
+ owner: asyncio.Task[Any],
+ ) -> None:
+ if registration.workers.get(partition) is owner:
+ registration.workers.pop(partition, None)
+ registration.worker_started_at.pop(partition, None)
+ self._rewind_after_partition_release(registration, partition)
+ if registration.live and self._active and not self._stopping:
+ registration.event.set()
+
+ @staticmethod
+ def _rewind_after_partition_release(
+ registration: _Registration,
+ partition: str,
+ ) -> None:
+ if partition not in registration.rewind_after_partitions:
+ return
+ registration.rewind_after_partitions.remove(partition)
+ if registration.live:
+ registration.rewind_requested = True
+ registration.event.set()
+
+ async def run_sync(self, operation: Callable[[], _T]) -> _T:
+ """Run blocking store work without abandoning its exact worker future."""
+
+ if self._stopping or self._sync_executor_stopped:
+ raise RuntimeError("runtime work executor is stopped")
+ loop = asyncio.get_running_loop()
+ future = loop.run_in_executor(self._sync_executor, operation)
+ self._sync_futures.add(future)
+ cancelled = False
+ try:
+ while True:
+ try:
+ result = await asyncio.shield(future)
+ break
+ except asyncio.CancelledError:
+ # Python threads are not safely cancellable. Consume every
+ # cancellation until the exact store operation exits; the
+ # partition task remains the owner throughout.
+ cancelled = True
+ if cancelled:
+ raise asyncio.CancelledError
+ return result
+ finally:
+ if future.done():
+ self._sync_futures.discard(future)
+
async def stop(self) -> None:
+ stop_task = self._begin_stop()
+ await asyncio.shield(stop_task)
+
+ def quiesce(self) -> None:
+ """Stop new admission while retaining executor-backed finalization."""
+
+ if self._quiescing or self._stopping:
+ return
+ self._quiescing = True
+ self._active = False
+ for registration in self._registrations.values():
+ registration.event.set()
+
+ def _begin_stop(self) -> asyncio.Task[None]:
if self._stop_task is None:
self._stop_task = asyncio.create_task(
self._stop_and_join(),
name="runtime-work-stop",
)
- await asyncio.shield(self._stop_task)
+ return self._stop_task
+
+ def _stop_for_lost_lease(self) -> None:
+ if self._quiescing or self._stopping or self._stop_task is not None:
+ return
+ logger.error(
+ "Runtime work supervisor stopping because this process no longer "
+ "owns the service lock"
+ )
+ self.quiesce()
+ if self._on_lease_lost is not None:
+ self._on_lease_lost()
+ return
+ self._begin_stop()
async def _stop_and_join(self) -> None:
if self._stopping:
return
+ self.quiesce()
self._stopping = True
- self._active = False
+ for handle in self._delayed_wakes.values():
+ handle.cancel()
+ self._delayed_wakes.clear()
if self._subscription_id is not None:
bus.unsubscribe(self._subscription_id)
self._subscription_id = None
@@ -230,6 +551,18 @@ class RuntimeWorkSupervisor:
tokens = [registration.token for registration in self._registrations.values()]
for token in tokens:
await self.unregister(token)
+ remaining = tuple(self._sync_futures)
+ if remaining:
+ await asyncio.gather(
+ *(asyncio.shield(future) for future in remaining),
+ return_exceptions=True,
+ )
+ self._sync_executor_stopped = True
+ await asyncio.to_thread(
+ self._sync_executor.shutdown,
+ wait=True,
+ cancel_futures=False,
+ )
self._loop = None
def _start_registration(self, registration: _Registration) -> None:
@@ -252,12 +585,18 @@ class RuntimeWorkSupervisor:
except RuntimeError:
pass
- def _notify_on_loop(self, lanes: tuple[RuntimeWorkLane, ...] | list[RuntimeWorkLane]) -> None:
+ def _notify_on_loop(
+ self,
+ lanes: tuple[RuntimeWorkLane, ...] | list[RuntimeWorkLane],
+ reset_cursor: bool = False,
+ ) -> None:
if not self._active or self._stopping:
return
for lane in lanes:
registration = self._registrations.get(lane)
if registration is not None and registration.live:
+ if reset_cursor:
+ registration.rewind_requested = True
registration.event.set()
def _owns_service_instance(self) -> bool:
@@ -270,55 +609,159 @@ class RuntimeWorkSupervisor:
while registration.live and not self._stopping:
await registration.event.wait()
registration.event.clear()
- if (
- not registration.live
- or self._stopping
- or not self._active
- or not self._owns_service_instance()
- ):
- continue
- capacity = self._lane_capacity - len(registration.workers)
- if capacity <= 0:
- continue
- occupied = frozenset(registration.workers)
- try:
- items, has_more = await asyncio.to_thread(
- registration.handler.scan,
- limit=min(capacity, self._scan_page_size),
- occupied=occupied,
- cursor=registration.scan_cursor,
+ pages_remaining = self._scan_continuation_pages
+ while pages_remaining > 0:
+ if (
+ not registration.live
+ or self._stopping
+ or not self._active
+ ):
+ break
+ if not self._owns_service_instance():
+ self._stop_for_lost_lease()
+ return
+ # Every admitted worker reserves room for its exact partition in
+ # the bounded backoff ledger. Once that ledger is full, wait for an
+ # existing deadline instead of accepting failures whose identity
+ # could not be retained safely.
+ capacity = min(
+ self._lane_capacity - len(registration.workers),
+ self._backoff_partition_limit
+ - len(registration.backoff_deadlines)
+ - len(registration.workers),
)
- except Exception:
- logger.exception(
- "Runtime work scan failed for lane=%s generation=%s",
- registration.token.lane.value,
- registration.token.generation,
+ if capacity <= 0:
+ break
+ occupied = frozenset(
+ (*registration.workers, *registration.backoff_deadlines)
)
- continue
- if not registration.live or self._stopping or not self._owns_service_instance():
- continue
- if items:
- last_partition = str(items[-1].partition_key or "").strip()
- if last_partition:
- registration.scan_cursor = last_partition
- elif registration.scan_cursor is not None:
- # The durable keyset reached its end. Wrap exactly once so old
- # stale observations can be retried without pinning later keys.
- registration.scan_cursor = None
- registration.event.set()
- for item in items:
- partition = str(item.partition_key or "").strip()
- if not partition or partition in registration.workers:
- continue
- task = asyncio.create_task(
- self._run_item(registration, item),
- name=(
- f"runtime-work:{registration.token.lane.value}:"
- f"{partition}"
- ),
+ scan_cursor = (
+ None if registration.rewind_requested else registration.scan_cursor
)
- registration.workers[partition] = task
- if has_more and len(registration.workers) < self._lane_capacity:
+ registration.rewind_requested = False
+ try:
+ registration.scan_started_at = self._monotonic()
+ try:
+ items, has_more = await self.run_sync(
+ partial(
+ registration.handler.scan,
+ limit=min(capacity, self._scan_page_size),
+ occupied=occupied,
+ cursor=scan_cursor,
+ )
+ )
+ finally:
+ registration.scan_started_at = None
+ except Exception:
+ logger.exception(
+ "Runtime work scan failed for lane=%s generation=%s",
+ registration.token.lane.value,
+ registration.token.generation,
+ )
+ if registration.live and not self._stopping:
+ await self._retry_wait(self._retry_backoff)
+ if registration.live and self._active and not self._stopping:
+ registration.event.set()
+ break
+ if not registration.live or self._stopping:
+ break
+ if not self._owns_service_instance():
+ self._stop_for_lost_lease()
+ return
+ page_advanced = False
+ if items:
+ last_cursor = str(
+ items[-1].cursor_key or items[-1].partition_key or ""
+ ).strip()
+ if last_cursor:
+ page_advanced = last_cursor != scan_cursor
+ registration.scan_cursor = last_cursor
+ elif registration.scan_cursor is not None and not has_more:
+ # Reset for the next real wake. Immediately scanning from the
+ # beginning would spin on occupied rows until their owner exits.
+ registration.scan_cursor = None
+ for item in items:
+ if item.cursor_only:
+ continue
+ partition = str(item.partition_key or "").strip()
+ if not partition:
+ continue
+ if item.defer_until_partition_release:
+ # Some scans return an occupied partition only to preserve a
+ # wake until its current owner exits. The owner can finish
+ # between the off-loop scan and admission here; in that case
+ # rewind immediately instead of executing a placeholder with
+ # no durable observation.
+ if partition in registration.workers:
+ registration.rewind_after_partitions.add(partition)
+ else:
+ registration.rewind_requested = True
+ registration.event.set()
+ continue
+ if partition in registration.workers:
+ # Row ordering can be finer-grained than the execution
+ # partition. Preserve the skipped durable observation
+ # without polling its still-live owner.
+ registration.rewind_after_partitions.add(partition)
+ continue
+ if partition in registration.backoff_deadlines:
+ continue
+ task = asyncio.create_task(
+ self._run_item(registration, item),
+ name=(
+ f"runtime-work:{registration.token.lane.value}:"
+ f"{partition}"
+ ),
+ )
+ registration.workers[partition] = task
+ registration.worker_started_at[partition] = self._monotonic()
+ if not has_more and registration.expired_backoff_rewind_pending:
+ # A retry deadline releases admission capacity but must not pull
+ # the forward cursor back over the same unavailable prefix. Finish
+ # the current durable scan first, then coalesce all expired retries
+ # into one bounded rewind. The store remains the retry inventory.
+ registration.expired_backoff_rewind_pending = False
+ registration.rewind_requested = True
+ if not registration.workers:
+ registration.event.set()
+ if not has_more or len(registration.workers) >= self._lane_capacity:
+ break
+ if not page_advanced:
+ # A broken/non-keyset handler cannot advance itself. A later
+ # durable wake or reconciliation can retry without a hot loop.
+ break
+ # Continue synchronously only while this wake's bounded raw-page
+ # budget remains. Partition admission may be coarser than the
+ # durable row cursor, so occupied duplicates must not hide a
+ # later partition, but they also must not create an unbounded
+ # same-tick scan loop.
+ pages_remaining -= 1
+ if pages_remaining <= 0:
+ self._start_scan_continuation(registration)
+ break
+
+ def _start_scan_continuation(self, registration: _Registration) -> None:
+ existing = registration.scan_continuation_task
+ if existing is not None and not existing.done():
+ return
+ registration.scan_continuation_task = asyncio.create_task(
+ self._finish_scan_continuation(registration),
+ name=(
+ f"runtime-work-scan-continuation:"
+ f"{registration.token.lane.value}"
+ ),
+ )
+
+ async def _finish_scan_continuation(
+ self,
+ registration: _Registration,
+ ) -> None:
+ try:
+ await self._retry_wait(self._retry_backoff)
+ finally:
+ if registration.scan_continuation_task is asyncio.current_task():
+ registration.scan_continuation_task = None
+ if registration.live and self._active and not self._stopping:
registration.event.set()
async def _run_item(
@@ -332,6 +775,8 @@ class RuntimeWorkSupervisor:
if registration.live and self._owns_service_instance():
processed = await registration.handler.process(item)
should_backoff = processed is False
+ elif registration.live:
+ self._stop_for_lost_lease()
except asyncio.CancelledError:
raise
except Exception:
@@ -343,20 +788,131 @@ class RuntimeWorkSupervisor:
registration.token.generation,
)
finally:
- try:
- if should_backoff and registration.live and not self._stopping:
- await self._retry_wait(self._retry_backoff)
- finally:
- current = registration.workers.get(partition)
- if current is asyncio.current_task():
- registration.workers.pop(partition, None)
- if registration.live and self._active and not self._stopping:
- registration.event.set()
+ current = registration.workers.get(partition)
+ if current is asyncio.current_task():
+ registration.workers.pop(partition, None)
+ registration.worker_started_at.pop(partition, None)
+ if should_backoff:
+ # Backoff completion already owns the retry rewind. Do not
+ # race it with an immediate scan of the guarded partition.
+ registration.rewind_after_partitions.discard(partition)
+ else:
+ self._rewind_after_partition_release(registration, partition)
+ if should_backoff and registration.live and not self._stopping:
+ self._start_partition_backoff(registration, partition)
+ if (
+ registration.live
+ and self._active
+ and not self._stopping
+ and (
+ should_backoff
+ or item.rearm_after_process
+ or registration.rewind_requested
+ )
+ ):
+ registration.event.set()
+
+ def _start_partition_backoff(
+ self,
+ registration: _Registration,
+ partition: str,
+ ) -> None:
+ deadline = self._monotonic() + self._retry_backoff
+ if (
+ partition not in registration.backoff_deadlines
+ and len(registration.backoff_deadlines)
+ >= self._backoff_partition_limit
+ ):
+ raise RuntimeError("runtime work backoff reservation invariant violated")
+ registration.backoff_deadlines[partition] = deadline
+ existing = registration.backoff_task
+ if existing is not None and not existing.done():
+ return
+ self._start_next_partition_backoff(registration)
+
+ def _start_next_partition_backoff(
+ self,
+ registration: _Registration,
+ ) -> None:
+ deadlines = list(registration.backoff_deadlines.values())
+ if not deadlines:
+ registration.backoff_task = None
+ return
+ deadline = min(deadlines)
+ registration.backoff_task = asyncio.create_task(
+ self._finish_partition_backoff(registration, deadline),
+ name=f"runtime-work-backoff:{registration.token.lane.value}",
+ )
+
+ async def _finish_partition_backoff(
+ self,
+ registration: _Registration,
+ deadline: float,
+ ) -> None:
+ completed = False
+ try:
+ await self._retry_wait(max(0.0, deadline - self._monotonic()))
+ completed = True
+ finally:
+ if registration.backoff_task is not asyncio.current_task():
+ return
+ registration.backoff_task = None
+ if completed:
+ registration.backoff_deadlines = {
+ partition: partition_deadline
+ for partition, partition_deadline in (
+ registration.backoff_deadlines.items()
+ )
+ if partition_deadline > deadline
+ }
+ registration.expired_backoff_rewind_pending = True
+ if (
+ completed
+ and registration.live
+ and self._active
+ and not self._stopping
+ ):
+ registration.event.set()
+ if registration.live and registration.backoff_deadlines:
+ self._start_next_partition_backoff(registration)
async def _reconcile_loop(self) -> None:
try:
while self._active and not self._stopping:
await self._reconcile_wait(self._reconcile_interval)
- self._notify_on_loop(tuple(self._registrations))
+ if not self._owns_service_instance():
+ self._stop_for_lost_lease()
+ return
+ self._report_overdue_workers()
+ self._notify_on_loop(tuple(self._registrations), True)
except asyncio.CancelledError:
raise
+
+ def _report_overdue_workers(self) -> None:
+ now = self._monotonic()
+ for lane, registration in tuple(self._registrations.items()):
+ if not registration.live:
+ continue
+ if registration.scan_started_at is not None:
+ elapsed = now - registration.scan_started_at
+ if elapsed >= self._overdue_seconds:
+ logger.warning(
+ "Runtime work item overdue lane=%s partition=%s "
+ "generation=%s elapsed=%.3fs",
+ lane.value,
+ "<scan>",
+ registration.token.generation,
+ elapsed,
+ )
+ for partition, started_at in tuple(registration.worker_started_at.items()):
+ elapsed = now - started_at
+ if elapsed < self._overdue_seconds:
+ continue
+ logger.warning(
+ "Runtime work item overdue lane=%s partition=%s generation=%s "
+ "elapsed=%.3fs",
+ lane.value,
+ partition,
+ registration.token.generation,
+ elapsed,
+ )
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 6da09904e..f1268b7b6 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -7,12 +7,14 @@ import json
import logging
import os
import tempfile
+import threading
import time
from dataclasses import asdict, dataclass, field, replace
from datetime import datetime, timedelta, timezone
+from functools import partial, wraps
from pathlib import Path
from types import MappingProxyType, SimpleNamespace
-from typing import Any, Dict, Mapping, NamedTuple, Optional, Sequence
+from typing import Any, Callable, Dict, Mapping, NamedTuple, Optional, Sequence, TypeVar
from uuid import uuid4
from zoneinfo import ZoneInfo
@@ -44,6 +46,8 @@ from core.runtime_activation import (
)
from core.runtime_recovery import FallbackRequestRecoveryHandler
from core.runtime_work import (
+ RuntimeWorkHandler,
+ RuntimeWorkItem,
RuntimeWorkLane,
RuntimeWorkRegistrationToken,
)
@@ -101,6 +105,7 @@ from storage.background import (
NOTICE_PENDING,
NOTICE_SENT,
NOTICE_SKIPPED,
+ OWED_FAILURE_NOTICE_KEY,
SKIP_REASON_SESSION_BUSY,
SKIP_REASON_TRANSPORT_UNAVAILABLE,
SQLiteBackgroundTaskStore,
@@ -121,6 +126,8 @@ from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
+_TaskStoreResult = TypeVar("_TaskStoreResult")
+
AGENT_RUN_DELIVERY_STEER = "steer"
AGENT_RUN_DELIVERY_SEND_NOW = "send_now"
AGENT_RUN_DELIVERY_QUEUE = "queue"
@@ -135,6 +142,15 @@ AGENT_RUN_DELIVERY_INTENT_METADATA_KEY = "delivery_intent"
AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY = "delivery_outcome"
+def _publish_task_definitions_updated() -> None:
+ try:
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="scheduled")
+ except Exception:
+ logger.debug("scheduled definition wake failed", exc_info=True)
+
+
class _ScopeAgentTarget(NamedTuple):
agent_name: Optional[str]
@@ -1222,6 +1238,23 @@ def _retire_stale_agent_run_queue_rows(
return retired
+def _serialize_task_mirror(
+ method: Callable[..., _TaskStoreResult],
+) -> Callable[..., _TaskStoreResult]:
+ """Hold one mirror generation across each read-modify-write operation."""
+
+ @wraps(method)
+ def _locked(
+ self: "ScheduledTaskStore",
+ *args: Any,
+ **kwargs: Any,
+ ) -> _TaskStoreResult:
+ with self._reload_lock:
+ return method(self, *args, **kwargs)
+
+ return _locked
+
+
class ScheduledTaskStore:
def __init__(self, path: Optional[Path] = None):
self.path = path or (paths.get_state_dir() / "scheduled_tasks.json")
@@ -1231,9 +1264,14 @@ class ScheduledTaskStore:
#: Set when a failed write left this mirror INCOMPLETE, cleared by the reload
#: that repairs it. See ``maybe_reload`` and ``_reload_after_lost_write``.
self._reload_required = False
+ self._reload_lock = threading.RLock()
self.load()
def load(self) -> None:
+ with self._reload_lock:
+ self._load_unlocked()
+
+ def _load_unlocked(self) -> None:
if self._sqlite is not None:
self._tasks = {
item["id"]: ScheduledTask.from_dict(item)
@@ -1285,6 +1323,10 @@ class ScheduledTaskStore:
so a reload that fails again keeps retrying on every later tick.
"""
+ with self._reload_lock:
+ return self._maybe_reload_unlocked()
+
+ def _maybe_reload_unlocked(self) -> bool:
if self._sqlite is not None:
changed = self._sqlite.maybe_reload()
if self._reload_required:
@@ -1326,10 +1368,23 @@ class ScheduledTaskStore:
self._signature = _path_signature(self.path)
def list_tasks(self) -> list[ScheduledTask]:
- return sorted(self._tasks.values(), key=lambda item: (item.created_at, item.id))
+ with self._reload_lock:
+ return sorted(
+ self._tasks.values(),
+ key=lambda item: (item.created_at, item.id),
+ )
def get_task(self, task_id: str) -> Optional[ScheduledTask]:
- return self._tasks.get(task_id)
+ with self._reload_lock:
+ return self._tasks.get(task_id)
+
+ def refresh_task(self, task_id: str) -> Optional[ScheduledTask]:
+ """Reload and read one scheduler definition under the same mirror lock."""
+
+ with self._reload_lock:
+ self._maybe_reload_unlocked()
+ task = self._tasks.get(task_id)
+ return ScheduledTask.from_dict(task.to_dict()) if task is not None else None
def get_watch_definition(self, definition_id: str) -> Optional[Dict[str, Any]]:
"""The watch row for *definition_id*, or ``None`` when it is not a watch.
@@ -1416,6 +1471,7 @@ class ScheduledTaskStore:
"with the task row"
)
self._save()
+ _publish_task_definitions_updated()
return True
if queued_run is None:
landed = self._sqlite.upsert_scheduled_task(
@@ -1437,6 +1493,7 @@ class ScheduledTaskStore:
self._reload_after_lost_write(task.id)
raise
if landed:
+ _publish_task_definitions_updated()
return True
self.load()
return False
@@ -1465,6 +1522,7 @@ class ScheduledTaskStore:
self._signature = None
self._reload_required = True
+ @_serialize_task_mirror
def upsert_task(
self,
task: ScheduledTask,
@@ -1494,12 +1552,15 @@ class ScheduledTaskStore:
)
if expected_reference_agent_id is not None:
self.load()
+ _publish_task_definitions_updated()
return self._tasks[task.id]
+ _publish_task_definitions_updated()
return task
self._save()
except Exception:
self._reload_after_lost_write(task.id)
raise
+ _publish_task_definitions_updated()
return task
def add_task(
@@ -1551,6 +1612,7 @@ class ScheduledTaskStore:
expected_reference_agent_id=expected_reference_agent_id,
)
+ @_serialize_task_mirror
def remove_task(self, task_id: str) -> bool:
"""Delete a task; the mirror rolls back with the delete (HFR-275).
@@ -1566,13 +1628,16 @@ class ScheduledTaskStore:
try:
if self._sqlite is not None:
self._sqlite.remove_task(task_id)
+ _publish_task_definitions_updated()
return True
self._save()
except Exception:
self._reload_after_lost_write(task_id)
raise
+ _publish_task_definitions_updated()
return True
+ @_serialize_task_mirror
def set_enabled(self, task_id: str, enabled: bool) -> ScheduledTask:
task = self._tasks[task_id]
expect = self._read_state(task)
@@ -1585,6 +1650,7 @@ class ScheduledTaskStore:
raise DefinitionWriteConflict(task_id, definition_type="scheduled task")
return task
+ @_serialize_task_mirror
def update_task(
self,
task_id: str,
@@ -1657,6 +1723,7 @@ class ScheduledTaskStore:
return self._tasks[task_id]
return task
+ @_serialize_task_mirror
def record_binding_recovery(
self,
task_id: str,
@@ -1701,6 +1768,7 @@ class ScheduledTaskStore:
return False
return self._write_task(task, expect)
+ @_serialize_task_mirror
def list_orphaned_reservations(self, task_id: str) -> list[dict[str, Any]]:
"""The reserved sessions recorded against ``task_id`` that were never given back."""
@@ -1712,6 +1780,7 @@ class ScheduledTaskStore:
return []
return [dict(entry) for entry in entries if isinstance(entry, dict)]
+ @_serialize_task_mirror
def record_orphaned_reservations(self, task_id: str, entries: list[dict[str, Any]]) -> bool:
"""Durably record (or clear) the reservations this definition could not release.
@@ -1742,6 +1811,7 @@ class ScheduledTaskStore:
task.updated_at = _utc_now_iso()
return self._write_task(task, expect)
+ @_serialize_task_mirror
def mark_task_result(
self,
task_id: str,
@@ -1831,6 +1901,7 @@ class TaskExecutionStore:
self.pending_dir = self.root / "pending"
self.processing_dir = self.root / "processing"
self.completed_dir = self.root / "completed"
+ self._file_enqueue_lock = threading.Lock()
self._ensure_dirs()
self._signature = self._state_signature()
@@ -2230,16 +2301,30 @@ class TaskExecutionStore:
*,
source_kind: str = "cli",
task: Optional[ScheduledTask] = None,
- ) -> TaskExecutionRequest:
+ suppress_scheduler_successor: bool = False,
+ ) -> Optional[TaskExecutionRequest]:
if task is None:
- return self.enqueue(
- TaskExecutionRequest(
- id=uuid4().hex[:12],
- request_type="scheduled",
- task_id=task_id,
- source_kind=source_kind,
- )
+ request = TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type="scheduled",
+ task_id=task_id,
+ source_kind=source_kind,
)
+ if self._sqlite is not None:
+ if suppress_scheduler_successor and any(
+ pending.task_id == task_id
+ and pending.source_kind == "scheduler"
+ for pending in self.list_pending()
+ ):
+ return None
+ return self.enqueue(request)
+ with self._file_enqueue_lock:
+ if (
+ suppress_scheduler_successor
+ and self._file_has_unstarted_scheduler_run(task_id)
+ ):
+ return None
+ return self.enqueue(request)
metadata = dict(task.metadata or {})
snapshot = command_snapshot(task)
if snapshot is not None:
@@ -2259,6 +2344,7 @@ class TaskExecutionStore:
agent_name=task.agent_name,
session_policy=task.session_policy,
metadata=metadata,
+ suppress_scheduler_successor=suppress_scheduler_successor,
)
def enqueue_definition_run(
@@ -2277,7 +2363,8 @@ class TaskExecutionStore:
source_actor: Optional[str] = None,
parent_run_id: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
- ) -> TaskExecutionRequest:
+ suppress_scheduler_successor: bool = False,
+ ) -> Optional[TaskExecutionRequest]:
request = TaskExecutionRequest(
id=uuid4().hex[:12],
request_type=run_type,
@@ -2296,8 +2383,19 @@ class TaskExecutionStore:
metadata=dict(metadata or {}),
)
if self._sqlite is None:
- return self.enqueue(request)
- snapshot = self._sqlite.enqueue_definition_run(self.queued_run_payload(request))
+ with self._file_enqueue_lock:
+ if (
+ suppress_scheduler_successor
+ and self._file_has_unstarted_scheduler_run(definition_id)
+ ):
+ return None
+ return self.enqueue(request)
+ snapshot = self._sqlite.enqueue_definition_run(
+ self.queued_run_payload(request),
+ suppress_scheduler_successor=suppress_scheduler_successor,
+ )
+ if snapshot is None:
+ return None
for field_name in (
"agent_name",
"agent_id",
@@ -2457,11 +2555,21 @@ class TaskExecutionStore:
expected_enabled_agent_id=expected_enabled_agent_id,
)
- def list_pending(self) -> list[TaskExecutionRequest]:
+ def list_pending(
+ self,
+ *,
+ limit: int | None = None,
+ after: tuple[str, str] | None = None,
+ ) -> list[TaskExecutionRequest]:
if self._sqlite is not None:
return [
TaskExecutionRequest.from_dict(item)
- for item in self._sqlite.list_runs(status="pending")
+ for item in self._sqlite.list_runs(
+ status="pending",
+ run_types=tuple(EXECUTION_RUN_TYPES),
+ after=after,
+ limit=limit,
+ )
# ``task_escalation`` belongs here for the same reason ``hook_send``
# does: it is a queued Agent turn the drain loop must claim. Left out,
# the escalation row would be durable and never executed -- a failure
@@ -2479,7 +2587,29 @@ class TaskExecutionStore:
if not isinstance(payload, dict):
continue
requests.append(TaskExecutionRequest.from_dict(payload))
- return sorted(requests, key=lambda item: (item.created_at, item.id))
+ ordered = sorted(requests, key=lambda item: (item.created_at, item.id))
+ if after is not None:
+ ordered = [
+ item
+ for item in ordered
+ if (item.created_at, item.id) > (str(after[0]), str(after[1]))
+ ]
+ return ordered if limit is None else ordered[: max(0, int(limit))]
+
+ def _file_has_unstarted_scheduler_run(self, definition_id: str) -> bool:
+ """Match SQLite's queued-or-claimed scheduler successor fence."""
+
+ for run in self._list_file_runs():
+ if (
+ str(run.get("task_id") or run.get("definition_id") or "")
+ != str(definition_id)
+ or run.get("source_kind") != "scheduler"
+ ):
+ continue
+ status = _normalize_requested_run_status(run.get("status"))
+ if status == "queued" or (status == "running" and not run.get("pid")):
+ return True
+ return False
def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
if self._sqlite is not None:
@@ -2523,9 +2653,14 @@ class TaskExecutionStore:
count += 1
return count
- def list_pending_callbacks(self, *, limit: int = 20) -> list[dict[str, Any]]:
+ def list_pending_callbacks(
+ self,
+ *,
+ limit: int = 20,
+ after: tuple[str, str] | None = None,
+ ) -> list[dict[str, Any]]:
if self._sqlite is not None:
- return self._sqlite.list_pending_callbacks(limit=limit)
+ return self._sqlite.list_pending_callbacks(limit=limit, after=after)
runs = [
item
for item in self._list_file_runs()
@@ -2534,7 +2669,18 @@ class TaskExecutionStore:
and item.get("completed_at")
and (_normalize_requested_run_status(item.get("status")) or item.get("status")) in TERMINAL_RUN_STATUSES
]
- return sorted(runs, key=lambda item: (item.get("completed_at") or "", item.get("id") or ""))[:limit]
+ ordered = sorted(
+ runs,
+ key=lambda item: (item.get("completed_at") or "", item.get("id") or ""),
+ )
+ if after is not None:
+ ordered = [
+ item
+ for item in ordered
+ if (item.get("completed_at") or "", item.get("id") or "")
+ > (str(after[0]), str(after[1]))
+ ]
+ return ordered[:limit]
def list_deferred_runs(self) -> list[dict[str, Any]]:
if self._sqlite is not None:
@@ -3217,6 +3363,350 @@ class TaskExecutionStore:
self.complete(request, ok=ok, error=error)
+class _ScheduledRuntimeWorkHandler(RuntimeWorkHandler):
+ """Thin lane adapter around the existing durable owners.
+
+ Scans run in the supervisor's executor. Processing remains on the controller
+ loop only where it must create/cancel asyncio tasks or perform transport I/O.
+ """
+
+ def __init__(self, service: "ScheduledTaskService", lane: RuntimeWorkLane) -> None:
+ self.service = service
+ self.lane = lane
+ self._fallback = (
+ FallbackRequestRecoveryHandler(
+ service.request_store.sqlite_backend,
+ live_claims=lambda: service._live_claimed_run_ids,
+ partition_key=service._fallback_request_partition_key,
+ )
+ if lane is RuntimeWorkLane.REQUESTS
+ and service.request_store.sqlite_backend is not None
+ else None
+ )
+
+ def scan(
+ self,
+ *,
+ limit: int,
+ occupied: frozenset[str],
+ cursor: str | None,
+ ) -> tuple[list[RuntimeWorkItem], bool]:
+ if self.lane is RuntimeWorkLane.TASK_DEFINITIONS:
+ changed = self.service.store.maybe_reload()
+ return [
+ RuntimeWorkItem(
+ "scheduled-tasks",
+ changed,
+ rearm_after_process=False,
+ )
+ ], False
+ if self.lane is RuntimeWorkLane.REQUESTS:
+ return self._scan_requests(limit=limit, occupied=occupied, cursor=cursor)
+ if self.lane is RuntimeWorkLane.RUN_CALLBACKS:
+ return self._scan_run_callbacks(limit=limit, occupied=occupied, cursor=cursor)
+ if self.lane is RuntimeWorkLane.VAULT_CALLBACKS:
+ return self.service._scan_vault_callback_work(
+ limit=limit,
+ occupied=occupied,
+ cursor=cursor,
+ )
+ if self.lane is RuntimeWorkLane.ACTIVITY_OUTPUTS:
+ registry = self.service._activity_registry()
+ if registry is None:
+ return [], False
+ runtimes, has_more, retry_after, scanned_cursor = (
+ registry.scan_recovered_output_runtimes(
+ limit=limit,
+ cursor=cursor,
+ grace_seconds=self.service._activity_output_grace_seconds,
+ )
+ )
+ if retry_after is not None:
+ self.service._schedule_runtime_work_wake(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ retry_after,
+ )
+ items = [
+ RuntimeWorkItem(
+ f"{backend}\x1f{runtime_key}",
+ (backend, runtime_key),
+ cursor_key=f"{backend}\x1f{runtime_key}",
+ )
+ for backend, runtime_key in runtimes
+ ]
+ if scanned_cursor and (
+ not items or items[-1].cursor_key != scanned_cursor
+ ):
+ items.append(
+ RuntimeWorkItem(
+ "",
+ None,
+ cursor_key=scanned_cursor,
+ rearm_after_process=False,
+ cursor_only=True,
+ )
+ )
+ return items, has_more
+ if self.lane is RuntimeWorkLane.FAILURE_NOTICES:
+ return self._scan_failure_notices(
+ limit=limit,
+ occupied=occupied,
+ cursor=cursor,
+ )
+ if self.lane is RuntimeWorkLane.STALE_RUNS:
+ retry_after = self.service._stale_run_sweep_delay_seconds()
+ if retry_after is None:
+ return [
+ RuntimeWorkItem(
+ "run-cancellations",
+ None,
+ rearm_after_process=False,
+ )
+ ], False
+ if retry_after > 0:
+ self.service._schedule_runtime_work_wake(
+ RuntimeWorkLane.STALE_RUNS,
+ retry_after,
+ )
+ return [
+ RuntimeWorkItem(
+ "run-cancellations",
+ None,
+ rearm_after_process=False,
+ )
+ ], False
+ return [
+ RuntimeWorkItem(
+ "stale-runs",
+ None,
+ rearm_after_process=False,
+ )
+ ], False
+ return [], False
+
+ def _scan_requests(
+ self,
+ *,
+ limit: int,
+ occupied: frozenset[str],
+ cursor: str | None,
+ ) -> tuple[list[RuntimeWorkItem], bool]:
+ items: list[RuntimeWorkItem] = []
+ fallback_has_more = False
+ if self._fallback is not None:
+ fallback_cursor = None
+ scan_fallback = cursor is None or cursor.startswith("0\x1f")
+ if cursor and scan_fallback:
+ fallback_cursor = cursor.split("\x1f", 1)[1]
+ recovered, fallback_has_more = (
+ self._fallback.scan(
+ limit=limit,
+ occupied=occupied,
+ cursor=fallback_cursor,
+ )
+ if scan_fallback
+ else ([], False)
+ )
+ items.extend(
+ [
+ RuntimeWorkItem(
+ item.partition_key,
+ ("fallback", item.observation),
+ cursor_key=f"0\x1f{item.cursor_key or item.partition_key}",
+ )
+ for item in recovered
+ ]
+ )
+
+ remaining = max(0, limit - len(items))
+ if remaining == 0:
+ return items, fallback_has_more
+ fallback_continuation = (
+ items[-1].cursor_key
+ if fallback_has_more and items
+ else None
+ )
+
+ after = None
+ if cursor and cursor.startswith("1\x1f"):
+ parts = cursor.split("\x1f", 2)
+ if len(parts) == 3:
+ after = (parts[1], parts[2])
+ pending = self.service.request_store.list_pending(limit=remaining, after=after)
+ items.extend(
+ [
+ RuntimeWorkItem(
+ self.service._request_partition_key(request),
+ ("queued", request),
+ cursor_key=(
+ fallback_continuation
+ or f"1\x1f{request.created_at}\x1f{request.id}"
+ ),
+ )
+ for request in pending
+ ]
+ )
+ return items, fallback_has_more or len(pending) >= remaining
+
+ def _scan_run_callbacks(
+ self,
+ *,
+ limit: int,
+ occupied: frozenset[str],
+ cursor: str | None,
+ ) -> tuple[list[RuntimeWorkItem], bool]:
+ after = None
+ if cursor:
+ parts = cursor.split("\x1f", 1)
+ if len(parts) == 2:
+ after = (parts[0], parts[1])
+ rows = self.service.request_store.list_pending_callbacks(
+ limit=limit,
+ after=after,
+ )
+ items: list[RuntimeWorkItem] = []
+ for row in rows:
+ run_id = str(row.get("id") or "")
+ session_id = str(row.get("callback_session_id") or "")
+ partition = f"session:{session_id}" if session_id else f"run:{run_id}"
+ if run_id:
+ items.append(
+ RuntimeWorkItem(
+ partition,
+ row,
+ cursor_key=(
+ f"{row.get('completed_at') or ''}\x1f{run_id}"
+ ),
+ )
+ )
+ return items, len(rows) >= limit
+
+ @staticmethod
+ def _failure_notice_cursor(row: dict[str, Any]) -> tuple[str, str, str]:
+ metadata = row.get("metadata")
+ notice = (
+ metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(metadata, dict)
+ else None
+ )
+ return (
+ str(notice.get("next_attempt_at") or "")
+ if isinstance(notice, dict)
+ else "",
+ str(row.get("created_at") or ""),
+ str(row.get("id") or ""),
+ )
+
+ def _scan_failure_notices(
+ self,
+ *,
+ limit: int,
+ occupied: frozenset[str],
+ cursor: str | None,
+ ) -> tuple[list[RuntimeWorkItem], bool]:
+ store = self.service.request_store.sqlite_backend
+ if store is None:
+ return [], False
+ after = None
+ if cursor:
+ parts = cursor.split("\x1f", 2)
+ if len(parts) == 3:
+ after = (parts[0], parts[1], parts[2])
+ rows = store.list_owed_failure_notices(limit=limit, after=after)
+ next_attempt_at = store.next_owed_failure_notice_at()
+ if next_attempt_at:
+ try:
+ next_attempt = datetime.fromisoformat(next_attempt_at)
+ if next_attempt.tzinfo is None:
+ next_attempt = next_attempt.replace(tzinfo=timezone.utc)
+ delay = max(
+ 0.0,
+ (next_attempt.astimezone(timezone.utc) - datetime.now(timezone.utc)).total_seconds(),
+ )
+ self.service._schedule_runtime_work_wake(
+ RuntimeWorkLane.FAILURE_NOTICES,
+ delay,
+ )
+ except (TypeError, ValueError):
+ logger.warning(
+ "Ignoring invalid failure-notice retry timestamp %r",
+ next_attempt_at,
+ )
+ items: list[RuntimeWorkItem] = []
+ for row in rows:
+ run_id = str(row.get("id") or "")
+ metadata = row.get("metadata")
+ notice = (
+ metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(metadata, dict)
+ else None
+ )
+ definition_id = str(
+ row.get("definition_id") or row.get("task_id") or ""
+ )
+ if definition_id and not failure_notices.bypasses_suppression(notice):
+ partition = f"definition:{definition_id}"
+ else:
+ partition = f"run:{run_id}"
+ if run_id:
+ cursor_parts = self._failure_notice_cursor(row)
+ items.append(
+ RuntimeWorkItem(
+ partition,
+ row,
+ cursor_key="\x1f".join(cursor_parts),
+ )
+ )
+ return items, len(rows) >= limit
+
+ async def process(self, item: RuntimeWorkItem) -> bool | None:
+ if self.lane is RuntimeWorkLane.TASK_DEFINITIONS:
+ self.service.reconcile_jobs()
+ return True
+ if self.lane is RuntimeWorkLane.REQUESTS:
+ kind, observation = item.observation
+ if kind == "fallback":
+ assert self._fallback is not None
+ return await self.service._run_runtime_sync(
+ self._fallback.process_sync,
+ RuntimeWorkItem(item.partition_key, observation),
+ )
+ return await self.service._process_pending_request(observation)
+ if self.lane is RuntimeWorkLane.RUN_CALLBACKS:
+ return await self.service._process_run_callback(item.observation)
+ if self.lane is RuntimeWorkLane.VAULT_CALLBACKS:
+ return await self.service._process_vault_callback(item.observation)
+ if self.lane is RuntimeWorkLane.ACTIVITY_OUTPUTS:
+ backend, runtime_key = item.observation
+ return await self.service._process_recovered_activity_output(
+ backend,
+ runtime_key,
+ )
+ if self.lane is RuntimeWorkLane.FAILURE_NOTICES:
+ store = self.service.request_store.sqlite_backend
+ if store is not None:
+ await self.service._deliver_one_failure_notice(store, item.observation)
+ return True
+ if self.lane is RuntimeWorkLane.STALE_RUNS:
+ if item.partition_key == "run-cancellations":
+ await self.service._propagate_requested_cancellations_async()
+ return True
+ await self.service._propagate_requested_cancellations_async()
+ await self.service._run_runtime_sync(
+ self.service._sweep_stale_runs,
+ release_leaked_locks=False,
+ )
+ self.service._release_leaked_session_locks()
+ retry_after = self.service._stale_run_sweep_delay_seconds()
+ if retry_after is not None and retry_after > 0:
+ self.service._schedule_runtime_work_wake(
+ RuntimeWorkLane.STALE_RUNS,
+ retry_after,
+ )
+ return True
+ return True
+
+
class ScheduledTaskService:
"""Controller-owned runtime that executes persisted scheduled tasks."""
@@ -3244,6 +3734,15 @@ class ScheduledTaskService:
self._service_teardown_task: Optional["asyncio.Task[None]"] = None
self._request_recovery_token: RuntimeWorkRegistrationToken | None = None
self._request_recovery_unregistration_task: asyncio.Task[None] | None = None
+ self._runtime_work_tokens: dict[
+ RuntimeWorkLane, RuntimeWorkRegistrationToken
+ ] = {}
+ self._controller_runtime_work_tokens: dict[
+ RuntimeWorkLane, RuntimeWorkRegistrationToken
+ ] = {}
+ self._legacy_probe_tasks: dict[str, asyncio.Task[None]] = {}
+ self._legacy_task_signature: tuple[int, int, int] | None = None
+ self._legacy_request_signature: tuple[_DirectoryEntrySignature, ...] | None = None
# The owed-notice drain pass currently in flight, if any. It runs OUTSIDE the
# store watch (see ``_spawn_failure_notice_drain``), which means it also has to
# be torn down by name: cancelling the watch no longer stops it.
@@ -3254,6 +3753,7 @@ class ScheduledTaskService:
# 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]"] = {}
+ self._request_capacity_reservations: set[str] = set()
# Immutable loop-published view consumed by the off-thread recovery scan.
# The handler rechecks it on the loop before the recovery CAS.
self._live_claimed_run_ids: frozenset[str] = frozenset()
@@ -3721,7 +4221,11 @@ class ScheduledTaskService:
exc_info=True,
)
return
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
def _execution_interruption(self, execution_id: str) -> str:
return self._inflight_cancellation_causes.get(
@@ -3747,6 +4251,17 @@ class ScheduledTaskService:
def _activity_registry(self) -> Any:
return getattr(getattr(self.controller, "agent_service", None), "activities", None)
+ def _activity_output_grace_seconds(self, backend: str) -> float:
+ agents = getattr(getattr(self.controller, "agent_service", None), "agents", {})
+ agent = agents.get(str(backend)) if isinstance(agents, dict) else None
+ try:
+ return max(
+ 0.0,
+ float(getattr(agent, "ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS", 0.0)),
+ )
+ except (TypeError, ValueError):
+ return 0.0
+
def _recover_activity_lifecycle(self) -> None:
"""Reconcile persisted Activity blockers before queued-Run recovery."""
@@ -3793,7 +4308,11 @@ class ScheduledTaskService:
if callable(has_pending_output) and has_pending_output(run_id):
continue
if self.request_store.settle_deferred_run(run_id):
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
def _settle_pending_recovered_activity_terminals(self) -> None:
"""Acknowledge terminal snapshots only after owned output leaves the Outbox."""
@@ -3833,7 +4352,11 @@ class ScheduledTaskService:
terminal_status="succeeded",
)
if self.request_store.settle_deferred_run(run_id):
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
async def _deliver_recovered_activity_output(self, activity: Any) -> None:
registry = self._activity_registry()
@@ -3915,6 +4438,41 @@ class ScheduledTaskService:
break
self._settle_pending_recovered_activity_terminals()
+ async def _process_recovered_activity_output(
+ self,
+ backend: str,
+ runtime_key: str,
+ ) -> bool:
+ registry = self._activity_registry()
+ claim = getattr(registry, "claim_completed_output", None)
+ if registry is None or not callable(claim):
+ return True
+ activity = claim(backend, runtime_key, recovered_only=True)
+ if activity is None:
+ self._settle_pending_recovered_activity_terminals()
+ return not bool(registry.has_completed_output(backend, runtime_key))
+ try:
+ await self._deliver_recovered_activity_output(activity)
+ except Exception:
+ registry.requeue_completed_output(activity, recovered=True)
+ logger.warning(
+ "Failed to deliver recovered Activity output %s",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+ return False
+ self._settle_pending_recovered_activity_terminals()
+ has_recovered_output = getattr(registry, "has_recovered_output", None)
+ if callable(has_recovered_output) and has_recovered_output(
+ backend,
+ runtime_key,
+ ):
+ self._wake_runtime_work(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ reset_cursor=True,
+ )
+ return True
+
def validate_platform(self, platform: str) -> None:
# The real IM platforms have a settings manager; ``avibe`` (the web
# workbench) is a virtual platform with an IM client but no settings
@@ -3935,14 +4493,21 @@ class ScheduledTaskService:
raise RuntimeError("scheduled task service generation is still stopping")
teardown.result()
self._service_teardown_task = None
- self._register_request_recovery()
+ if self._supports_runtime_work_lanes():
+ self.register_controller_runtime_work_lanes()
+ self._register_runtime_work_lanes()
+ else:
+ self._register_request_recovery()
try:
self.scheduler.start()
except BaseException:
self._begin_stop()
raise
self._running = True
- self._spawn_watch_store()
+ if not self._supports_runtime_work_lanes():
+ self._spawn_watch_store()
+ else:
+ self._start_legacy_runtime_work_probes()
try:
self.reconcile_jobs()
except Exception as exc:
@@ -4007,9 +4572,182 @@ class ScheduledTaskService:
FallbackRequestRecoveryHandler(
sqlite_store,
live_claims=lambda: self._live_claimed_run_ids,
+ partition_key=self._fallback_request_partition_key,
),
)
+ def _supports_runtime_work_lanes(self) -> bool:
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ return callable(getattr(supervisor, "notify", None))
+
+ def _register_runtime_work_lanes(self) -> None:
+ previous = self._request_recovery_unregistration_task
+ if previous is not None:
+ if not previous.done():
+ raise RuntimeError(
+ "scheduled task service runtime work generation is still stopping"
+ )
+ previous.result()
+ self._request_recovery_unregistration_task = None
+ if self._runtime_work_tokens:
+ raise RuntimeError(
+ "scheduled task service runtime work generation is already registered"
+ )
+ supervisor = self.controller.runtime_work_supervisor
+ registered: list[RuntimeWorkRegistrationToken] = []
+ try:
+ for lane in (
+ RuntimeWorkLane.TASK_DEFINITIONS,
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.VAULT_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ RuntimeWorkLane.STALE_RUNS,
+ ):
+ token = supervisor.register(
+ lane,
+ _ScheduledRuntimeWorkHandler(self, lane),
+ )
+ self._runtime_work_tokens[lane] = token
+ registered.append(token)
+ except BaseException:
+ for token in registered:
+ supervisor.begin_unregister(token)
+ self._runtime_work_tokens.clear()
+ raise
+ self._request_recovery_token = self._runtime_work_tokens[
+ RuntimeWorkLane.REQUESTS
+ ]
+
+ def register_controller_runtime_work_lanes(
+ self,
+ ) -> tuple[RuntimeWorkRegistrationToken, ...]:
+ """Register live-producer lanes for the full controller generation."""
+
+ if not self._supports_runtime_work_lanes():
+ return ()
+ existing = self._controller_runtime_work_tokens.get(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS
+ )
+ if existing is not None:
+ return ()
+ token = self.controller.runtime_work_supervisor.register(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ _ScheduledRuntimeWorkHandler(self, RuntimeWorkLane.ACTIVITY_OUTPUTS),
+ )
+ self._controller_runtime_work_tokens[RuntimeWorkLane.ACTIVITY_OUTPUTS] = token
+ return (token,)
+
+ def _begin_runtime_work_unregistration(self) -> asyncio.Task[None] | None:
+ if not self._runtime_work_tokens:
+ return self._begin_request_recovery_unregistration()
+ existing = self._request_recovery_unregistration_task
+ if existing is not None:
+ return existing
+ supervisor = self.controller.runtime_work_supervisor
+ tasks = [
+ supervisor.begin_unregister(token)
+ for token in self._runtime_work_tokens.values()
+ ]
+ self._runtime_work_tokens.clear()
+ self._request_recovery_token = None
+
+ async def _join() -> None:
+ await asyncio.gather(*tasks)
+
+ joined = asyncio.create_task(
+ _join(),
+ name="scheduled-runtime-work-unregister",
+ )
+ self._request_recovery_unregistration_task = joined
+ return joined
+
+ def _wake_runtime_work(
+ self,
+ *lanes: RuntimeWorkLane,
+ reset_cursor: bool = False,
+ ) -> None:
+ controller = getattr(self, "controller", None)
+ supervisor = getattr(controller, "runtime_work_supervisor", None)
+ notify = getattr(supervisor, "notify", None)
+ if callable(notify):
+ if reset_cursor:
+ notify(*lanes, reset_cursor=True)
+ else:
+ notify(*lanes)
+ else:
+ self._drain_dirty = True
+
+ def _schedule_runtime_work_wake(
+ self,
+ lane: RuntimeWorkLane,
+ delay: float,
+ ) -> None:
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ notify_after = getattr(supervisor, "notify_after", None)
+ token = self._runtime_work_tokens.get(
+ lane,
+ self._controller_runtime_work_tokens.get(lane),
+ )
+ if callable(notify_after) and token is not None:
+ notify_after(token, delay)
+
+ async def _run_runtime_sync(self, operation, /, *args, **kwargs): # noqa: ANN001, ANN202
+ call = partial(operation, *args, **kwargs)
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ run_sync = getattr(supervisor, "run_sync", None)
+ if callable(run_sync):
+ return await run_sync(call)
+ return await asyncio.to_thread(call)
+
+ def _start_legacy_runtime_work_probes(self) -> None:
+ if self.store.sqlite_backend is None:
+ self._legacy_task_signature = _path_signature(self.store.path)
+ self._legacy_probe_tasks["tasks"] = asyncio.create_task(
+ self._legacy_task_definition_probe(),
+ name="scheduled-runtime-work-task-file-probe",
+ )
+ if self.request_store.sqlite_backend is None:
+ self._legacy_request_signature = self.request_store._state_signature()
+ self._legacy_probe_tasks["requests"] = asyncio.create_task(
+ self._legacy_request_directory_probe(),
+ name="scheduled-runtime-work-request-file-probe",
+ )
+
+ async def _legacy_task_definition_probe(self) -> None:
+ """Wake only when the injected task file signature changes."""
+
+ try:
+ while self._running:
+ await asyncio.sleep(2)
+ signature = await self._run_runtime_sync(_path_signature, self.store.path)
+ if signature == self._legacy_task_signature:
+ continue
+ self._legacy_task_signature = signature
+ self._wake_runtime_work(RuntimeWorkLane.TASK_DEFINITIONS)
+ except asyncio.CancelledError:
+ raise
+
+ async def _legacy_request_directory_probe(self) -> None:
+ """Wake every Run consumer on a legacy directory edge."""
+
+ try:
+ while self._running:
+ await asyncio.sleep(2)
+ signature = await self._run_runtime_sync(
+ self.request_store._state_signature
+ )
+ if signature == self._legacy_request_signature:
+ continue
+ self._legacy_request_signature = signature
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.STALE_RUNS,
+ )
+ except asyncio.CancelledError:
+ raise
+
def _begin_request_recovery_unregistration(
self,
) -> asyncio.Task[None] | None:
@@ -4139,16 +4877,52 @@ class ScheduledTaskService:
self._inflight_cancellation_causes[request_id] = SETTLED_BY_STOPPED
execution.cancel()
+ async def _propagate_requested_cancellations_async(self) -> None:
+ """Off-loop store reads with loop-owned cancellation decisions."""
+
+ candidates = [
+ (request_id, execution, self._inflight_requests.get(request_id))
+ for request_id, execution in self._inflight_executions.items()
+ if not execution.done()
+ and request_id not in self._inflight_cancellation_causes
+ ]
+ for request_id, execution, request in candidates:
+ if request is None or not self._is_command_execution(request):
+ continue
+ try:
+ run = await self._run_runtime_sync(
+ self.request_store.get_run,
+ request_id,
+ )
+ except Exception:
+ logger.exception(
+ "Failed to read Run %s while checking for a requested cancellation",
+ request_id,
+ )
+ continue
+ if (
+ not run
+ or not bool(run.get("cancel_requested"))
+ or str(run.get("status") or "") in TERMINAL_RUN_STATUSES
+ or execution.done()
+ ):
+ continue
+ self._inflight_cancellation_causes[request_id] = SETTLED_BY_STOPPED
+ execution.cancel()
+
def _begin_stop(
self,
*,
cancel_reconcile: bool = True,
) -> asyncio.Task[None] | None:
self._running = False
- request_recovery_stop = self._begin_request_recovery_unregistration()
+ request_recovery_stop = self._begin_runtime_work_unregistration()
current_task = self._current_asyncio_task()
if cancel_reconcile and self._reconcile_task and self._reconcile_task is not current_task:
self._reconcile_task.cancel()
+ for probe in self._legacy_probe_tasks.values():
+ if probe is not current_task:
+ probe.cancel()
# Cancelled by name, and not gated on ``cancel_reconcile``: the notice drain is
# no longer part of the watch coroutine, so stopping the watch leaves it running
# — a delivery on behalf of a service this process no longer owns, or one that
@@ -4179,6 +4953,10 @@ class ScheduledTaskService:
async def stop(self) -> None:
request_recovery_stop = self._begin_stop()
+ legacy_probes = tuple(self._legacy_probe_tasks.values())
+ self._legacy_probe_tasks.clear()
+ if legacy_probes:
+ await asyncio.gather(*legacy_probes, return_exceptions=True)
if self._reconcile_task:
self._reconcile_task.cancel()
try:
@@ -4216,6 +4994,7 @@ class ScheduledTaskService:
if self._request_recovery_unregistration_task is request_recovery_stop:
self._request_recovery_unregistration_task = None
self._inflight_executions.clear()
+ self._request_capacity_reservations.clear()
self._live_claimed_run_ids = frozenset()
self._inflight_requests.clear()
self._inflight_cancellation_causes.clear()
@@ -4349,10 +5128,14 @@ class ScheduledTaskService:
if leaked:
# The wedge is gone; re-check the queue now instead of waiting for the
# next store change, which a stuck session has no reason to produce.
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
return set(leaked)
- def _sweep_stale_runs(self) -> None:
+ def _sweep_stale_runs(self, *, release_leaked_locks: bool = True) -> None:
"""Terminalize runs that nothing is executing any more (plan §4).
Rides the existing store tick because the leak it repairs is the ABSENCE of
@@ -4411,11 +5194,27 @@ class ScheduledTaskService:
)
# Unconditional: the in-memory wedge and the stale rows are independent
# failures, and either can outlive the other.
- self._release_leaked_session_locks()
+ if release_leaked_locks:
+ self._release_leaked_session_locks()
if swept:
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
self._retire_swept_queue_segments(swept)
+ def _stale_run_sweep_delay_seconds(self) -> float | None:
+ interval = self._runtime_seconds(
+ "harness_run_sweep_interval_seconds",
+ DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS,
+ )
+ if interval <= 0:
+ return None
+ if not self._last_sweep_at:
+ return 0.0
+ return max(0.0, interval - (time.monotonic() - self._last_sweep_at))
+
def _retire_swept_queue_segments(self, swept: list[Any]) -> None:
"""Drop the persisted Workbench queue rows a swept run left behind.
@@ -4523,45 +5322,124 @@ class ScheduledTaskService:
async def _run_task(self, task_id: str) -> None:
if not self._owns_service_instance():
return
- self.store.maybe_reload()
- task = self.store.get_task(task_id)
+ task = await self._run_runtime_sync(self.store.refresh_task, task_id)
if not task or not task.enabled:
return
- if any(
- request.request_type == "scheduled"
- and request.source_kind == "scheduler"
- and request.task_id == task.id
- for request in self.request_store.list_pending()
- ):
- self._drain_dirty = True
- return
- queued = self.request_store.enqueue_task_run(task.id, source_kind="scheduler", task=task)
- if not self._transport_ready_for_request(queued):
- self._drain_dirty = True
- return
- request = self._claim_pending_request(queued)
- if request is None:
- return
+ queued = await self._run_runtime_sync(
+ self.request_store.enqueue_task_run,
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ )
+ if queued is not None:
+ self._wake_runtime_work(RuntimeWorkLane.REQUESTS)
+
+ def _request_partition_key(self, request: TaskExecutionRequest) -> str:
lock_key = self._execution_lock_key(request)
- if len(self._inflight_executions) >= self._MAX_CONCURRENT_EXECUTIONS:
- self.request_store.requeue(request.id)
- return
- if lock_key is not None and lock_key in self._inflight_sessions:
- self.request_store.requeue(request.id)
- return
- command_definition_id = self._command_fire_definition_id(request)
- if command_definition_id is not None and self._command_definition_has_live_worker(
- command_definition_id
+ if lock_key:
+ return lock_key
+ return f"run:{request.id}"
+
+ def _fallback_request_partition_key(self, row: dict[str, Any]) -> str:
+ return self._request_partition_key(TaskExecutionRequest.from_dict(row))
+
+ async def _process_pending_request(
+ self,
+ pending: TaskExecutionRequest,
+ ) -> bool:
+ if not self._owns_service_instance():
+ return True
+ if pending.id in self._request_capacity_reservations:
+ return True
+ if (
+ len(self._inflight_executions) + len(self._request_capacity_reservations)
+ >= self._MAX_CONCURRENT_EXECUTIONS
):
- # Requeued, not dropped: the row stays the definition's one pending fire and
- # runs as soon as the earlier worker is shown gone.
- self.request_store.requeue(request.id)
- self._drain_dirty = True
- return
- self._spawn_execution(request, lock_key)
- execution = self._inflight_executions.get(request.id)
- if execution is not None:
- await execution
+ return False
+ if pending.id in self._inflight_executions:
+ return True
+ registration = self._runtime_work_tokens.get(RuntimeWorkLane.REQUESTS)
+ self._request_capacity_reservations.add(pending.id)
+ try:
+ if not self._transport_ready_for_request(pending):
+ await self._run_runtime_sync(
+ self.request_store.record_skip_reason,
+ pending.id,
+ reason=SKIP_REASON_TRANSPORT_UNAVAILABLE,
+ )
+ return False
+ lock_key = self._execution_lock_key(pending)
+ if lock_key is not None and lock_key in self._inflight_sessions:
+ await self._run_runtime_sync(
+ self.request_store.record_skip_reason,
+ pending.id,
+ reason=SKIP_REASON_SESSION_BUSY,
+ )
+ return False
+ command_definition_id = self._command_fire_definition_id(pending)
+ if command_definition_id is not None and await self._run_runtime_sync(
+ self._command_definition_has_live_worker,
+ command_definition_id,
+ ):
+ await self._run_runtime_sync(
+ self.request_store.record_skip_reason,
+ pending.id,
+ reason=SKIP_REASON_SESSION_BUSY,
+ )
+ return False
+ request = await self._run_runtime_sync(self._claim_pending_request, pending)
+ if request is None:
+ return True
+ if registration is not None and (
+ not self._running
+ or self._runtime_work_tokens.get(RuntimeWorkLane.REQUESTS)
+ != registration
+ or not self._owns_service_instance()
+ ):
+ await self._run_runtime_sync(
+ self.request_store.requeue,
+ request.id,
+ )
+ return True
+ self._spawn_execution(request, lock_key)
+ return True
+ finally:
+ self._request_capacity_reservations.discard(pending.id)
+
+ async def _process_run_callback(self, run: dict[str, Any]) -> bool:
+ run_id = str(run.get("id") or "")
+ if not run_id:
+ return True
+ try:
+ callback_run = await self._run_runtime_sync(
+ self._enqueue_callback_run,
+ run,
+ )
+ except Exception as exc:
+ logger.error("Agent run callback failed for %s: %s", run_id, exc, exc_info=True)
+ await self._run_runtime_sync(
+ self.request_store.update_callback_status,
+ run_id,
+ status="failed",
+ error=str(exc),
+ )
+ return False
+ if callback_run is None:
+ await self._run_runtime_sync(
+ self.request_store.update_callback_status,
+ run_id,
+ status="skipped",
+ )
+ return True
+ await self._run_runtime_sync(
+ self.request_store.update_callback_status,
+ run_id,
+ status="sent",
+ callback_run_id=callback_run.id,
+ )
+ self._wake_runtime_work(RuntimeWorkLane.REQUESTS)
+ return True
async def _drain_requests(self) -> None:
if not self._owns_service_instance():
@@ -4623,14 +5501,17 @@ class ScheduledTaskService:
except Exception as exc:
logger.error("Agent run callback failed for %s: %s", run_id, exc, exc_info=True)
self.request_store.update_callback_status(run_id, status="failed", error=str(exc))
- self._drain_dirty = True
+ self._wake_runtime_work(RuntimeWorkLane.RUN_CALLBACKS)
continue
if callback_run is None:
self.request_store.update_callback_status(run_id, status="skipped")
- self._drain_dirty = True
+ self._wake_runtime_work(RuntimeWorkLane.RUN_CALLBACKS)
continue
self.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ )
# --- the owed-failure-notice drain ---------------------------------------
#
@@ -4734,7 +5615,7 @@ class ScheduledTaskService:
async def _deliver_one_failure_notice(self, store: Any, run: dict[str, Any]) -> None:
run_id = str(run["id"])
definition_id = str(run.get("task_id") or run.get("definition_id") or "") or None
- notice = store.owed_failure_notice(run_id)
+ notice = await self._run_runtime_sync(store.owed_failure_notice, run_id)
# Re-read and re-check ELIGIBILITY, not merely the state. The batch was listed
# before this pass began and each row is then delivered one at a time, so by
# the time a row is reached another owner may already have claimed it — and a
@@ -4761,7 +5642,8 @@ class ScheduledTaskService:
# failures and defer the notice behind a canonical row it has nothing to do
# with.
if definition_id and not failure_notices.bypasses_suppression(notice):
- earlier_unsettled = store.earliest_unsettled_run_before(
+ earlier_unsettled = await self._run_runtime_sync(
+ store.earliest_unsettled_run_before,
definition_id,
created_at=str(run.get("created_at") or ""),
run_id=run_id,
@@ -4773,7 +5655,11 @@ class ScheduledTaskService:
# read snapshot: read separately, a success settling between the
# boundary seek and the row read merges two streaks, and a ``sent``
# notice from the earlier outage then skips a live one.
- streak_facts = store.failure_streak_decision(definition_id, run_id)
+ streak_facts = await self._run_runtime_sync(
+ store.failure_streak_decision,
+ definition_id,
+ run_id,
+ )
# The callback's status is read FRESH, not taken from the listed row: the
# batch predates this decision by up to a whole pass, and ``_drain_callbacks``
@@ -4781,13 +5667,17 @@ class ScheduledTaskService:
# callback already landed, and a stale absence would deliver beside it. A
# read failure propagates to the drain loop's per-row handler and the row is
# retried later, which errs toward one message rather than two.
+ callback_status = await self._run_runtime_sync(
+ store.run_callback_state,
+ run_id,
+ )
decision = failure_notices.decide(
run_id=run_id,
definition_id=definition_id,
notice=notice,
streak_facts=streak_facts,
earlier_unsettled=earlier_unsettled,
- callback_status=store.run_callback_state(run_id),
+ callback_status=callback_status,
)
if decision.action == failure_notices.ACTION_DEFER:
# No attempt consumed — this row has not been tried. But the deferral is
@@ -4795,7 +5685,8 @@ class ScheduledTaskService:
# is re-selected by every tick and keeps occupying the batch, so one
# definition with more than a batch worth of pending failures starved
# every other definition's notices indefinitely.
- store.update_owed_failure_notice(
+ await self._run_runtime_sync(
+ store.update_owed_failure_notice,
run_id,
expect=expect,
next_attempt_at=(
@@ -4807,7 +5698,8 @@ class ScheduledTaskService:
logger.debug("failure notice for %s deferred (%s)", run_id, decision.reason)
return
if decision.action == failure_notices.ACTION_SKIP:
- store.update_owed_failure_notice(
+ await self._run_runtime_sync(
+ store.update_owed_failure_notice,
run_id,
expect=expect,
state=NOTICE_SKIPPED,
@@ -4846,7 +5738,8 @@ class ScheduledTaskService:
# bound, and the recovered pass consumes its own attempt rather than inheriting
# the dead one, so the retry ladder stays finite. The residual is at-least-once
# delivery, documented on that constant.
- claimed = store.update_owed_failure_notice(
+ claimed = await self._run_runtime_sync(
+ store.update_owed_failure_notice,
run_id,
expect=expect,
attempts=attempt,
@@ -4948,7 +5841,8 @@ class ScheduledTaskService:
# on a function return. ``emit_replayed_backend_failure`` discards the
# notify result and returns normally either way, so a returns-cleanly ack
# would flip a lost notice to ``sent`` permanently.
- store.update_owed_failure_notice(
+ await self._run_runtime_sync(
+ store.update_owed_failure_notice,
run_id,
expect=expect,
state=NOTICE_SENT,
@@ -4962,14 +5856,15 @@ class ScheduledTaskService:
# diagnosis and must NOT trigger a resend.
error=evidence.error_text,
)
- self._drain_dirty = True
+ self._wake_runtime_work(RuntimeWorkLane.FAILURE_NOTICES)
return
error_text = evidence.error_text or "failure notice delivery produced no evidence"
if retry_after is None:
# Dead letter, carrying the raised exception's own message rather than a
# generic string. Visible rather than silently retrying forever.
- store.update_owed_failure_notice(
+ await self._run_runtime_sync(
+ store.update_owed_failure_notice,
run_id,
expect=expect,
state=NOTICE_FAILED,
@@ -4981,7 +5876,8 @@ class ScheduledTaskService:
next_attempt_at = (
datetime.now(timezone.utc) + timedelta(seconds=retry_after)
).isoformat()
- store.update_owed_failure_notice(
+ await self._run_runtime_sync(
+ store.update_owed_failure_notice,
run_id,
expect=expect,
state=NOTICE_PENDING,
@@ -6059,7 +6955,11 @@ class ScheduledTaskService:
):
settled.append(run_id)
if settled:
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
return settled
async def _drain_vault_callbacks(self) -> None:
@@ -6126,7 +7026,109 @@ class ScheduledTaskService:
continue
if status == "sent":
# A callback run was enqueued into the run store; drain it promptly.
- self._drain_dirty = True
+ self._wake_runtime_work(RuntimeWorkLane.REQUESTS)
+
+ def _scan_vault_callback_work(
+ self,
+ *,
+ limit: int,
+ occupied: frozenset[str],
+ cursor: str | None,
+ ) -> tuple[list[RuntimeWorkItem], bool]:
+ from storage import vault_service
+
+ engine = get_cached_sqlite_engine(paths.get_sqlite_state_path())
+ after = None
+ if cursor:
+ parts = cursor.split("\x1f", 1)
+ if len(parts) == 2:
+ after = (parts[0], parts[1])
+ with engine.begin() as conn:
+ vault_service.expire_overdue_requests(conn)
+ next_expiry = vault_service.earliest_pending_request_expiry(conn)
+ pending = vault_service.list_pending_request_callbacks(
+ conn,
+ limit=limit,
+ after=after,
+ )
+ if next_expiry is not None:
+ self._schedule_runtime_work_wake(
+ RuntimeWorkLane.VAULT_CALLBACKS,
+ max(
+ 0.0,
+ (next_expiry - datetime.now(timezone.utc)).total_seconds(),
+ ),
+ )
+ items: list[RuntimeWorkItem] = []
+ for row in pending:
+ request_id = str(row.get("id") or "")
+ if not request_id:
+ continue
+ try:
+ plan = vault_service.resolve_request_callback(row)
+ except Exception:
+ plan = None
+ session_id = str(getattr(plan, "session_id", "") or "")
+ partition = f"session:{session_id}" if session_id else f"request:{request_id}"
+ items.append(
+ RuntimeWorkItem(
+ partition,
+ row,
+ cursor_key=f"{row.get('decided_at') or ''}\x1f{request_id}",
+ )
+ )
+ return items, len(pending) >= limit
+
+ async def _process_vault_callback(self, row: dict[str, Any]) -> bool:
+ status = await self._run_runtime_sync(self._process_vault_callback_sync, row)
+ if status == "sent":
+ self._wake_runtime_work(RuntimeWorkLane.REQUESTS)
+ return status != "pending"
+
+ def _process_vault_callback_sync(self, row: dict[str, Any]) -> str:
+ from storage import vault_service
+
+ request_id = str(row.get("id") or "")
+ if not request_id:
+ return "skipped"
+ engine = get_cached_sqlite_engine(paths.get_sqlite_state_path())
+ status = "skipped"
+ try:
+ with engine.begin() as conn:
+ ready = vault_service.request_callback_ready(conn, row)
+ if not ready:
+ return "pending"
+ plan = vault_service.resolve_request_callback(row)
+ if plan is not None:
+ enqueue_session_callback(
+ self.request_store,
+ session_id=plan.session_id,
+ message=plan.message,
+ source_actor=f"vault:{request_id}",
+ )
+ status = "sent"
+ except ValueError:
+ status = "skipped"
+ except Exception as exc:
+ logger.error(
+ "Vault request callback failed for %s: %s",
+ request_id,
+ exc,
+ exc_info=True,
+ )
+ status = "failed"
+ try:
+ with engine.begin() as conn:
+ vault_service.mark_request_callback(conn, request_id, status=status)
+ except Exception as exc:
+ logger.error(
+ "Vault request callback mark failed for %s: %s",
+ request_id,
+ exc,
+ exc_info=True,
+ )
+ return "pending"
+ return status
def _enqueue_callback_run(self, run: dict[str, Any]) -> Optional[TaskExecutionRequest]:
callback_session_id = str(run.get("callback_session_id") or "").strip()
@@ -6278,6 +7280,11 @@ class ScheduledTaskService:
def notify_transport_ready(self, platform: str) -> None:
logger.info("Transport %s ready; scheduled Run queue will be drained", platform)
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ notify = getattr(supervisor, "notify", None)
+ if callable(notify):
+ notify(RuntimeWorkLane.REQUESTS, reset_cursor=True)
+ return
self._drain_dirty = True
def _canonical_session_lock(self, session_id: str, session_key: Optional[str]) -> str:
@@ -6339,7 +7346,11 @@ class ScheduledTaskService:
# live lock as leaked.
if self._session_lock_owners.get(lock_key) == request_id:
self._session_lock_owners.pop(lock_key, None)
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
# ``_execute_claimed_request`` already terminalizes cancellations and
# records ordinary failures. A task cancelled before its coroutine enters
# has no execution to settle; put that bare claim back in the queue.
@@ -7652,7 +8663,11 @@ class ScheduledTaskService:
expected_status=settled,
)
if settled_any:
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
def settle_agent_runs_from_terminal_turn(
self,
@@ -7745,7 +8760,11 @@ class ScheduledTaskService:
result.get("terminal_transition") or result.get("text_backfilled")
)
if settled_any:
- self._drain_dirty = True
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
def _retract_escalation_of_stopped_fire(self, execution_id: str) -> None:
"""Take back the Agent turn a fire queued, once the user stops that fire.
diff --git a/core/session_activities.py b/core/session_activities.py
index 62f20a548..9fe7099a4 100644
--- a/core/session_activities.py
+++ b/core/session_activities.py
@@ -12,6 +12,7 @@ import logging
import threading
import time
import uuid
+from bisect import bisect_left, bisect_right, insort
from collections import defaultdict, deque
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
@@ -27,6 +28,7 @@ logger = logging.getLogger(__name__)
TERMINAL_ACTIVITY_STATUSES = frozenset({"completed", "failed", "stopped", "killed", "disconnected"})
CONNECTION_STATES = frozenset({"connected", "reconnecting", "disconnected", "unknown"})
TERMINAL_SNAPSHOT_PHASE = "terminal"
+_IMMEDIATE_RECOVERY_ELIGIBILITY = datetime.min.replace(tzinfo=timezone.utc)
def _now_iso() -> str:
@@ -262,6 +264,15 @@ class SessionActivityRegistry:
] = {}
self._next_completed_output_sequence = 0
self._recovered_output_ids: set[tuple[str, str, str]] = set()
+ self._recovered_output_counts: dict[tuple[str, str], int] = {}
+ self._recovered_runtime_keys: list[tuple[str, str]] = []
+ self._recovered_output_eligibility: dict[
+ tuple[str, str], dict[str, datetime]
+ ] = {}
+ self._recovered_runtime_eligibility: dict[tuple[str, str], datetime] = {}
+ self._recovered_backend_eligibility: dict[
+ str, list[tuple[datetime, str]]
+ ] = defaultdict(list)
self._recovered_terminals: deque[SessionActivity] = deque()
self._restore()
@@ -282,6 +293,89 @@ class SessionActivityRegistry:
def _activity_key(cls, activity: SessionActivity) -> tuple[str, str, str]:
return cls._key(activity.backend, activity.runtime_key, activity.id)
+ @staticmethod
+ def _recovered_activity_eligibility(activity: SessionActivity) -> datetime:
+ if (
+ str(activity.metadata.get("output_batch_id") or "").strip()
+ or activity.metadata.get("_output_local_settlement_only")
+ ):
+ return _IMMEDIATE_RECOVERY_ELIGIBILITY
+ raw = str(activity.completed_at or "").strip()
+ try:
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ except ValueError:
+ return _IMMEDIATE_RECOVERY_ELIGIBILITY
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+ def _refresh_recovered_runtime_eligibility(
+ self,
+ runtime: tuple[str, str],
+ ) -> None:
+ backend, runtime_key = runtime
+ index = self._recovered_backend_eligibility[backend]
+ previous = self._recovered_runtime_eligibility.pop(runtime, None)
+ if previous is not None and previous != _IMMEDIATE_RECOVERY_ELIGIBILITY:
+ position = bisect_left(index, (previous, runtime_key))
+ if position < len(index) and index[position] == (previous, runtime_key):
+ index.pop(position)
+
+ activities = self._recovered_output_eligibility.get(runtime)
+ if not activities:
+ self._recovered_output_eligibility.pop(runtime, None)
+ if not index:
+ self._recovered_backend_eligibility.pop(backend, None)
+ return
+ current = min(activities.values())
+ self._recovered_runtime_eligibility[runtime] = current
+ if current != _IMMEDIATE_RECOVERY_ELIGIBILITY:
+ insort(index, (current, runtime_key))
+ elif not index:
+ self._recovered_backend_eligibility.pop(backend, None)
+
+ def _add_recovered_output_id(
+ self,
+ activity_key: tuple[str, str, str],
+ activity: SessionActivity,
+ ) -> None:
+ if activity_key in self._recovered_output_ids:
+ return
+ self._recovered_output_ids.add(activity_key)
+ runtime_key = activity_key[:2]
+ self._recovered_output_eligibility.setdefault(runtime_key, {})[
+ activity_key[2]
+ ] = self._recovered_activity_eligibility(activity)
+ self._refresh_recovered_runtime_eligibility(runtime_key)
+ count = self._recovered_output_counts.get(runtime_key, 0) + 1
+ self._recovered_output_counts[runtime_key] = count
+ if count == 1:
+ insort(self._recovered_runtime_keys, runtime_key)
+
+ def _discard_recovered_output_id(
+ self,
+ activity_key: tuple[str, str, str],
+ ) -> None:
+ if activity_key not in self._recovered_output_ids:
+ return
+ self._recovered_output_ids.discard(activity_key)
+ runtime_key = activity_key[:2]
+ eligibility = self._recovered_output_eligibility.get(runtime_key)
+ if eligibility is not None:
+ eligibility.pop(activity_key[2], None)
+ self._refresh_recovered_runtime_eligibility(runtime_key)
+ count = self._recovered_output_counts.get(runtime_key, 0) - 1
+ if count > 0:
+ self._recovered_output_counts[runtime_key] = count
+ return
+ self._recovered_output_counts.pop(runtime_key, None)
+ index = bisect_left(self._recovered_runtime_keys, runtime_key)
+ if (
+ index < len(self._recovered_runtime_keys)
+ and self._recovered_runtime_keys[index] == runtime_key
+ ):
+ self._recovered_runtime_keys.pop(index)
+
def _new_completed_output_entry(
self,
activity: SessionActivity,
@@ -399,7 +493,7 @@ class SessionActivityRegistry:
self._completed_outputs[connection_key].append(
self._new_completed_output_entry(activity)
)
- self._recovered_output_ids.add(key)
+ self._add_recovered_output_id(key, activity)
continue
recovered = (
@@ -766,6 +860,9 @@ class SessionActivityRegistry:
) -> SessionActivity | None:
"""Claim one receipt and return its canonical (last) batch member."""
+ if self.has_claimed_output(backend, runtime_key):
+ return None
+
claimed = self._claim_completed_outputs(
backend,
runtime_key,
@@ -820,6 +917,15 @@ class SessionActivityRegistry:
key = (str(backend), str(runtime_key))
with self._lock:
+ if any(
+ (
+ claimed.entry.activity.backend,
+ claimed.entry.activity.runtime_key,
+ )
+ == key
+ for claimed in self._claimed_completed_outputs.values()
+ ):
+ return []
queue = self._completed_outputs.get(key)
if not queue:
return []
@@ -1175,7 +1281,7 @@ class SessionActivityRegistry:
retained.extend(queue)
self._completed_outputs[key] = retained
raise
- self._recovered_output_ids.discard(activity_key)
+ self._discard_recovered_output_id(activity_key)
continue
turn_id = str(activity.turn_id or "").strip()
if identities is not None and turn_id not in identities:
@@ -1188,7 +1294,7 @@ class SessionActivityRegistry:
activity.metadata.get("_output_local_settlement_only")
),
)
- self._recovered_output_ids.discard(activity_key)
+ self._discard_recovered_output_id(activity_key)
claimed.append(activity)
if retained:
self._completed_outputs[key] = retained
@@ -1217,7 +1323,7 @@ class SessionActivityRegistry:
key = (str(activity.backend), str(activity.runtime_key))
restored_by_runtime[key].append(claimed)
if claimed.recovered:
- self._recovered_output_ids.add(activity_key)
+ self._add_recovered_output_id(activity_key, activity)
for key, restored in restored_by_runtime.items():
entries = list(self._completed_outputs.get(key) or ())
entries.extend(item.entry for item in restored)
@@ -1261,7 +1367,7 @@ class SessionActivityRegistry:
key = (str(activity.backend), str(activity.runtime_key))
restored_by_runtime[key].append(claimed)
if claimed.recovered if recovered is None else recovered:
- self._recovered_output_ids.add(activity_key)
+ self._add_recovered_output_id(activity_key, activity)
for key, restored in restored_by_runtime.items():
entries = list(self._completed_outputs.get(key) or ())
entries.extend(item.entry for item in restored)
@@ -1345,7 +1451,7 @@ class SessionActivityRegistry:
else:
queue.append(self._new_completed_output_entry(activity))
if recovered:
- self._recovered_output_ids.add(activity_key)
+ self._add_recovered_output_id(activity_key, activity)
return True
@staticmethod
@@ -1521,7 +1627,7 @@ class SessionActivityRegistry:
for activity in activities:
activity_key = self._activity_key(activity)
self._claimed_completed_outputs.pop(activity_key, None)
- self._recovered_output_ids.discard(activity_key)
+ self._discard_recovered_output_id(activity_key)
released.append(activity)
callback = self._output_settled_callback
@@ -1594,6 +1700,20 @@ class SessionActivityRegistry:
for claimed in self._claimed_completed_outputs.values()
)
+ def has_claimed_output(self, backend: str, runtime_key: str) -> bool:
+ """Whether one batch already owns transport/local settlement."""
+
+ key = (str(backend), str(runtime_key))
+ with self._lock:
+ return any(
+ (
+ claimed.entry.activity.backend,
+ claimed.entry.activity.runtime_key,
+ )
+ == key
+ for claimed in self._claimed_completed_outputs.values()
+ )
+
def has_pending_run_output(self, run_id: str) -> bool:
identity = str(run_id or "").strip()
if not identity:
@@ -1615,13 +1735,107 @@ class SessionActivityRegistry:
"""Runtime queues containing completion output restored after restart."""
with self._lock:
- runtimes = {
- (entry.activity.backend, entry.activity.runtime_key)
- for queue in self._completed_outputs.values()
- for entry in queue
- if self._activity_key(entry.activity) in self._recovered_output_ids
- }
- return sorted(runtimes)
+ return list(self._recovered_runtime_keys)
+
+ def has_recovered_output(self, backend: str, runtime_key: str) -> bool:
+ with self._lock:
+ return self._recovered_output_counts.get(
+ (str(backend), str(runtime_key)),
+ 0,
+ ) > 0
+
+ def scan_recovered_output_runtimes(
+ self,
+ *,
+ limit: int,
+ cursor: str | None,
+ grace_seconds: Callable[[str], float],
+ ) -> tuple[list[tuple[str, str]], bool, float | None, str | None]:
+ """Return one bounded raw keyset page and global deferred eligibility."""
+
+ page_limit = max(1, int(limit))
+ cursor_key: tuple[str, str] | None = None
+ if cursor and "\x1f" in cursor:
+ backend, runtime_key = cursor.split("\x1f", 1)
+ cursor_key = (backend, runtime_key)
+ instant = datetime.now(timezone.utc)
+ due: list[tuple[str, str]] = []
+ with self._lock:
+ start = (
+ bisect_right(self._recovered_runtime_keys, cursor_key)
+ if cursor_key is not None
+ else 0
+ )
+ raw_page = self._recovered_runtime_keys[start : start + page_limit]
+ for runtime in raw_page:
+ delay = self._recovered_output_delay_seconds_unlocked(
+ runtime,
+ grace_seconds=grace_seconds(runtime[0]),
+ now=instant,
+ )
+ if delay is None:
+ continue
+ if delay <= 0:
+ due.append(runtime)
+ has_more = start + len(raw_page) < len(self._recovered_runtime_keys)
+ retry_after = self._next_recovered_output_delay_seconds_unlocked(
+ grace_seconds=grace_seconds,
+ now=instant,
+ )
+ scanned_cursor = (
+ "\x1f".join(raw_page[-1]) if raw_page else None
+ )
+ return due, has_more, retry_after, scanned_cursor
+
+ def recovered_output_delay_seconds(
+ self,
+ backend: str,
+ runtime_key: str,
+ *,
+ grace_seconds: float,
+ now: datetime | None = None,
+ ) -> float | None:
+ """Return the durable remaining live-batching grace for one runtime."""
+
+ key = (str(backend), str(runtime_key))
+ instant = now or datetime.now(timezone.utc)
+ with self._lock:
+ return self._recovered_output_delay_seconds_unlocked(
+ key,
+ grace_seconds=grace_seconds,
+ now=instant,
+ )
+
+ def _recovered_output_delay_seconds_unlocked(
+ self,
+ key: tuple[str, str],
+ *,
+ grace_seconds: float,
+ now: datetime,
+ ) -> float | None:
+ first = self._recovered_runtime_eligibility.get(key)
+ if first is None:
+ return None
+ if first == _IMMEDIATE_RECOVERY_ELIGIBILITY:
+ return 0.0
+ elapsed = max(0.0, (now - first).total_seconds())
+ return max(0.0, float(grace_seconds) - elapsed)
+
+ def _next_recovered_output_delay_seconds_unlocked(
+ self,
+ *,
+ grace_seconds: Callable[[str], float],
+ now: datetime,
+ ) -> float | None:
+ earliest: float | None = None
+ for backend, entries in self._recovered_backend_eligibility.items():
+ if not entries:
+ continue
+ first = entries[0][0]
+ elapsed = max(0.0, (now - first).total_seconds())
+ delay = max(0.0, float(grace_seconds(backend)) - elapsed)
+ earliest = delay if earliest is None else min(earliest, delay)
+ return earliest
def drain_recovered_terminals(self) -> list[SessionActivity]:
with self._lock:
@@ -1716,7 +1930,7 @@ class SessionActivityRegistry:
for key in [key for key in self._claimed_completed_outputs if key[0] == identity]:
self._claimed_completed_outputs.pop(key, None)
for activity in terminated_pending:
- self._recovered_output_ids.discard(self._activity_key(activity))
+ self._discard_recovered_output_id(self._activity_key(activity))
completed.extend(terminated_pending)
return completed
diff --git a/core/watches.py b/core/watches.py
index cffcefc09..442dd629d 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -7,8 +7,10 @@ import json
import logging
import os
import tempfile
+import threading
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
+from functools import partial
from pathlib import Path
from typing import Any, Optional
from uuid import uuid4
@@ -28,6 +30,12 @@ from core.process_isolation import (
terminate_process_group_by_pgid,
terminate_process_tree_by_pid,
)
+from core.runtime_work import (
+ RuntimeWorkHandler,
+ RuntimeWorkItem,
+ RuntimeWorkLane,
+ RuntimeWorkRegistrationToken,
+)
from core.scheduled_tasks import TaskExecutionRequest, TaskExecutionStore
from storage.background import (
DEFINITION_CYCLE_COLUMNS,
@@ -47,6 +55,15 @@ WATCH_STORE_RECONCILE_FUSE_FAILURES = 3
WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS = 2 * DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS
+def _publish_watch_definitions_updated() -> None:
+ try:
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="watch")
+ except Exception:
+ logger.debug("watch definition wake failed", exc_info=True)
+
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@@ -372,6 +389,7 @@ class ManagedWatchStore:
"a file-backed watch store cannot commit a queued run with the watch row"
)
self._save()
+ _publish_watch_definitions_updated()
return True
if queued_run is None:
landed = self._sqlite.upsert_watch(
@@ -388,6 +406,7 @@ class ManagedWatchStore:
self._reload_after_lost_write(watch.id)
raise
if landed:
+ _publish_watch_definitions_updated()
return True
self.load()
return False
@@ -447,12 +466,15 @@ class ManagedWatchStore:
)
if expected_reference_agent_id is not None:
self.load()
+ _publish_watch_definitions_updated()
return self._watches[watch.id]
+ _publish_watch_definitions_updated()
return watch
self._save()
except Exception:
self._reload_after_lost_write(watch.id)
raise
+ _publish_watch_definitions_updated()
return watch
def add_watch(
@@ -521,11 +543,13 @@ class ManagedWatchStore:
try:
if self._sqlite is not None:
self._sqlite.remove_task(watch_id)
+ _publish_watch_definitions_updated()
return True
self._save()
except Exception:
self._reload_after_lost_write(watch_id)
raise
+ _publish_watch_definitions_updated()
return True
def set_enabled(self, watch_id: str, enabled: bool) -> ManagedWatch:
@@ -766,6 +790,127 @@ class _CycleResult:
timed_out: bool
+@dataclass(frozen=True)
+class _StaleWorkerRecovery:
+ recovered: bool
+ blocked: tuple[tuple[str, dict[str, Any]], ...] = ()
+
+
+class _ManagedWatchRuntimeWorkHandler(RuntimeWorkHandler):
+ def __init__(self, service: "ManagedWatchService") -> None:
+ self.service = service
+
+ def scan(
+ self,
+ *,
+ limit: int,
+ occupied: frozenset[str],
+ cursor: str | None,
+ ) -> tuple[list[RuntimeWorkItem], bool]:
+ del limit, cursor
+ if "managed-watches" in occupied:
+ # Return the partition observation without touching storage. The
+ # supervisor records it as deferred against the live owner and
+ # rewinds once that owner releases, preserving wakes received while
+ # reconciliation is in progress.
+ return [
+ RuntimeWorkItem(
+ "managed-watches",
+ None,
+ rearm_after_process=False,
+ defer_until_partition_release=True,
+ )
+ ], False
+ with self.service._store_worker_lock:
+ recovery = _StaleWorkerRecovery(True)
+ if self.service._recovery_pending:
+ recovery = self.service._inspect_stale_workers()
+ blocked = {
+ watch_id: dict(entry)
+ for watch_id, entry in self.service._unreaped_runtime_entries.items()
+ }
+ blocked.update(
+ (watch_id, dict(entry))
+ for watch_id, entry in recovery.blocked
+ )
+ unblocked = (
+ self.service._inspect_recovery_blocked_watches(blocked)
+ if recovery.recovered and blocked
+ else ()
+ )
+ changed = False
+ watches: tuple[ManagedWatch, ...] = ()
+ store_error: Exception | None = None
+ fused = self.service._store_error_fused
+ if recovery.recovered and not fused:
+ try:
+ changed = self.service.store.maybe_reload()
+ watches = tuple(
+ ManagedWatch.from_dict(watch.to_dict())
+ for watch in self.service.store.list_watches()
+ )
+ except Exception as exc:
+ store_error = exc
+ return [
+ RuntimeWorkItem(
+ "managed-watches",
+ {
+ "recovery": recovery,
+ "unblocked": unblocked,
+ "changed": changed,
+ "watches": watches,
+ "store_error": store_error,
+ "fused": fused,
+ },
+ rearm_after_process=False,
+ )
+ ], False
+
+ async def process(self, item: RuntimeWorkItem) -> bool:
+ observation = item.observation
+ recovery = observation["recovery"]
+ self.service._apply_stale_worker_recovery(recovery)
+ self.service._apply_recovery_unblocked(observation["unblocked"])
+ if not recovery.recovered:
+ self.service._schedule_runtime_work_wake(
+ WATCH_RECONCILE_INTERVAL_SECONDS
+ )
+ return True
+ if self.service._recovery_blocked_watch_ids:
+ self.service._schedule_runtime_work_wake(
+ WATCH_RECONCILE_INTERVAL_SECONDS
+ )
+ self.service._recovery_pending = False
+ if observation["unblocked"]:
+ self.service._reconcile_dirty = True
+ self.service._runtime_state_dirty = True
+ store_error = observation.get("store_error")
+ if store_error is not None:
+ self.service._reconcile_dirty = True
+ self.service._handle_reconcile_store_error(store_error)
+ return self.service._store_error_fused
+ if observation.get("fused") or self.service._store_error_fused:
+ if self.service._runtime_state_dirty:
+ await self.service._persist_runtime_state()
+ return not self.service._runtime_state_dirty
+ return True
+ try:
+ if observation["changed"] or self.service._reconcile_dirty:
+ if self.service.reconcile_watches(observation["watches"]):
+ self.service._runtime_state_dirty = True
+ if self.service._runtime_state_dirty:
+ await self.service._persist_runtime_state()
+ if self.service._runtime_state_dirty:
+ return False
+ self.service._store_reconcile_failures = 0
+ self.service._reconcile_dirty = False
+ return True
+ except Exception as exc:
+ self.service._reconcile_dirty = True
+ self.service._handle_reconcile_store_error(exc)
+ return self.service._store_error_fused
+
+
class ManagedWatchService:
def __init__(
self,
@@ -794,6 +939,12 @@ class ManagedWatchService:
self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
self._reconcile_dirty = True
self._runtime_state_dirty = True
+ self._runtime_state_revision = 0
+ self._store_worker_lock = threading.Lock()
+ self._runtime_work_token: RuntimeWorkRegistrationToken | None = None
+ self._runtime_work_unregistration_task: asyncio.Task[None] | None = None
+ self._legacy_probe_task: asyncio.Task[None] | None = None
+ self._legacy_watch_signature: tuple[int, int, int] | None = None
def _t(self, key: str, **kwargs: Any) -> str:
controller_translator = getattr(self.controller, "_t", None)
@@ -815,9 +966,78 @@ class ManagedWatchService:
self._running = True
self._startup_task = asyncio.create_task(self._start_after_recovery())
+ def _supports_runtime_work_lane(self) -> bool:
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ return callable(getattr(supervisor, "notify", None))
+
+ async def _run_runtime_sync(self, operation, /, *args, **kwargs): # noqa: ANN001, ANN202
+ call = partial(operation, *args, **kwargs)
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ run_sync = getattr(supervisor, "run_sync", None)
+ if callable(run_sync):
+ return await run_sync(call)
+ return await asyncio.to_thread(call)
+
+ def _register_runtime_work_lane(self) -> None:
+ previous = self._runtime_work_unregistration_task
+ if previous is not None:
+ if not previous.done():
+ raise RuntimeError(
+ "managed watch runtime work generation is still stopping"
+ )
+ previous.result()
+ self._runtime_work_unregistration_task = None
+ if self._runtime_work_token is not None:
+ raise RuntimeError("managed watch runtime work generation is already registered")
+ self._runtime_work_token = self.controller.runtime_work_supervisor.register(
+ RuntimeWorkLane.WATCH_DEFINITIONS,
+ _ManagedWatchRuntimeWorkHandler(self),
+ )
+
+ def _begin_runtime_work_unregistration(self) -> asyncio.Task[None] | None:
+ existing = self._runtime_work_unregistration_task
+ if existing is not None:
+ return existing
+ token = self._runtime_work_token
+ if token is None:
+ return None
+ self._runtime_work_token = None
+ task = self.controller.runtime_work_supervisor.begin_unregister(token)
+ self._runtime_work_unregistration_task = task
+ return task
+
+ def _wake_runtime_work(self) -> None:
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ notify = getattr(supervisor, "notify", None)
+ if callable(notify):
+ notify(RuntimeWorkLane.WATCH_DEFINITIONS)
+ else:
+ self._reconcile_dirty = True
+
+ def _schedule_runtime_work_wake(self, delay: float) -> None:
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ notify_after = getattr(supervisor, "notify_after", None)
+ token = self._runtime_work_token
+ if callable(notify_after) and token is not None:
+ notify_after(token, delay)
+
+ async def _legacy_runtime_work_probe(self) -> None:
+ try:
+ while self._running:
+ await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
+ signature = await self._run_runtime_sync(_path_signature, self.store.path)
+ if signature == self._legacy_watch_signature:
+ continue
+ self._legacy_watch_signature = signature
+ self._wake_runtime_work()
+ except asyncio.CancelledError:
+ raise
+
async def _start_after_recovery(self) -> None:
try:
- recovered = await asyncio.to_thread(self._reap_stale_workers)
+ recovery = await self._run_runtime_sync(self._inspect_stale_workers)
+ self._apply_stale_worker_recovery(recovery)
+ recovered = recovery.recovered
except Exception:
recovered = False
logger.exception("Unexpected error during stale watch worker recovery")
@@ -825,7 +1045,7 @@ class ManagedWatchService:
if not self._running or not self._owns_service_instance():
return
self._recovery_pending = not recovered
- if recovered:
+ if recovered and not self._supports_runtime_work_lane():
try:
if self.reconcile_watches():
self._runtime_state_dirty = True
@@ -834,13 +1054,33 @@ class ManagedWatchService:
except Exception as exc:
self._reconcile_dirty = True
self._handle_reconcile_store_error(exc)
- if self._running and self._owns_service_instance():
+ if self._running and self._owns_service_instance() and self._supports_runtime_work_lane():
+ self._register_runtime_work_lane()
+ self._wake_runtime_work()
+ if self.store.sqlite_backend is None:
+ self._legacy_watch_signature = _path_signature(self.store.path)
+ self._legacy_probe_task = asyncio.create_task(
+ self._legacy_runtime_work_probe(),
+ name="watch-runtime-work-legacy-probe",
+ )
+ elif self._running and self._owns_service_instance():
self._reconcile_task = asyncio.create_task(self._watch_store())
finally:
if self._startup_task is asyncio.current_task():
self._startup_task = None
- def _reap_stale_workers(self) -> bool:
+ def _inspect_stale_workers(self) -> _StaleWorkerRecovery:
+ blocked: dict[str, dict[str, Any]] = {}
+
+ def block(watch_id: str, entry: dict[str, Any]) -> None:
+ blocked[watch_id] = dict(entry)
+
+ def result(recovered: bool) -> _StaleWorkerRecovery:
+ return _StaleWorkerRecovery(
+ recovered,
+ tuple((watch_id, entry) for watch_id, entry in blocked.items()),
+ )
+
try:
runtime_state = self.runtime_store.load_for_recovery()
except Exception:
@@ -848,11 +1088,11 @@ class ManagedWatchService:
"Unable to read prior watch runtime state; deferring watch reconciliation",
exc_info=True,
)
- return False
+ return result(False)
if not isinstance(runtime_state, dict):
logger.warning("Prior watch runtime state is malformed; deferring watch reconciliation")
- return False
+ return result(False)
runtime_watches = runtime_state.get("watches")
if not isinstance(runtime_watches, dict) or any(
not isinstance(watch_id, str)
@@ -861,9 +1101,9 @@ class ManagedWatchService:
for watch_id, entry in runtime_watches.items()
):
logger.warning("Prior watch runtime state is malformed; deferring watch reconciliation")
- return False
+ return result(False)
if not runtime_watches:
- return True
+ return result(True)
try:
watches = self.store.list_watches_for_recovery()
@@ -874,7 +1114,7 @@ class ManagedWatchService:
"Unable to read managed watch definitions; deferring watch reconciliation",
exc_info=True,
)
- return False
+ return result(False)
watch_ids = {watch.id for watch in watches}
for watch_id, entry in runtime_watches.items():
@@ -897,7 +1137,7 @@ class ManagedWatchService:
pid,
watch_id,
)
- self._block_watch_after_failed_recovery(watch_id, entry)
+ block(watch_id, entry)
continue
logger.warning(
"Reaping stale watch process group pgid=%s watch_id=%s after its leader exited",
@@ -910,7 +1150,7 @@ class ManagedWatchService:
f"stale watch {watch_id}",
expected_identity=expected_identity,
):
- self._block_watch_after_failed_recovery(watch_id, entry)
+ block(watch_id, entry)
continue
except Exception:
logger.warning(
@@ -919,7 +1159,7 @@ class ManagedWatchService:
watch_id,
exc_info=True,
)
- self._block_watch_after_failed_recovery(watch_id, entry)
+ block(watch_id, entry)
continue
if expected_identity is None:
live_identity = inspect_process_identity(pid)
@@ -940,7 +1180,7 @@ class ManagedWatchService:
pid,
watch_id,
)
- self._block_watch_after_failed_recovery(watch_id, entry)
+ block(watch_id, entry)
continue
try:
live_identity = inspect_process_identity(pid)
@@ -958,7 +1198,7 @@ class ManagedWatchService:
pid,
watch_id,
)
- self._block_watch_after_failed_recovery(watch_id, entry)
+ block(watch_id, entry)
continue
if live_identity.create_time != expected_identity.create_time:
logger.info(
@@ -974,7 +1214,7 @@ class ManagedWatchService:
pid,
watch_id,
)
- self._block_watch_after_failed_recovery(watch_id, entry)
+ block(watch_id, entry)
continue
watch_label = f"stale watch {watch_id}"
@@ -993,18 +1233,34 @@ class ManagedWatchService:
logger.exception("Unexpected error reaping stale watch worker pid=%s watch_id=%s", pid, watch_id)
if not terminated:
logger.error("Failed to reap stale watch worker pid=%s watch_id=%s", pid, watch_id)
- self._block_watch_after_failed_recovery(watch_id, entry)
- return True
+ block(watch_id, entry)
+ return result(True)
+
+ def _apply_stale_worker_recovery(
+ self,
+ recovery: _StaleWorkerRecovery,
+ ) -> None:
+ if not recovery.blocked:
+ return
+ for watch_id, entry in recovery.blocked:
+ self._block_watch_after_failed_recovery(watch_id, entry)
+
+ def _reap_stale_workers(self) -> bool:
+ recovery = self._inspect_stale_workers()
+ self._apply_stale_worker_recovery(recovery)
+ return recovery.recovered
def _block_watch_after_failed_recovery(self, watch_id: str, entry: dict[str, Any]) -> None:
self._recovery_blocked_watch_ids.add(watch_id)
self._unreaped_runtime_entries[watch_id] = dict(entry)
self._runtime_state_dirty = True
- def _recheck_recovery_blocked_watches(self) -> bool:
- unblocked = False
- for watch_id in list(self._recovery_blocked_watch_ids):
- entry = self._unreaped_runtime_entries.get(watch_id)
+ def _inspect_recovery_blocked_watches(
+ self,
+ entries: dict[str, dict[str, Any]],
+ ) -> tuple[str, ...]:
+ unblocked: list[str] = []
+ for watch_id, entry in entries.items():
if not isinstance(entry, dict):
continue
pid = entry.get("pid")
@@ -1057,13 +1313,34 @@ class ManagedWatchService:
"Unblocking recovered watch_id=%s after its prior worker exited",
watch_id,
)
+ unblocked.append(watch_id)
+ return tuple(unblocked)
+
+ def _apply_recovery_unblocked(self, watch_ids: tuple[str, ...]) -> bool:
+ if not watch_ids:
+ return False
+ for watch_id in watch_ids:
self._recovery_blocked_watch_ids.discard(watch_id)
self._unreaped_runtime_entries.pop(watch_id, None)
- unblocked = True
- return unblocked
+ return True
+
+ def _recheck_recovery_blocked_watches(self) -> bool:
+ entries = {
+ watch_id: dict(entry)
+ for watch_id, entry in self._unreaped_runtime_entries.items()
+ if watch_id in self._recovery_blocked_watch_ids
+ }
+ return self._apply_recovery_unblocked(
+ self._inspect_recovery_blocked_watches(entries)
+ )
async def stop(self) -> None:
self._begin_stop()
+ runtime_work_stop = self._begin_runtime_work_unregistration()
+ legacy_probe = self._legacy_probe_task
+ self._legacy_probe_task = None
+ if legacy_probe is not None and legacy_probe is not asyncio.current_task():
+ await asyncio.gather(legacy_probe, return_exceptions=True)
startup_task = self._startup_task
if startup_task and startup_task is not asyncio.current_task():
await startup_task
@@ -1082,7 +1359,11 @@ class ManagedWatchService:
self._active_process_identities.clear()
self._watch_started_at.clear()
self._runtime_state_dirty = True
- self._write_runtime_state()
+ await self._persist_runtime_state()
+ if runtime_work_stop is not None:
+ await runtime_work_stop
+ if self._runtime_work_unregistration_task is runtime_work_stop:
+ self._runtime_work_unregistration_task = None
async def _watch_store(self) -> None:
while self._running:
@@ -1090,7 +1371,9 @@ class ManagedWatchService:
return
if self._recovery_pending:
try:
- recovered = await asyncio.to_thread(self._reap_stale_workers)
+ recovery = await self._run_runtime_sync(self._inspect_stale_workers)
+ self._apply_stale_worker_recovery(recovery)
+ recovered = recovery.recovered
except asyncio.CancelledError:
raise
except Exception:
@@ -1106,9 +1389,19 @@ class ManagedWatchService:
await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
continue
try:
- if self._recovery_blocked_watch_ids and await asyncio.to_thread(
- self._recheck_recovery_blocked_watches
- ):
+ if self._recovery_blocked_watch_ids:
+ blocked = {
+ watch_id: dict(entry)
+ for watch_id, entry in self._unreaped_runtime_entries.items()
+ if watch_id in self._recovery_blocked_watch_ids
+ }
+ unblocked = await self._run_runtime_sync(
+ self._inspect_recovery_blocked_watches,
+ blocked,
+ )
+ else:
+ unblocked = ()
+ if self._apply_recovery_unblocked(unblocked):
self._reconcile_dirty = True
self._runtime_state_dirty = True
should_reconcile = self.store.maybe_reload() or self._reconcile_dirty
@@ -1126,12 +1419,15 @@ class ManagedWatchService:
self._handle_reconcile_store_error(exc)
await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
- def reconcile_watches(self) -> bool:
+ def reconcile_watches(
+ self,
+ watches: tuple[ManagedWatch, ...] | list[ManagedWatch] | None = None,
+ ) -> bool:
if not self._owns_service_instance():
return False
if self._store_error_fused:
return False
- watches = self.store.list_watches()
+ watches = self.store.list_watches() if watches is None else watches
desired_ids = {watch.id for watch in watches if watch.enabled}
changed = False
for watch in watches:
@@ -1160,14 +1456,13 @@ class ManagedWatchService:
self._active_pids.pop(watch_id, None)
self._active_process_identities.pop(watch_id, None)
self._watch_started_at.pop(watch_id, None)
- self._runtime_state_dirty = True
self._write_runtime_state()
self._reconcile_dirty = True
- def _write_runtime_state(self) -> None:
- if self._recovery_pending:
- return
- payload = {
+ def _runtime_state_payload(self) -> dict[str, Any]:
+ """Assemble the loop-owned runtime projection without storage I/O."""
+
+ payload: dict[str, Any] = {
"watches": {
watch_id: dict(entry)
for watch_id, entry in self._unreaped_runtime_entries.items()
@@ -1185,8 +1480,43 @@ class ManagedWatchService:
if identity is not None:
entry["process_identity"] = serialize_process_identity(identity)
payload["watches"][watch_id] = entry
+ return payload
+
+ def _mark_runtime_state_dirty(self) -> None:
+ self._runtime_state_revision += 1
+ self._runtime_state_dirty = True
+ if self._supports_runtime_work_lane() and self._running:
+ self._wake_runtime_work()
+
+ async def _persist_runtime_state(self) -> None:
+ if self._recovery_pending:
+ return
+ revision = self._runtime_state_revision
+ payload = self._runtime_state_payload()
try:
+ await self._run_runtime_sync(self._write_runtime_state_payload, payload)
+ if revision == self._runtime_state_revision:
+ self._runtime_state_dirty = False
+ else:
+ self._wake_runtime_work()
+ except Exception:
+ self._runtime_state_dirty = True
+ logger.exception("Failed to persist watch runtime state")
+
+ def _write_runtime_state_payload(self, payload: dict[str, Any]) -> None:
+ with self._store_worker_lock:
self.runtime_store.write(payload)
+
+ def _write_runtime_state(self) -> None:
+ """Legacy synchronous persistence; production is owned by the lane."""
+
+ self._mark_runtime_state_dirty()
+ if self._supports_runtime_work_lane():
+ return
+ if self._recovery_pending:
+ return
+ try:
+ self._write_runtime_state_payload(self._runtime_state_payload())
self._runtime_state_dirty = False
except Exception:
self._runtime_state_dirty = True
@@ -1237,11 +1567,8 @@ class ManagedWatchService:
case and must not stop the watch. Only the guarded writers opt in.
"""
- try:
+ with self._store_worker_lock:
result = callback()
- except Exception as exc:
- self._fuse_store_after_error(operation, exc, watch_id=watch_id)
- return False
if guarded and result is False:
# NOT a store error: the row is fine, this write simply lost to a
# concurrent lifecycle change. Fusing would disable reconciliation for a
@@ -1255,6 +1582,26 @@ class ManagedWatchService:
return False
return True
+ async def _watch_store_call_async(
+ self,
+ watch_id: str,
+ operation: str,
+ callback,
+ *,
+ guarded: bool = False,
+ ) -> bool:
+ try:
+ return await self._run_runtime_sync(
+ self._watch_store_call,
+ watch_id,
+ operation,
+ callback,
+ guarded=guarded,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(operation, exc, watch_id=watch_id)
+ return False
+
def _current_asyncio_task(self) -> Optional["asyncio.Task[Any]"]:
try:
return asyncio.current_task()
@@ -1263,9 +1610,12 @@ class ManagedWatchService:
def _begin_stop(self, *, cancel_reconcile: bool = True) -> None:
self._running = False
+ self._begin_runtime_work_unregistration()
current_task = self._current_asyncio_task()
if cancel_reconcile and self._reconcile_task and self._reconcile_task is not current_task:
self._reconcile_task.cancel()
+ if self._legacy_probe_task and self._legacy_probe_task is not current_task:
+ self._legacy_probe_task.cancel()
for task in list(self._active_tasks.values()):
if task is not current_task:
task.cancel()
@@ -1292,7 +1642,11 @@ class ManagedWatchService:
return
if watch_id in self._fused_watch_ids:
return
- if not self._watch_store_call(watch_id, "reload", self.store.maybe_reload):
+ if not await self._watch_store_call_async(
+ watch_id,
+ "reload",
+ self.store.maybe_reload,
+ ):
return
watch = self.store.get_watch(watch_id)
if watch is None or not watch.enabled:
@@ -1304,7 +1658,7 @@ class ManagedWatchService:
if remaining_lifetime <= 0:
# ONE DECISION (HFR-269), not a stamp followed by a hook. See
# ``_commit_cycle_result``.
- self._commit_cycle_result(
+ await self._commit_cycle_result_async(
watch,
# Running out of lifetime is a timeout, and the row has
# to be able to say so: ``definition_lifecycle_detail``
@@ -1334,7 +1688,7 @@ class ManagedWatchService:
# refusal means a teardown (``/new`` reclaim, archive) committed after this
# loop read the watch, so the definition it is about to run no longer
# exists in the state this iteration decided from.
- if not self._watch_store_call(
+ if not await self._watch_store_call_async(
watch.id,
"mark_cycle_start",
lambda: self.store.mark_cycle_start(watch.id),
@@ -1343,7 +1697,10 @@ class ManagedWatchService:
return
cwd_error = _missing_watch_cwd_error(watch)
if cwd_error:
- self._stop_watch_for_missing_cwd(watch, error_text=cwd_error)
+ await self._stop_watch_for_missing_cwd_async(
+ watch,
+ error_text=cwd_error,
+ )
return
try:
result = await self._run_cycle(watch, timeout_seconds=cycle_timeout)
@@ -1352,7 +1709,10 @@ class ManagedWatchService:
except Exception as exc:
cwd_error = _missing_watch_cwd_error(watch)
if cwd_error:
- self._stop_watch_for_missing_cwd(watch, error_text=cwd_error)
+ await self._stop_watch_for_missing_cwd_async(
+ watch,
+ error_text=cwd_error,
+ )
return
result = _CycleResult(
exit_code=1,
@@ -1367,7 +1727,7 @@ class ManagedWatchService:
if result.exit_code == 0:
# Building the prompt is pure; the stamp and the hook it authorises are
# committed together (HFR-269).
- if not self._commit_cycle_result(
+ if not await self._commit_cycle_result_async(
watch,
exit_code=0,
error=None,
@@ -1385,13 +1745,16 @@ class ManagedWatchService:
if watch.mode == "forever" and 124 in set(watch.retry_exit_codes):
# A retry authorises no hook: the watch keeps running, and there is
# nothing to tell the user yet.
- if not self._commit_cycle_result(
- watch, exit_code=124, error=error_text, disable=False
+ if not await self._commit_cycle_result_async(
+ watch,
+ exit_code=124,
+ error=error_text,
+ disable=False,
):
return
await asyncio.sleep(watch.retry_delay_seconds)
continue
- self._commit_cycle_result(
+ await self._commit_cycle_result_async(
watch,
exit_code=124,
error=error_text,
@@ -1407,14 +1770,17 @@ class ManagedWatchService:
error_text = _squash_error(result.stderr) or f"watch command exited with status {result.exit_code}"
if watch.mode == "forever" and result.exit_code in set(watch.retry_exit_codes):
- if not self._commit_cycle_result(
- watch, exit_code=result.exit_code, error=error_text, disable=False
+ if not await self._commit_cycle_result_async(
+ watch,
+ exit_code=result.exit_code,
+ error=error_text,
+ disable=False,
):
return
await asyncio.sleep(watch.retry_delay_seconds)
continue
- self._commit_cycle_result(
+ await self._commit_cycle_result_async(
watch,
exit_code=result.exit_code,
error=error_text,
@@ -1577,6 +1943,25 @@ class ManagedWatchService:
self.request_store.enqueue(request)
return True
+ async def _commit_cycle_result_async(
+ self,
+ watch: ManagedWatch,
+ **kwargs: Any,
+ ) -> bool:
+ try:
+ return await self._run_runtime_sync(
+ self._commit_cycle_result,
+ watch,
+ **kwargs,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "mark_cycle_result",
+ exc,
+ watch_id=watch.id,
+ )
+ return False
+
def _stop_watch_for_missing_cwd(self, watch: ManagedWatch, *, error_text: str) -> None:
watch_label = watch.name or watch.id
self._commit_cycle_result(
@@ -1591,6 +1976,26 @@ class ManagedWatchService:
),
)
+ async def _stop_watch_for_missing_cwd_async(
+ self,
+ watch: ManagedWatch,
+ *,
+ error_text: str,
+ ) -> bool:
+ try:
+ return await self._run_runtime_sync(
+ self._stop_watch_for_missing_cwd,
+ watch,
+ error_text=error_text,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "mark_cycle_result",
+ exc,
+ watch_id=watch.id,
+ )
+ return False
+
def _failure_hook_body(watch: ManagedWatch, *, exit_code: int, error_text: str) -> str:
"""The body of the hook that tells the user why a watch stopped failing."""
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 0473fa0b0..0852b2053 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -17,6 +17,7 @@ from core.message_output import (
from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.reply_enhancer import strip_silent_blocks
from core.runtime_activation import RuntimeActivationIdentity
+from core.runtime_work import RuntimeWorkLane
from core.services.agent_steering import (
ActiveSteerTarget,
SteerOutcome,
@@ -2648,6 +2649,11 @@ class ClaudeAgent(BaseAgent):
retain_terminal_snapshot=status != "completed" and not foreground,
activation_identity=activation_identity,
)
+ if completed is not None and status == "completed" and not foreground:
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ notify = getattr(supervisor, "notify", None)
+ if callable(notify):
+ notify(RuntimeWorkLane.ACTIVITY_OUTPUTS)
service = getattr(self.controller, "agent_service", None)
on_terminal = getattr(service, "on_activity_terminal", None)
if completed is not None and not foreground and callable(on_terminal):
@@ -2875,6 +2881,36 @@ class ClaudeAgent(BaseAgent):
) -> bool:
"""Deliver task notifications that ended the receiver without a Result."""
+ supervisor = getattr(self.controller, "runtime_work_supervisor", None)
+ run_in_partition = getattr(supervisor, "run_in_partition", None)
+ if callable(run_in_partition):
+ return await run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ f"{self.name}\x1f{composite_key}",
+ lambda: self._flush_completed_activity_outputs_owned(
+ composite_key,
+ context,
+ expected_steering_generation=expected_steering_generation,
+ allow_closing=allow_closing,
+ ),
+ )
+ return await self._flush_completed_activity_outputs_owned(
+ composite_key,
+ context,
+ expected_steering_generation=expected_steering_generation,
+ allow_closing=allow_closing,
+ )
+
+ async def _flush_completed_activity_outputs_owned(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ *,
+ expected_steering_generation: int | None = None,
+ allow_closing: bool = False,
+ ) -> bool:
+ """Claim, emit, and settle while the exact runtime partition is held."""
+
registry = self._activity_registry()
if registry is None:
return False
diff --git a/storage/background.py b/storage/background.py
index 6b2bea789..44c089946 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1814,7 +1814,7 @@ def _publish_run_rows_updated(rows: list[Any]) -> None:
cancel_requested=bool(row.get("cancel_requested")),
)
bus.publish(RUNS_UPDATED_EVENT, payload)
- if bus.subscriber_count() == 0 and not is_controller_process():
+ if not is_controller_process():
try:
from vibe import internal_client
@@ -1841,7 +1841,7 @@ def _publish_queue_updated(session_id: str) -> None:
payload = {"session_id": normalized_session_id}
try:
bus.publish(QUEUE_UPDATED_EVENT, payload)
- if bus.subscriber_count() == 0 and not is_controller_process():
+ if not is_controller_process():
try:
from vibe import internal_client
@@ -2958,7 +2958,12 @@ class SQLiteBackgroundTaskStore:
values["agent_backend"] = identity["backend"]
enqueue_run_in_connection(conn, values)
- def enqueue_definition_run(self, payload: dict[str, Any]) -> dict[str, Any]:
+ def enqueue_definition_run(
+ self,
+ payload: dict[str, Any],
+ *,
+ suppress_scheduler_successor: bool = False,
+ ) -> Optional[dict[str, Any]]:
"""Enqueue one internally consistent snapshot of a live definition."""
values = self._run_values(payload)
@@ -2967,6 +2972,29 @@ class SQLiteBackgroundTaskStore:
raise ValueError("definition id is required")
with run_update_event_transaction(self.engine) as conn:
reserve_write_lock(conn)
+ if suppress_scheduler_successor:
+ unstarted = conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(agent_runs.c.source_kind == "scheduler")
+ .where(
+ or_(
+ agent_runs.c.status.in_(_status_query_values("queued")),
+ and_(
+ agent_runs.c.status.in_(_status_query_values("running")),
+ agent_runs.c.delivery_id.is_(None),
+ agent_runs.c.pid.is_(None),
+ func.json_extract(
+ agent_runs.c.metadata_json,
+ f"$.{COMMAND_WORKER_METADATA_KEY}",
+ ).is_(None),
+ ),
+ )
+ )
+ .limit(1)
+ ).scalar_one_or_none()
+ if unstarted is not None:
+ return None
definition = conn.execute(
select(
run_definitions.c.definition_type,
@@ -3081,8 +3109,25 @@ class SQLiteBackgroundTaskStore:
_defer_run_ids_updated_from_connection(conn, [cleaned_run_id])
return {"agent_id": canonical_id, "agent_name": canonical_name}
- def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
+ def list_runs(
+ self,
+ *,
+ status: Optional[str] = None,
+ run_types: Optional[Sequence[str]] = None,
+ after: tuple[str, str] | None = None,
+ limit: int | None = None,
+ ) -> list[dict[str, Any]]:
stmt = self._runs_query(status=status).order_by(agent_runs.c.created_at, agent_runs.c.id)
+ included = [value for value in (run_types or ()) if value]
+ if included:
+ stmt = stmt.where(agent_runs.c.run_type.in_(included))
+ if after is not None:
+ stmt = stmt.where(
+ tuple_(agent_runs.c.created_at, agent_runs.c.id)
+ > tuple_(str(after[0]), str(after[1]))
+ )
+ if limit is not None:
+ stmt = stmt.limit(max(0, int(limit)))
with self.engine.connect() as conn:
return [self._run_from_row(row) for row in conn.execute(stmt).mappings()]
@@ -3490,21 +3535,29 @@ class SQLiteBackgroundTaskStore:
deferred.append(self._run_from_row(row))
return deferred
- def list_pending_callbacks(self, *, limit: int = 20) -> list[dict[str, Any]]:
+ def list_pending_callbacks(
+ self,
+ *,
+ limit: int = 20,
+ after: tuple[str, str] | None = None,
+ ) -> list[dict[str, Any]]:
terminal_statuses = _status_query_values("succeeded") + _status_query_values("failed") + _status_query_values("canceled")
- with self.engine.connect() as conn:
- rows = list(
- conn.execute(
- select(agent_runs)
- .where(agent_runs.c.callback_session_id.is_not(None))
- .where(agent_runs.c.callback_session_id != "")
- .where(agent_runs.c.callback_status == "pending")
- .where(agent_runs.c.completed_at.is_not(None))
- .where(agent_runs.c.status.in_(terminal_statuses))
- .order_by(agent_runs.c.completed_at, agent_runs.c.id)
- .limit(limit)
- ).mappings()
+ stmt = (
+ select(agent_runs)
+ .where(agent_runs.c.callback_session_id.is_not(None))
+ .where(agent_runs.c.callback_session_id != "")
+ .where(agent_runs.c.callback_status == "pending")
+ .where(agent_runs.c.completed_at.is_not(None))
+ .where(agent_runs.c.status.in_(terminal_statuses))
+ )
+ if after is not None:
+ stmt = stmt.where(
+ tuple_(agent_runs.c.completed_at, agent_runs.c.id)
+ > tuple_(str(after[0]), str(after[1]))
)
+ stmt = stmt.order_by(agent_runs.c.completed_at, agent_runs.c.id).limit(limit)
+ with self.engine.connect() as conn:
+ rows = list(conn.execute(stmt).mappings())
return [self._run_from_row(row) for row in rows]
def cancel_run(self, run_id: str, *, requested_at: Optional[str] = None) -> bool:
@@ -4035,8 +4088,12 @@ class SQLiteBackgroundTaskStore:
}
if callback_run_id is not None:
values["callback_run_id"] = callback_run_id
- with self.engine.begin() as conn:
- conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+ with run_update_event_transaction(self.engine) as conn:
+ result = conn.execute(
+ update(agent_runs).where(agent_runs.c.id == run_id).values(**values)
+ )
+ if result.rowcount:
+ _defer_run_ids_updated_from_connection(conn, [run_id])
def mark_callback_pending(self, run_id: str, *, updated_at: Optional[str] = None) -> None:
now = updated_at or _utc_now_iso()
@@ -4046,8 +4103,12 @@ class SQLiteBackgroundTaskStore:
"callback_completed_at": None,
"updated_at": now,
}
- with self.engine.begin() as conn:
- conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+ with run_update_event_transaction(self.engine) as conn:
+ result = conn.execute(
+ update(agent_runs).where(agent_runs.c.id == run_id).values(**values)
+ )
+ if result.rowcount:
+ _defer_run_ids_updated_from_connection(conn, [run_id])
def mark_run_queued_from_running(
self,
@@ -4094,13 +4155,7 @@ class SQLiteBackgroundTaskStore:
page_limit = max(1, int(limit))
query = (
- select(
- agent_runs.c.id,
- agent_runs.c.status,
- agent_runs.c.updated_at,
- agent_runs.c.delivery_id,
- agent_runs.c.pid,
- )
+ select(agent_runs)
.where(agent_runs.c.status.in_(_status_query_values("running")))
.where(agent_runs.c.pid.is_(None))
.where(agent_runs.c.delivery_id.is_(None))
@@ -4113,7 +4168,10 @@ class SQLiteBackgroundTaskStore:
if occupied:
query = query.where(~agent_runs.c.id.in_(occupied))
with self.engine.connect() as conn:
- rows = [dict(row) for row in conn.execute(query).mappings()]
+ rows = [
+ self._run_from_row(row)
+ for row in conn.execute(query).mappings()
+ ]
return rows[:page_limit], len(rows) > page_limit
def recover_claimed_pre_execution_run(
@@ -5192,7 +5250,13 @@ class SQLiteBackgroundTaskStore:
# --- owed failure notices -------------------------------------------------
- def list_owed_failure_notices(self, *, limit: int = 20, now: Optional[str] = None) -> list[dict[str, Any]]:
+ def list_owed_failure_notices(
+ self,
+ *,
+ limit: int = 20,
+ now: Optional[str] = None,
+ after: tuple[str, str, str] | None = None,
+ ) -> list[dict[str, Any]]:
"""Runs owing a user-visible failure notice whose backoff has elapsed.
Ordered by ``(created_at, id)`` so the drain sees a streak's earliest row
@@ -5282,8 +5346,13 @@ class SQLiteBackgroundTaskStore:
# canonical notice is chosen by ``failure_streak_decision``, not by arrival
# order — and least-recently-deferred-first is the fairer sequence anyway.
.order_by(next_attempt_at, agent_runs.c.created_at, agent_runs.c.id)
- .limit(max(1, limit))
)
+ if after is not None:
+ stmt = stmt.where(
+ tuple_(next_attempt_at, agent_runs.c.created_at, agent_runs.c.id)
+ > tuple_(str(after[0]), str(after[1]), str(after[2]))
+ )
+ stmt = stmt.limit(max(1, limit))
with self.engine.connect() as conn:
for row in conn.execute(stmt).mappings():
notice = _json_loads(row["metadata_json"], {})
@@ -5301,6 +5370,41 @@ class SQLiteBackgroundTaskStore:
break
return owed
+ def next_owed_failure_notice_at(self, *, now: Optional[str] = None) -> Optional[str]:
+ """Earliest future retry deadline for an otherwise deliverable notice."""
+
+ instant = now or _utc_now_iso()
+ notice_state = literal_column(OWED_NOTICE_STATE_SQL)
+ notice_kind = literal_column(OWED_NOTICE_KIND_SQL)
+ next_attempt_at = literal_column(OWED_NOTICE_NEXT_ATTEMPT_SQL)
+ stmt = (
+ select(next_attempt_at)
+ .where(
+ or_(
+ agent_runs.c.status.in_(
+ [*_status_query_values("failed"), *_status_query_values("succeeded")]
+ ),
+ and_(
+ agent_runs.c.status.in_(_status_query_values("canceled")),
+ notice_kind == NOTICE_KIND_BINDING_CHANGE,
+ ),
+ )
+ )
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(notice_state == NOTICE_PENDING)
+ .where(next_attempt_at > instant)
+ .order_by(next_attempt_at)
+ .limit(1)
+ )
+ with self.engine.connect() as conn:
+ value = conn.execute(stmt).scalar_one_or_none()
+ return str(value) if value else None
+
def stamp_binding_change_notice(
self,
run_id: str,
diff --git a/storage/db.py b/storage/db.py
index c5fe9cd90..6b90c0406 100644
--- a/storage/db.py
+++ b/storage/db.py
@@ -97,15 +97,26 @@ class SqliteInvalidationProbe:
def __init__(self, engine: Engine):
self._connection = engine.connect()
self._last_data_version: int | None = None
+ self._lock = RLock()
def has_external_write(self) -> bool:
- version = int(self._connection.exec_driver_sql("PRAGMA data_version").scalar_one())
- changed = self._last_data_version is not None and version != self._last_data_version
- self._last_data_version = version
- return changed
+ # Runtime work lanes may ask the same store to refresh from separate
+ # executor workers. The probe deliberately owns one persistent
+ # connection, so its read-and-compare operation must remain single-file.
+ with self._lock:
+ version = int(
+ self._connection.exec_driver_sql("PRAGMA data_version").scalar_one()
+ )
+ changed = (
+ self._last_data_version is not None
+ and version != self._last_data_version
+ )
+ self._last_data_version = version
+ return changed
def close(self) -> None:
- self._connection.close()
+ with self._lock:
+ self._connection.close()
def __enter__(self) -> "SqliteInvalidationProbe":
return self
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index f21ab20f3..3d1246229 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -62,6 +62,18 @@ SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
logger = logging.getLogger(__name__)
+def _publish_definition_reclaim_hint() -> None:
+ """Wake both definition owners after a committed Session teardown."""
+
+ try:
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="scheduled")
+ publish_definitions_updated(definition_type="watch")
+ except Exception:
+ logger.debug("session definition reclaim wake failed", exc_info=True)
+
+
def _require_enabled_agent_identity(
conn: Connection,
*,
@@ -457,7 +469,11 @@ class SQLiteSessionsService:
row = self.get_agent_session_by_id(str(session_id))
if row is None:
return False
- with reclaim_ledger_transaction(), self.engine.begin() as conn:
+ from storage.background import run_update_event_transaction
+
+ with reclaim_ledger_transaction(), run_update_event_transaction(
+ self.engine
+ ) as conn:
reserve_write_lock(conn)
deleted = _delete_agent_session_rows(
conn,
@@ -1122,23 +1138,29 @@ class SQLiteSessionsService:
reclaim_reason: str | None = None,
) -> bool:
now = _utc_now_iso()
+ from storage.background import run_update_event_transaction
+
# ``reclaim_ledger_transaction`` OUTSIDE ``begin()``: every transaction that can
# reclaim a definition must discard its ledger entries if it does not commit
# (HFR-273), and the truncation has to run after the rollback.
- with reclaim_ledger_transaction(), self.engine.begin() as conn:
+ deleted = 0
+ with reclaim_ledger_transaction(), run_update_event_transaction(
+ self.engine
+ ) as conn:
scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
- if scope_id is None:
- return False
- deleted = _delete_agent_session_rows(
- conn,
- select(agent_sessions.c.id)
- .where(agent_sessions.c.scope_id == scope_id)
- .where(_agent_session_name_predicate(str(agent_name) or "default"))
- .where(agent_sessions.c.session_anchor == str(session_anchor)),
- reclaim_mode=reclaim_mode,
- reclaim_reason=reclaim_reason,
- )
- return bool(deleted)
+ if scope_id is not None:
+ deleted = _delete_agent_session_rows(
+ conn,
+ select(agent_sessions.c.id)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .where(_agent_session_name_predicate(str(agent_name) or "default"))
+ .where(agent_sessions.c.session_anchor == str(session_anchor)),
+ reclaim_mode=reclaim_mode,
+ reclaim_reason=reclaim_reason,
+ )
+ if scope_id is not None:
+ _publish_definition_reclaim_hint()
+ return bool(deleted)
def delete_agent_sessions(
self,
@@ -1151,21 +1173,31 @@ class SQLiteSessionsService:
include_superseded: bool = False,
) -> int:
now = _utc_now_iso()
- with reclaim_ledger_transaction(), self.engine.begin() as conn:
+ deleted = 0
+ from storage.background import run_update_event_transaction
+
+ with reclaim_ledger_transaction(), run_update_event_transaction(
+ self.engine
+ ) as conn:
scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
if scope_id is None:
- return 0
- stmt = select(agent_sessions.c.id).where(agent_sessions.c.scope_id == scope_id)
- if agent_name is not None:
- stmt = stmt.where(_agent_session_name_predicate(str(agent_name) or "default"))
- if session_anchor_prefix is not None:
+ stmt = None
+ else:
+ stmt = select(agent_sessions.c.id).where(
+ agent_sessions.c.scope_id == scope_id
+ )
+ if stmt is not None and agent_name is not None:
+ stmt = stmt.where(
+ _agent_session_name_predicate(str(agent_name) or "default")
+ )
+ if stmt is not None and session_anchor_prefix is not None:
prefix = str(session_anchor_prefix)
prefix_pattern = f"{_escape_sql_like(prefix)}:%"
stmt = stmt.where(
(agent_sessions.c.session_anchor == prefix)
| (agent_sessions.c.session_anchor.like(prefix_pattern, escape="\\"))
)
- if not include_superseded:
+ if stmt is not None and not include_superseded:
# A superseded row carries ``<original_anchor>:superseded:<id>``.
# This is a HARD delete and superseding deliberately keeps the row
# -- its native id is write-once and its history is not
@@ -1197,12 +1229,16 @@ class SQLiteSessionsService:
),
)
)
- return _delete_agent_session_rows(
- conn,
- stmt,
- reclaim_mode=reclaim_mode,
- reclaim_reason=reclaim_reason,
- )
+ if stmt is not None:
+ deleted = _delete_agent_session_rows(
+ conn,
+ stmt,
+ reclaim_mode=reclaim_mode,
+ reclaim_reason=reclaim_reason,
+ )
+ if scope_id is not None:
+ _publish_definition_reclaim_hint()
+ return deleted
def load_state(self) -> SessionState:
with self.engine.connect() as conn:
@@ -2248,10 +2284,18 @@ def _delete_agent_session_rows(
# cancel-shaped guard could ever see it. The cancel below closes that.
from storage.background import (
TEARDOWN_CONDEMNED_RUN_STATUSES,
+ _defer_run_ids_updated_from_connection,
rearm_notices_for_escalations_canceled_with_session,
)
rearm_notices_for_escalations_canceled_with_session(conn, session_id, now=now)
+ condemned_run_ids = list(
+ conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.session_id == session_id)
+ .where(agent_runs.c.status.in_(TEARDOWN_CONDEMNED_RUN_STATUSES))
+ ).scalars()
+ )
# Also before the branch, and for the same reason. ``agent_runs.session_id``
# carries no foreign key, so deleting the Session row leaves its runs ``queued``
# and claimable against a Session that is gone -- and for an escalation that is
@@ -2273,6 +2317,7 @@ def _delete_agent_session_rows(
.where(agent_runs.c.status.in_(("pending", "queued")))
.values(status="canceled", completed_at=now, updated_at=now)
)
+ _defer_run_ids_updated_from_connection(conn, condemned_run_ids)
has_retained_history = bool(
conn.execute(
select(messages.c.id)
diff --git a/storage/vault_service.py b/storage/vault_service.py
index c32ae8cf9..77dbce147 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -25,7 +25,7 @@ from datetime import datetime, timedelta, timezone
from typing import Any
from urllib.parse import urlsplit
-from sqlalchemy import func, or_, select
+from sqlalchemy import func, or_, select, tuple_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
@@ -1442,13 +1442,38 @@ def expire_overdue_requests(conn: Connection) -> None:
_expire_pending_requests(conn)
-def list_pending_request_callbacks(conn: Connection, *, limit: int | None = None) -> list[dict[str, Any]]:
+def earliest_pending_request_expiry(conn: Connection) -> datetime | None:
+ """Return the next durable request-expiry deadline, if one exists."""
+
+ expires_at = conn.execute(
+ select(vault_requests.c.expires_at)
+ .where(
+ vault_requests.c.status == "pending",
+ vault_requests.c.expires_at.is_not(None),
+ )
+ .order_by(vault_requests.c.expires_at)
+ .limit(1)
+ ).scalar_one_or_none()
+ return _parse_iso_datetime(str(expires_at) if expires_at is not None else None)
+
+
+def list_pending_request_callbacks(
+ conn: Connection,
+ *,
+ limit: int | None = None,
+ after: tuple[str, str] | None = None,
+) -> list[dict[str, Any]]:
"""Terminal requests owed an auto-resume callback (``callback_status='pending'``)."""
query = (
select(vault_requests)
.where(vault_requests.c.callback_status == "pending")
- .order_by(vault_requests.c.decided_at, vault_requests.c.id)
)
+ if after is not None:
+ query = query.where(
+ tuple_(vault_requests.c.decided_at, vault_requests.c.id)
+ > tuple_(str(after[0]), str(after[1]))
+ )
+ query = query.order_by(vault_requests.c.decided_at, vault_requests.c.id)
if limit is not None:
query = query.limit(limit)
rows = conn.execute(query).mappings()
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 799a9a24c..aa1d85863 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -2540,6 +2540,181 @@ scenarios:
layer: contract
backend: shared
test: tests/test_runtime_work_supervisor.py::test_hfr_154_replacing_live_registration_requires_generation_handoff
+ - id: HFR-155
+ name: runtime work hints wake only their mapped durable lanes
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_155_events_wake_only_their_durable_lanes
+ - id: HFR-156
+ name: socket hint failure cannot roll back committed durable work
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_inbox_events.py::test_hfr_156_bridge_failure_does_not_rollback_committed_run
+ - id: HFR-157
+ name: startup and slow reconciliation recover lost runtime work hints
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_152_supervisor_starts_paused_and_periodic_reconcile_wakes_lane
+ - id: HFR-158
+ name: occupied partitions cannot hide later actionable work
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_158_request_scan_fills_page_across_recovery_and_queued_work
+ - id: HFR-159
+ name: blocking store scans do not block the controller loop or other lanes
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_159_blocked_store_scan_does_not_block_another_lane
+ - id: HFR-160
+ name: live and recovered work share one exact partition owner
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_160_canceled_sync_worker_remains_owner_until_thread_exits
+ - id: HFR-161
+ name: scheduled work admits one queued successor through one request owner
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_161_scheduler_only_enqueues_one_successor_behind_active_work
+ - id: HFR-162
+ name: a final-scan wake is retained and rearmed after failure
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_162_wake_during_final_empty_scan_is_not_lost
+ - id: HFR-163
+ name: runtime work lanes enforce global and per-partition single flight
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_163_lane_capacity_bounds_distinct_partition_workers
+ - id: HFR-164
+ name: service restart joins only its own runtime work registrations
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_164_hfr_165_service_restart_joins_only_its_harness_lane_generations
+ - id: HFR-165
+ name: repeated service cycles leave one current registration generation
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_164_hfr_165_service_restart_joins_only_its_harness_lane_generations
+ - id: HFR-166
+ name: recovered Activity batches retain durable live batching grace
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_session_activities.py::test_hfr_166_recovered_unbound_grace_uses_first_durable_completion
+ - id: HFR-167
+ name: accepted Activity output retries local settlement without transport replay
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_message_dispatcher_scheduled.py::MessageDispatcherScheduledTests::test_recovered_durable_message_retries_only_local_settlement_after_restart
+ - id: HFR-168
+ name: incomplete recovered Activity batches fail closed before transport
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_session_activities.py::test_recovery_marks_an_incomplete_persisted_output_batch_for_fail_closed_emit
+ - id: HFR-169
+ name: Activity recovery remains visible without a Run projection
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_169_recovered_activity_without_run_reaches_its_session
+ - id: HFR-170
+ name: skipped runtime work rearms with bounded backoff
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_170_guarded_noop_uses_partition_backoff
+ - id: HFR-171
+ name: overdue runtime work identifies lane partition and generation
+ status: covered
+ kind: observability
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_171_overdue_report_names_lane_partition_and_generation
+ - id: HFR-172
+ name: definition hints follow commit and exclude rollback or losing CAS
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_172_task_definition_wake_follows_commit_and_not_rollback
+ - id: HFR-173
+ name: local event fanout and bounded bridge echo dedupe deliver once
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_inbox_bridge.py::test_hfr_173_local_event_echo_is_suppressed_once
+ - id: HFR-174
+ name: task and watch definition commits wake separate reconcile owners
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_watches.py::test_hfr_174_watch_definition_commit_emits_watch_hint
+ - id: HFR-175
+ name: global lease loss stops and joins every runtime work registration
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_runtime_work_supervisor.py::test_hfr_175_global_lease_loss_joins_every_registration
+ - id: HFR-176
+ name: legacy file signatures wake only their mapped runtime work lanes
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_176_legacy_file_probes_wake_only_their_mapped_lanes
+ - id: HFR-177
+ name: transport readiness directly resumes skipped request admission
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_hfr_177_transport_ready_wakes_requests_and_resumes_skipped_run
+ - id: HFR-178
+ name: loop-owned shutdown retains supervisor join past outer grace
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_controller_dispatch_loop.py::test_request_shutdown_keeps_loop_owned_supervisor_join_alive_after_grace
+ - id: HFR-179
+ name: managed-watch store work stays single-flight and applies on loop
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ test: tests/test_watches.py::test_hfr_179_watch_store_phases_are_single_flight_and_apply_on_loop
- id: HFR-240
name: the backend-wide clear does not delete a superseded row
status: covered
@@ -3590,6 +3765,75 @@ scenarios:
# A rename the mirror has NOT absorbed needs nothing: it bumps the agent binding
# revision and the compare-and-set refuses both halves.
test: tests/test_watches.py::test_a_hook_queued_after_a_rename_names_an_agent_that_still_exists
+ - id: HFR-282
+ name: scheduled task mirror mutations serialize with reloads through commit
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # A scheduler result stamp reads, mutates, and persists one full definition row.
+ # Reloading the mirror inside that window could replace the object being stamped,
+ # leaving the live mirror enabled after the durable one-shot task was disabled.
+ # Every mirror mutation now holds the same re-entrant lock as reload and snapshot.
+ test: tests/test_scheduled_tasks.py::test_hfr_282_task_reload_waits_for_result_stamp_mirror_commit
+ - id: HFR-283
+ name: session archive wakes cancellation processing after its Run commit
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # Archive flags active Runs with raw SQL. The post-commit UI path must publish the
+ # ordinary runs.updated hint so STALE_RUNS promptly propagates command cancellation;
+ # a lost hint remains recoverable by periodic reconciliation.
+ test: tests/test_ui_server_fastapi.py::test_hfr_283_archive_run_cancellations_wake_runtime_consumers
+ - id: HFR-284
+ name: controller delivery recovery joins before final Turn owner release
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Quiesce rejects new scans but does not join a worker already admitted. Controller-
+ # generation lanes are invalidated and joined while the executor remains available,
+ # before ScheduledTaskService takes its final durable owner snapshot.
+ test: tests/test_controller_dispatch_loop.py::test_hfr_284_runtime_work_stack_joins_controller_lanes_before_service_teardown
+ - id: HFR-285
+ name: deferred Activity recovery scans bounded raw pages with indexed eligibility
+ status: covered
+ kind: liveness
+ layer: contract
+ backend: shared
+ # A page limit bounds inspected runtime rows, not only due outputs. Deferred grace
+ # entries advance the keyset cursor while a per-backend index supplies the earliest
+ # future deadline without walking every recovered runtime under the Registry lock.
+ test: tests/test_session_activities.py::test_hfr_285_deferred_runtime_scan_bounds_raw_rows_and_indexes_deadline
+ - id: HFR-286
+ name: Run cancellation hints bypass stale sweep eligibility
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # runs.updated always admits the cancellation observer as its own item. The periodic
+ # stale sweep keeps its configured cadence and cannot delay an in-flight command Stop.
+ test: tests/test_scheduled_tasks.py::test_hfr_286_cancellation_wake_is_not_gated_by_stale_sweep_cadence
+ - id: HFR-287
+ name: new-session teardown publishes committed Run cancellations
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # Every SessionMappingStore teardown uses the Run event transaction. Raw SQL changes
+ # remain invisible before commit and wake cancellation/callback consumers afterward.
+ test: tests/test_session_archive.py::test_hfr_287_new_session_teardown_publishes_run_updates_after_commit
+ - id: HFR-288
+ name: expired partition backoff preserves forward scan before retry rewind
+ status: covered
+ kind: liveness
+ layer: contract
+ backend: shared
+ # An expired bounded retry frees admission capacity without rewinding over the same
+ # unavailable prefix. The lane reaches later partitions, then coalesces expired retry
+ # work into one tail-boundary rewind while the durable store retains the inventory.
+ test: tests/test_runtime_work_supervisor.py::test_hfr_288_expired_backoff_preserves_forward_scan_before_retry
- id: HFR-430
name: an Agent Run can apply the Workbench send-now transition to a busy Session
status: covered
diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.py
index 25493c3fa..b770d6aef 100644
--- a/tests/test_claude_agent_initiated_turn.py
+++ b/tests/test_claude_agent_initiated_turn.py
@@ -858,10 +858,6 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
[activity.id for activity in pending_request.output_activities],
["task-current-a", "task-current-b"],
)
- detached = service.activities.claim_completed_output("claude", composite_key)
- self.assertIsNotNone(detached)
- self.assertEqual(detached.id, "task-detached")
- service.activities.ack_completed_output(detached)
self.assertTrue(
service.activities.settle_completed_output_batch(
pending_request.output,
@@ -869,6 +865,10 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
)
)
agent._clear_request_activities(pending_request)
+ detached = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(detached)
+ self.assertEqual(detached.id, "task-detached")
+ service.activities.ack_completed_output(detached)
async def test_terminal_only_task_event_keeps_current_turn_origin(self):
agent, service = _build_agent()
@@ -2366,7 +2366,6 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
async def test_requeued_activity_batch_preserves_fifo_order(self):
agent, service = _build_agent()
composite_key = "session-requeued-batch-order:/tmp/work"
- claimed = []
for activity_id in ("task-build", "task-rebuild"):
service.activities.start(
backend="claude",
@@ -2383,9 +2382,14 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
status="completed",
expects_output=True,
)
- activity = service.activities.claim_completed_output("claude", composite_key)
- self.assertIsNotNone(activity)
- claimed.append(activity)
+ claimed = service.activities.claim_completed_output_batch(
+ "claude",
+ composite_key,
+ )
+ self.assertEqual(
+ [activity.id for activity in claimed],
+ ["task-build", "task-rebuild"],
+ )
request = SimpleNamespace(
output_activities=claimed,
output=agent._activity_message_output(
@@ -2397,17 +2401,15 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
agent._requeue_request_activity(request)
- retried = [
- service.activities.claim_completed_output("claude", composite_key),
- service.activities.claim_completed_output("claude", composite_key),
- ]
+ retried = service.activities.claim_completed_output_batch(
+ "claude",
+ composite_key,
+ )
self.assertEqual(
- [activity.id for activity in retried if activity is not None],
+ [activity.id for activity in retried],
["task-build", "task-rebuild"],
)
- for activity in retried:
- self.assertIsNotNone(activity)
- service.activities.ack_completed_output(activity)
+ self.assertEqual(service.activities.requeue_completed_outputs(retried), 2)
async def test_failed_pending_batch_restores_older_global_output_order(self):
agent, service = _build_agent()
@@ -2454,6 +2456,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
composite_key,
):
restored.append(activity)
+ service.activities.ack_completed_output(activity)
self.assertEqual(
[activity.id for activity in restored],
["task-old", "task-current-b"],
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index 73a1b73ba..09f34cecd 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -334,7 +334,13 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:
controller = Controller.__new__(Controller)
loop = asyncio.new_event_loop()
controller._loop = loop
- stopped: dict[str, bool] = {"watch": False, "tasks": False, "runtime": False}
+ stopped: dict[str, bool] = {
+ "watch": False,
+ "tasks": False,
+ "supervisor": False,
+ "runtime": False,
+ }
+ stop_order: list[str] = []
class _Stopper:
def __init__(self, key: str) -> None:
@@ -342,9 +348,24 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:
async def stop(self) -> None:
stopped[self.key] = True
+ stop_order.append(self.key)
+
+ class _Supervisor(_Stopper):
+ def quiesce(self) -> None:
+ stop_order.append("quiesce")
+
+ async def run_sync(self, operation): # noqa: ANN001, ANN202
+ assert not stopped["supervisor"]
+ return operation()
+
+ class _WatchStopper(_Stopper):
+ async def stop(self) -> None:
+ await controller.runtime_work_supervisor.run_sync(lambda: None)
+ await super().stop()
controller.scheduled_task_service = _Stopper("tasks")
- controller.watch_service = _Stopper("watch")
+ controller.runtime_work_supervisor = _Supervisor("supervisor")
+ controller.watch_service = _WatchStopper("watch")
controller.runtime_command_watcher = _Stopper("runtime")
controller.update_checker = type("UpdateChecker", (), {"stop": lambda self: None})()
controller.receiver_tasks = {}
@@ -358,7 +379,95 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:
assert stopped["tasks"] is True
assert stopped["watch"] is True
+ assert stopped["supervisor"] is True
assert stopped["runtime"] is True
+ assert stop_order[0] == "quiesce"
+ assert set(stop_order[1:3]) == {"tasks", "watch"}
+ assert stop_order[3] == "supervisor"
+
+
+async def test_runtime_work_stack_stops_supervisor_after_service_failure() -> None:
+ controller = Controller.__new__(Controller)
+ controller._shutdown_tainted = False
+ stopped: list[str] = []
+
+ class _Service:
+ def __init__(self, name: str, *, fail: bool = False) -> None:
+ self.name = name
+ self.fail = fail
+
+ async def stop(self) -> None:
+ stopped.append(self.name)
+ if self.fail:
+ raise RuntimeError(f"{self.name} failed")
+
+ class _Supervisor:
+ def quiesce(self) -> None:
+ stopped.append("quiesce")
+
+ async def stop(self) -> None:
+ stopped.append("supervisor")
+
+ controller.scheduled_task_service = _Service("tasks", fail=True)
+ controller.watch_service = _Service("watch")
+ controller.runtime_work_supervisor = _Supervisor()
+
+ with pytest.raises(RuntimeError, match="runtime work stack shutdown failed"):
+ await controller._stop_runtime_work_stack()
+
+ assert stopped[0] == "quiesce"
+ assert set(stopped[1:3]) == {"tasks", "watch"}
+ assert stopped[3] == "supervisor"
+ assert controller._shutdown_tainted is True
+
+
+async def test_hfr_284_runtime_work_stack_joins_controller_lanes_before_service_teardown() -> None:
+ controller = Controller.__new__(Controller)
+ controller._shutdown_tainted = False
+ controller._runtime_work_tokens = [object()]
+ join_entered = asyncio.Event()
+ release_join = asyncio.Event()
+ stopped: list[str] = []
+
+ class _Service:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+ async def stop(self) -> None:
+ stopped.append(self.name)
+
+ class _Supervisor:
+ def quiesce(self) -> None:
+ stopped.append("quiesce")
+
+ def begin_unregister(self, _token): # noqa: ANN001, ANN202
+ async def _join() -> None:
+ join_entered.set()
+ await release_join.wait()
+ stopped.append("controller-lanes")
+
+ return asyncio.create_task(_join())
+
+ async def stop(self) -> None:
+ stopped.append("supervisor")
+
+ controller.scheduled_task_service = _Service("tasks")
+ controller.watch_service = _Service("watch")
+ controller.runtime_work_supervisor = _Supervisor()
+
+ shutdown = asyncio.create_task(controller._stop_runtime_work_stack())
+ await asyncio.wait_for(join_entered.wait(), 1)
+ assert stopped == ["quiesce"]
+
+ release_join.set()
+ await shutdown
+
+ assert stopped[1] == "controller-lanes"
+ assert set(stopped[2:4]) == {"tasks", "watch"}
+ assert stopped[4] == "supervisor"
+ assert controller._runtime_work_tokens == []
def test_request_shutdown_keeps_loop_owned_supervisor_join_alive_after_grace() -> None:
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index f80be2bc7..3ed9c2b1d 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -1482,8 +1482,13 @@ def test_a_notice_whose_backoff_has_not_elapsed_is_not_listed(tmp_path: Path) ->
)
assert sqlite.list_owed_failure_notices(now="2026-07-27T11:00:00+00:00") == []
+ assert (
+ sqlite.next_owed_failure_notice_at(now="2026-07-27T11:00:00+00:00")
+ == "2026-07-27T12:00:00+00:00"
+ )
ready = sqlite.list_owed_failure_notices(now="2026-07-27T13:00:00+00:00")
assert [item["id"] for item in ready] == [run.id]
+ assert sqlite.next_owed_failure_notice_at(now="2026-07-27T13:00:00+00:00") is None
def test_a_sent_notice_is_not_listed_again(tmp_path: Path) -> None:
diff --git a/tests/test_inbox_bridge.py b/tests/test_inbox_bridge.py
index e2a4d2c23..f58b09250 100644
--- a/tests/test_inbox_bridge.py
+++ b/tests/test_inbox_bridge.py
@@ -52,3 +52,48 @@ def test_inbox_bridge_tracks_current_status(monkeypatch):
("workbench.events.bridge.status", {"connected": True}),
("workbench.events.bridge.status", {"connected": False}),
]
+
+
+def test_hfr_173_local_event_echo_is_suppressed_once(monkeypatch):
+ from vibe import inbox_bridge
+
+ published = []
+ inbox_bridge._bridge_connected = False
+ inbox_bridge._local_event_ids.clear()
+ inbox_bridge._local_event_order.clear()
+ inbox_bridge.remember_local_event("event-1")
+
+ async def stream_events():
+ yield "vaults.updated", {"_event_id": "event-1", "scope": "request"}
+ yield "vaults.updated", {"_event_id": "event-1", "scope": "request"}
+
+ async def stop_after_disconnect(_delay):
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(inbox_bridge.internal_client, "stream_events", stream_events)
+ monkeypatch.setattr(
+ inbox_bridge.broker,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ monkeypatch.setattr(inbox_bridge.asyncio, "sleep", stop_after_disconnect)
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(inbox_bridge.run_inbox_bridge())
+
+ assert published == [
+ ("vaults.updated", {"_event_id": "event-1", "scope": "request"}),
+ ]
+
+
+def test_hfr_173_local_event_dedupe_is_bounded():
+ from vibe import inbox_bridge
+
+ inbox_bridge._local_event_ids.clear()
+ inbox_bridge._local_event_order.clear()
+ for index in range(inbox_bridge._LOCAL_EVENT_IDS_MAX + 3):
+ inbox_bridge.remember_local_event(f"event-{index}")
+
+ assert len(inbox_bridge._local_event_ids) == inbox_bridge._LOCAL_EVENT_IDS_MAX
+ assert "event-0" not in inbox_bridge._local_event_ids
+ assert f"event-{inbox_bridge._LOCAL_EVENT_IDS_MAX + 2}" in inbox_bridge._local_event_ids
diff --git a/tests/test_inbox_events.py b/tests/test_inbox_events.py
index 37ede020b..30aa302cf 100644
--- a/tests/test_inbox_events.py
+++ b/tests/test_inbox_events.py
@@ -164,7 +164,7 @@ def test_sqlite_background_store_publishes_run_updates(tmp_path):
assert failed[1]["status"] == "failed"
-def test_sqlite_background_store_bridges_run_updates_without_local_subscribers(tmp_path, monkeypatch):
+def test_hfr_156_sqlite_commit_bridges_run_update_to_controller(tmp_path, monkeypatch):
from core import inbox_events
from storage.background import SQLiteBackgroundTaskStore
@@ -204,6 +204,36 @@ def test_sqlite_background_store_bridges_run_updates_without_local_subscribers(t
]
+def test_hfr_156_bridge_failure_does_not_rollback_committed_run(tmp_path, monkeypatch):
+ from core import inbox_events
+ from storage.background import SQLiteBackgroundTaskStore
+
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", False)
+
+ def _fail_bridge(*_args, **_kwargs):
+ raise OSError("dispatch socket unavailable")
+
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", _fail_bridge)
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ store.enqueue_run(
+ {
+ "id": "run_evt_bridge_failure",
+ "request_type": "agent_run",
+ "status": "queued",
+ "message": "hello",
+ "created_at": "2026-07-04T00:00:00+00:00",
+ "updated_at": "2026-07-04T00:00:00+00:00",
+ }
+ )
+ persisted = store.get_run("run_evt_bridge_failure")
+ finally:
+ store.close()
+
+ assert persisted is not None
+ assert persisted["status"] == "queued"
+
+
def test_sqlite_background_store_does_not_bridge_controller_self_updates(tmp_path, monkeypatch):
from core import inbox_events
from storage.background import SQLiteBackgroundTaskStore
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index d997b7e79..b8b168084 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -427,22 +427,34 @@ async def _publish_event_round_trip():
"data": {"session_id": "ses_queue"},
},
)
+ definitions_resp = await client.post(
+ "/internal/events",
+ json={
+ "type": "definitions.updated",
+ "data": {"definition_type": "scheduled"},
+ },
+ )
bad_resp = await client.post("/internal/events", json={"type": "unsupported", "data": {}})
events = [
await asyncio.wait_for(queue.get(), timeout=1.0),
await asyncio.wait_for(queue.get(), timeout=1.0),
+ await asyncio.wait_for(queue.get(), timeout=1.0),
]
- return resp, queue_resp, bad_resp, events
+ return resp, queue_resp, definitions_resp, bad_resp, events
finally:
inbox_events.bus.unsubscribe(sub_id)
def test_publish_event_endpoint_emits_allowlisted_bus_event():
- resp, queue_resp, bad_resp, events = asyncio.run(_publish_event_round_trip())
+ resp, queue_resp, definitions_resp, bad_resp, events = asyncio.run(
+ _publish_event_round_trip()
+ )
assert resp.status_code == 200
assert resp.json() == {"ok": True}
assert queue_resp.status_code == 200
assert queue_resp.json() == {"ok": True}
+ assert definitions_resp.status_code == 200
+ assert definitions_resp.json() == {"ok": True}
assert bad_resp.status_code == 400
assert events == [
(
@@ -450,6 +462,7 @@ def test_publish_event_endpoint_emits_allowlisted_bus_event():
{"scope": "request", "request_id": "vreq_1", "request_status": "pending"},
),
("queue.updated", {"session_id": "ses_queue"}),
+ ("definitions.updated", {"definition_type": "scheduled"}),
]
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 210080ed3..624988a5f 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -582,7 +582,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNotNone(activity)
activity_key = registry._activity_key(activity)
with registry._lock:
- registry._recovered_output_ids.add(activity_key)
+ registry._add_recovered_output_id(activity_key, activity)
service = object.__new__(ScheduledTaskService)
service.controller = controller
diff --git a/tests/test_runtime_work_supervisor.py b/tests/test_runtime_work_supervisor.py
index 66f863486..5c15dd23a 100644
--- a/tests/test_runtime_work_supervisor.py
+++ b/tests/test_runtime_work_supervisor.py
@@ -6,7 +6,13 @@ from dataclasses import dataclass
import pytest
-from core.inbox_events import QUEUE_UPDATED_EVENT, bus
+from core.inbox_events import (
+ DEFINITIONS_UPDATED_EVENT,
+ QUEUE_UPDATED_EVENT,
+ RUNS_UPDATED_EVENT,
+ VAULTS_UPDATED_EVENT,
+ bus,
+)
from core.runtime_work import (
RuntimeWorkHandler,
RuntimeWorkItem,
@@ -97,7 +103,7 @@ async def test_hfr_151_supervisor_coalesces_wakes_and_keeps_partition_single_fli
@pytest.mark.anyio
-async def test_hfr_151_guarded_noop_uses_partition_backoff() -> None:
+async def test_hfr_170_guarded_noop_uses_partition_backoff() -> None:
"""HFR-151: a stale guarded no-op cannot become a tight retry loop."""
attempted = asyncio.Event()
@@ -105,7 +111,7 @@ async def test_hfr_151_guarded_noop_uses_partition_backoff() -> None:
release_backoff = asyncio.Event()
async def controlled_backoff(delay: float) -> None:
- assert delay == 0.1
+ assert delay == pytest.approx(0.1, abs=0.01)
backoff_entered.set()
await release_backoff.wait()
@@ -123,9 +129,517 @@ async def test_hfr_151_guarded_noop_uses_partition_backoff() -> None:
assert handler.attempts == 1
release_backoff.set()
await supervisor.stop()
+ await supervisor.stop()
assert handler.attempts == 1
+async def test_hfr_162_backoff_partitions_release_capacity_and_rewind_for_retry() -> None:
+ backoff_entered = asyncio.Event()
+ release_backoff = asyncio.Event()
+ later_started = asyncio.Event()
+ retried_head = asyncio.Event()
+
+ async def controlled_backoff(_delay: float) -> None:
+ backoff_entered.set()
+ await release_backoff.wait()
+
+ class _BackoffHead(RuntimeWorkHandler):
+ def __init__(self) -> None:
+ self.attempts: dict[str, int] = {}
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ rows = [
+ RuntimeWorkItem(
+ f"partition-{index}",
+ {},
+ cursor_key=str(index),
+ )
+ for index in range(5)
+ if f"partition-{index}" not in occupied
+ and (cursor is None or str(index) > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> bool:
+ count = self.attempts.get(item.partition_key, 0) + 1
+ self.attempts[item.partition_key] = count
+ if item.partition_key == "partition-4":
+ later_started.set()
+ return True
+ if count == 1:
+ return False
+ if item.partition_key == "partition-0":
+ retried_head.set()
+ return True
+
+ handler = _BackoffHead()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=4,
+ scan_page_size=4,
+ retry_wait=controlled_backoff,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+
+ await asyncio.wait_for(backoff_entered.wait(), 1)
+ await asyncio.wait_for(later_started.wait(), 1)
+ assert handler.attempts["partition-4"] == 1
+
+ release_backoff.set()
+ await asyncio.wait_for(retried_head.wait(), 1)
+ await supervisor.stop()
+
+
+async def test_hfr_162_partition_backoff_state_is_lane_bounded() -> None:
+ retry_entered = asyncio.Event()
+ release_retry = asyncio.Event()
+ six_partitions_attempted = asyncio.Event()
+ later_partition_started = asyncio.Event()
+ later_partition_retried = asyncio.Event()
+ attempted: list[str] = []
+ attempt_counts: dict[str, int] = {}
+
+ async def controlled_retry(_delay: float) -> None:
+ retry_entered.set()
+ await release_retry.wait()
+
+ class _UnavailablePartitions(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ rows = [
+ RuntimeWorkItem(
+ f"partition-{index:02d}",
+ {},
+ cursor_key=f"{index:02d}",
+ )
+ for index in range(9)
+ if f"partition-{index:02d}" not in occupied
+ and (cursor is None or f"{index:02d}" > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> bool:
+ attempted.append(item.partition_key)
+ if len(attempted) == 6:
+ six_partitions_attempted.set()
+ attempt_counts[item.partition_key] = (
+ attempt_counts.get(item.partition_key, 0) + 1
+ )
+ if item.partition_key == "partition-08":
+ later_partition_started.set()
+ return True
+ if attempt_counts[item.partition_key] == 1:
+ return False
+ if item.partition_key == "partition-06":
+ later_partition_retried.set()
+ return True
+
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ scan_continuation_pages=3,
+ retry_wait=controlled_retry,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, _UnavailablePartitions())
+ await supervisor.activate()
+
+ await asyncio.wait_for(retry_entered.wait(), 1)
+ await asyncio.wait_for(six_partitions_attempted.wait(), 1)
+ assert attempted == [f"partition-{index:02d}" for index in range(6)]
+ registration = supervisor._registrations[RuntimeWorkLane.REQUESTS]
+ assert len(registration.backoff_deadlines) == 6
+ assert registration.backoff_task is not None
+ assert not registration.backoff_task.done()
+ assert not later_partition_started.is_set()
+
+ supervisor.notify(RuntimeWorkLane.REQUESTS, reset_cursor=True)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert not later_partition_started.is_set()
+
+ release_retry.set()
+ await asyncio.wait_for(later_partition_started.wait(), 1)
+ await asyncio.wait_for(later_partition_retried.wait(), 1)
+ assert attempt_counts["partition-06"] == 2
+ await supervisor.stop()
+
+
+async def test_hfr_288_expired_backoff_preserves_forward_scan_before_retry() -> None:
+ retry_entered = asyncio.Event()
+ release_retry = asyncio.Event()
+ first_window_attempted = asyncio.Event()
+ later_partition_started = asyncio.Event()
+ attempts: list[str] = []
+
+ async def controlled_retry(_delay: float) -> None:
+ retry_entered.set()
+ await release_retry.wait()
+
+ class _UnavailablePrefix(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ rows = [
+ RuntimeWorkItem(
+ f"partition-{index:02d}",
+ {},
+ cursor_key=f"{index:02d}",
+ )
+ for index in range(7)
+ if f"partition-{index:02d}" not in occupied
+ and (cursor is None or f"{index:02d}" > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> bool:
+ attempts.append(item.partition_key)
+ if len(attempts) == 6:
+ first_window_attempted.set()
+ if item.partition_key == "partition-06":
+ later_partition_started.set()
+ return True
+ return later_partition_started.is_set()
+
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ scan_continuation_pages=3,
+ retry_wait=controlled_retry,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, _UnavailablePrefix())
+ await supervisor.activate()
+
+ await asyncio.wait_for(retry_entered.wait(), 1)
+ await asyncio.wait_for(first_window_attempted.wait(), 1)
+ assert attempts == [f"partition-{index:02d}" for index in range(6)]
+
+ release_retry.set()
+ await asyncio.wait_for(later_partition_started.wait(), 1)
+ assert attempts[6] == "partition-06"
+ await supervisor.stop()
+
+
+async def test_hfr_162_backoff_budget_preserves_exact_partition_deadline() -> None:
+ now = 0.0
+ release_retry = asyncio.Event()
+ retry_delays: list[float] = []
+ exact_retried = asyncio.Event()
+ later_started = asyncio.Event()
+ attempts: dict[str, int] = {}
+
+ async def controlled_retry(delay: float) -> None:
+ retry_delays.append(delay)
+ await release_retry.wait()
+
+ class _TwoPartitions(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ rows = [
+ RuntimeWorkItem(partition, {}, cursor_key=partition)
+ for partition in ("exact", "later")
+ if partition not in occupied
+ and (cursor is None or partition > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> bool:
+ attempts[item.partition_key] = attempts.get(item.partition_key, 0) + 1
+ if item.partition_key == "exact" and attempts[item.partition_key] == 1:
+ return False
+ if item.partition_key == "exact":
+ exact_retried.set()
+ else:
+ later_started.set()
+ return True
+
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=1,
+ scan_page_size=1,
+ scan_continuation_pages=1,
+ retry_backoff=10,
+ retry_wait=controlled_retry,
+ monotonic=lambda: now,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, _TwoPartitions())
+ await supervisor.activate()
+ try:
+ for _ in range(10):
+ await asyncio.sleep(0)
+ if retry_delays:
+ break
+ assert retry_delays == [10.0]
+ assert attempts == {"exact": 1}
+
+ now = 5.0
+ supervisor.notify(RuntimeWorkLane.REQUESTS, reset_cursor=True)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert attempts == {"exact": 1}
+ assert not later_started.is_set()
+
+ now = 10.0
+ release_retry.set()
+ await asyncio.wait_for(exact_retried.wait(), 1)
+ await asyncio.wait_for(later_started.wait(), 1)
+ assert attempts == {"exact": 2, "later": 1}
+ finally:
+ await supervisor.stop()
+
+
+async def test_hfr_170_live_partition_admission_is_rejected_after_shutdown_starts() -> None:
+ invoked = False
+
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ async def operation() -> None:
+ nonlocal invoked
+ invoked = True
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, _Idle())
+ await supervisor.activate()
+ stopping = asyncio.create_task(supervisor.stop())
+ while not supervisor._stopping:
+ await asyncio.sleep(0)
+
+ with pytest.raises(RuntimeError, match="partition is stopping"):
+ await supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ operation,
+ )
+ await stopping
+ assert invoked is False
+
+
+async def test_hfr_170_quiesce_keeps_executor_for_service_finalization() -> None:
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, _Idle())
+ await supervisor.activate()
+ supervisor.quiesce()
+
+ assert await supervisor.run_sync(lambda: "persisted") == "persisted"
+ with pytest.raises(RuntimeError, match="partition is stopping"):
+ await supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ lambda: asyncio.sleep(0),
+ )
+ await supervisor.stop()
+
+
+async def test_hfr_170_waiter_cannot_reacquire_after_quiesce() -> None:
+ owner_entered = asyncio.Event()
+ release_owner = asyncio.Event()
+ waiter_invoked = False
+
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ async def owner() -> None:
+ owner_entered.set()
+ await release_owner.wait()
+
+ async def waiter_operation() -> None:
+ nonlocal waiter_invoked
+ waiter_invoked = True
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, _Idle())
+ await supervisor.activate()
+ first = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ owner,
+ )
+ )
+ await asyncio.wait_for(owner_entered.wait(), 1)
+ waiter = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ waiter_operation,
+ )
+ )
+ await asyncio.sleep(0)
+ assert not waiter.done()
+
+ supervisor.quiesce()
+ release_owner.set()
+ await first
+ with pytest.raises(RuntimeError, match="partition is stopping"):
+ await waiter
+ assert waiter_invoked is False
+ await supervisor.stop()
+
+
+async def test_hfr_175_lease_loss_quiesces_before_controller_callback() -> None:
+ callbacks: list[str] = []
+ invoked = False
+
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ async def operation() -> None:
+ nonlocal invoked
+ invoked = True
+
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ on_lease_lost=lambda: callbacks.append("lost"),
+ )
+ supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, _Idle())
+ await supervisor.activate()
+ supervisor._stop_for_lost_lease()
+
+ assert callbacks == ["lost"]
+ assert supervisor._quiescing is True
+ with pytest.raises(RuntimeError, match="partition is stopping"):
+ await supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ operation,
+ )
+ assert invoked is False
+ await supervisor.stop()
+
+
+async def test_hfr_175_waiter_rechecks_service_lease_before_reacquiring(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owns_lease = True
+ owner_entered = asyncio.Event()
+ release_owner = asyncio.Event()
+ callbacks: list[str] = []
+ waiter_invoked = False
+
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ async def owner() -> None:
+ owner_entered.set()
+ await release_owner.wait()
+
+ async def waiter_operation() -> None:
+ nonlocal waiter_invoked
+ waiter_invoked = True
+
+ monkeypatch.setattr(
+ "core.runtime_work.runtime.current_process_owns_service_instance",
+ lambda: owns_lease,
+ )
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ on_lease_lost=lambda: callbacks.append("lost"),
+ )
+ supervisor._requires_service_lease = True
+ supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, _Idle())
+ await supervisor.activate()
+ first = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ owner,
+ )
+ )
+ await asyncio.wait_for(owner_entered.wait(), 1)
+ waiter = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ waiter_operation,
+ )
+ )
+ await asyncio.sleep(0)
+ assert not waiter.done()
+
+ owns_lease = False
+ release_owner.set()
+ await first
+ with pytest.raises(RuntimeError, match="partition is stopping"):
+ await waiter
+ assert callbacks == ["lost"]
+ assert supervisor._quiescing is True
+ assert waiter_invoked is False
+ await supervisor.stop()
+
+
+async def test_completed_maintenance_item_does_not_self_rearm() -> None:
+ scans = 0
+ processed = asyncio.Event()
+
+ class _Maintenance(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ nonlocal scans
+ del limit, occupied, cursor
+ scans += 1
+ return [
+ RuntimeWorkItem(
+ "maintenance",
+ {},
+ rearm_after_process=False,
+ )
+ ], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+ processed.set()
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ supervisor.register(RuntimeWorkLane.TASK_DEFINITIONS, _Maintenance())
+ await supervisor.activate()
+ await asyncio.wait_for(processed.wait(), 1)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert scans == 1
+
+ processed.clear()
+ supervisor.notify(RuntimeWorkLane.TASK_DEFINITIONS)
+ await asyncio.wait_for(processed.wait(), 1)
+ assert scans == 2
+ await supervisor.stop()
+
+
@pytest.mark.anyio
async def test_hfr_151_stale_first_page_does_not_starve_later_partition() -> None:
"""HFR-151: the bounded scan cursor advances past stale partitions."""
@@ -355,3 +869,894 @@ async def test_concurrent_stop_callers_join_the_same_blocked_scan() -> None:
handler.release_scan.set()
await asyncio.gather(first, second)
+
+
+ ("event_type", "expected"),
+ [
+ (QUEUE_UPDATED_EVENT, {RuntimeWorkLane.SESSION_DELIVERIES}),
+ (
+ RUNS_UPDATED_EVENT,
+ {
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ RuntimeWorkLane.STALE_RUNS,
+ },
+ ),
+ (VAULTS_UPDATED_EVENT, {RuntimeWorkLane.VAULT_CALLBACKS}),
+ (
+ DEFINITIONS_UPDATED_EVENT,
+ {
+ RuntimeWorkLane.TASK_DEFINITIONS,
+ RuntimeWorkLane.WATCH_DEFINITIONS,
+ },
+ ),
+ ],
+)
+async def test_hfr_155_events_wake_only_their_durable_lanes(
+ event_type: str,
+ expected: set[RuntimeWorkLane],
+) -> None:
+ started: set[RuntimeWorkLane] = set()
+ events = {lane: asyncio.Event() for lane in RuntimeWorkLane}
+
+ class _OneShot(RuntimeWorkHandler):
+ def __init__(self, lane: RuntimeWorkLane) -> None:
+ self.lane = lane
+ self.ready = False
+ self.initial_scan = threading.Event()
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ self.initial_scan.set()
+ if not self.ready:
+ return [], False
+ self.ready = False
+ return [RuntimeWorkItem(self.lane.value, {})], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+ started.add(self.lane)
+ events[self.lane].set()
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ handlers = {lane: _OneShot(lane) for lane in RuntimeWorkLane}
+ for lane, handler in handlers.items():
+ supervisor.register(lane, handler)
+ await supervisor.activate()
+ await asyncio.gather(
+ *(asyncio.to_thread(handler.initial_scan.wait, 1) for handler in handlers.values())
+ )
+ for handler in handlers.values():
+ handler.ready = True
+ bus.publish(event_type, {})
+ await asyncio.gather(
+ *(asyncio.wait_for(events[lane].wait(), 1) for lane in expected)
+ )
+ await asyncio.sleep(0)
+ await supervisor.stop()
+ assert started == expected
+
+
+async def test_hfr_162_failed_scan_rearms_after_bounded_backoff() -> None:
+ attempted = asyncio.Event()
+ release_backoff = asyncio.Event()
+ processed = asyncio.Event()
+
+ class _FailsOnce(RuntimeWorkHandler):
+ scans = 0
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ self.scans += 1
+ attempted.set()
+ if self.scans == 1:
+ raise RuntimeError("transient")
+ return [RuntimeWorkItem("partition-a", {})], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+ processed.set()
+
+ async def backoff(delay: float) -> None:
+ assert delay == 0.25
+ await release_backoff.wait()
+
+ handler = _FailsOnce()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ retry_backoff=0.25,
+ retry_wait=backoff,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+ await asyncio.wait_for(attempted.wait(), 1)
+ assert handler.scans == 1
+ release_backoff.set()
+ await asyncio.wait_for(processed.wait(), 1)
+ await supervisor.stop()
+ assert handler.scans >= 2
+
+
+async def test_hfr_162_wake_during_final_empty_scan_is_not_lost() -> None:
+ processed = asyncio.Event()
+ holder: dict[str, RuntimeWorkSupervisor] = {}
+
+ class _WakeDuringEmpty(RuntimeWorkHandler):
+ scans = 0
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ self.scans += 1
+ if self.scans == 1:
+ holder["supervisor"].notify(RuntimeWorkLane.REQUESTS)
+ return [], False
+ return [RuntimeWorkItem("run-a", {})], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ assert item.partition_key == "run-a"
+ processed.set()
+
+ handler = _WakeDuringEmpty()
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ holder["supervisor"] = supervisor
+ supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+ await asyncio.wait_for(processed.wait(), 1)
+ await supervisor.stop()
+ assert handler.scans >= 2
+
+
+async def test_hfr_159_blocked_store_scan_does_not_block_another_lane() -> None:
+ scan_entered = threading.Event()
+ release_scan = threading.Event()
+ other_processed = asyncio.Event()
+
+ class _BlockedScan(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ scan_entered.set()
+ assert release_scan.wait(timeout=1)
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ class _Ready(RuntimeWorkHandler):
+ ready = True
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ if not self.ready:
+ return [], False
+ self.ready = False
+ return [RuntimeWorkItem("other", {})], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ assert item.partition_key == "other"
+ other_processed.set()
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ supervisor.register(RuntimeWorkLane.TASK_DEFINITIONS, _BlockedScan())
+ supervisor.register(RuntimeWorkLane.STALE_RUNS, _Ready())
+ await supervisor.activate()
+ assert await asyncio.to_thread(scan_entered.wait, 1)
+ await asyncio.wait_for(other_processed.wait(), 1)
+ stopping = asyncio.create_task(supervisor.stop())
+ await asyncio.sleep(0)
+ assert not stopping.done()
+ release_scan.set()
+ await stopping
+
+
+async def test_hfr_163_lane_capacity_bounds_distinct_partition_workers() -> None:
+ release = asyncio.Event()
+ two_started = asyncio.Event()
+ active = 0
+ peak = 0
+ completed = 0
+ done: set[str] = set()
+
+ class _Backlog(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ rows = [
+ RuntimeWorkItem(f"partition-{index}", {}, cursor_key=str(index))
+ for index in range(5)
+ if f"partition-{index}" not in occupied
+ and f"partition-{index}" not in done
+ and (cursor is None or str(index) > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ nonlocal active, peak, completed
+ active += 1
+ peak = max(peak, active)
+ if active == 2:
+ two_started.set()
+ await release.wait()
+ active -= 1
+ done.add(item.partition_key)
+ completed += 1
+
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=5,
+ )
+ supervisor.register(RuntimeWorkLane.RUN_CALLBACKS, _Backlog())
+ await supervisor.activate()
+ await asyncio.wait_for(two_started.wait(), 1)
+ assert peak == 2
+ release.set()
+ for _ in range(100):
+ if completed == 5:
+ break
+ await asyncio.sleep(0)
+ await supervisor.stop()
+ assert completed == 5
+ assert peak == 2
+
+
+async def test_hfr_171_overdue_report_names_lane_partition_and_generation(
+ caplog,
+) -> None:
+ release = asyncio.Event()
+ started = asyncio.Event()
+ tick = asyncio.Event()
+ clock = iter((0.0, 10.0, 45.0))
+
+ async def reconcile_wait(delay: float) -> None:
+ assert delay == 1
+ await tick.wait()
+
+ handler = _Handler(
+ [RuntimeWorkItem("session-a", {})],
+ [],
+ release,
+ started,
+ )
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=1,
+ overdue_seconds=30,
+ reconcile_wait=reconcile_wait,
+ monotonic=lambda: next(clock),
+ )
+ token = supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+ await asyncio.wait_for(started.wait(), 1)
+ tick.set()
+ for _ in range(10):
+ await asyncio.sleep(0)
+ if "Runtime work item overdue" in caplog.text:
+ break
+ unregister = supervisor.begin_unregister(token)
+ release.set()
+ await unregister
+ await supervisor.stop()
+ assert "lane=requests partition=session-a generation=1" in caplog.text
+
+
+async def test_hfr_158_occupied_page_cannot_hide_a_later_partition() -> None:
+ """HFR-158: keyset paging advances through followers of an occupied owner."""
+
+ live_entered = asyncio.Event()
+ release_live = asyncio.Event()
+ later_started = asyncio.Event()
+ scans = 0
+
+ class _OccupiedPage(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ nonlocal scans
+ del occupied
+ scans += 1
+ if not self.ready:
+ return [], False
+ rows = [
+ RuntimeWorkItem(
+ "session-a",
+ index,
+ cursor_key=f"{index:02d}",
+ )
+ for index in range(8)
+ ] + [RuntimeWorkItem("session-b", 8, cursor_key="08")]
+ rows = [row for row in rows if cursor is None or row.cursor_key > cursor]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ if item.partition_key == "session-b":
+ later_started.set()
+
+ async def live_owner() -> None:
+ live_entered.set()
+ await release_live.wait()
+
+ handler = _OccupiedPage()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ scan_continuation_pages=16,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+ live = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.REQUESTS,
+ "session-a",
+ live_owner,
+ )
+ )
+ await asyncio.wait_for(live_entered.wait(), 1)
+ handler.ready = True
+ supervisor.notify(RuntimeWorkLane.REQUESTS)
+ await asyncio.wait_for(later_started.wait(), 1)
+ assert scans >= 9
+ release_live.set()
+ await live
+ await supervisor.stop()
+
+
+async def test_hfr_158_occupied_page_without_cursor_progress_does_not_spin() -> None:
+ live_entered = asyncio.Event()
+ release_live = asyncio.Event()
+ scanned_twice = threading.Event()
+ scans = 0
+
+ class _RepeatedOccupiedPage(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ nonlocal scans
+ del limit, occupied, cursor
+ if not self.ready:
+ return [], False
+ scans += 1
+ if scans >= 2:
+ scanned_twice.set()
+ return [
+ RuntimeWorkItem("session-a", 0, cursor_key="00"),
+ RuntimeWorkItem("session-a", 1, cursor_key="01"),
+ ], True
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ raise AssertionError(item)
+
+ async def live_owner() -> None:
+ live_entered.set()
+ await release_live.wait()
+
+ handler = _RepeatedOccupiedPage()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+ live = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.REQUESTS,
+ "session-a",
+ live_owner,
+ )
+ )
+ await asyncio.wait_for(live_entered.wait(), 1)
+ handler.ready = True
+ supervisor.notify(RuntimeWorkLane.REQUESTS)
+ assert await asyncio.to_thread(scanned_twice.wait, 1)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert scans == 2
+
+ release_live.set()
+ await live
+ await supervisor.stop()
+
+
+async def test_hfr_158_duplicate_pages_continue_only_after_bounded_backoff() -> None:
+ live_entered = asyncio.Event()
+ release_live = asyncio.Event()
+ later_started = asyncio.Event()
+ retry_started: asyncio.Queue[None] = asyncio.Queue()
+ retry_release: asyncio.Queue[None] = asyncio.Queue()
+ scans = 0
+
+ async def controlled_retry(_delay: float) -> None:
+ retry_started.put_nowait(None)
+ await retry_release.get()
+
+ class _LongOccupiedTail(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ nonlocal scans
+ del occupied
+ if not self.ready:
+ return [], False
+ scans += 1
+ rows = [
+ RuntimeWorkItem("session-a", index, cursor_key=f"{index:02d}")
+ for index in range(4)
+ ] + [RuntimeWorkItem("session-b", 4, cursor_key="04")]
+ rows = [row for row in rows if cursor is None or row.cursor_key > cursor]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ if item.partition_key == "session-b":
+ later_started.set()
+
+ async def live_owner() -> None:
+ live_entered.set()
+ await release_live.wait()
+
+ handler = _LongOccupiedTail()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ scan_continuation_pages=2,
+ retry_wait=controlled_retry,
+ )
+ supervisor.register(RuntimeWorkLane.REQUESTS, handler)
+ await supervisor.activate()
+ live = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.REQUESTS,
+ "session-a",
+ live_owner,
+ )
+ )
+ await asyncio.wait_for(live_entered.wait(), 1)
+ handler.ready = True
+ supervisor.notify(RuntimeWorkLane.REQUESTS)
+
+ await asyncio.wait_for(retry_started.get(), 1)
+ assert scans == 2
+ assert not later_started.is_set()
+ retry_release.put_nowait(None)
+ await asyncio.wait_for(retry_started.get(), 1)
+ assert scans == 4
+ assert not later_started.is_set()
+ retry_release.put_nowait(None)
+ await asyncio.wait_for(later_started.wait(), 1)
+
+ release_live.set()
+ await live
+ await supervisor.stop()
+
+
+async def test_hfr_158_skipped_partition_rewinds_when_its_owner_releases() -> None:
+ first_started = asyncio.Event()
+ release_first = asyncio.Event()
+ second_started = asyncio.Event()
+ completed: set[int] = set()
+ scans = 0
+
+ class _SamePartitionCallbacks(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ nonlocal scans
+ del occupied
+ if not self.ready:
+ return [], False
+ scans += 1
+ rows = [
+ RuntimeWorkItem(
+ "session-a",
+ index,
+ cursor_key=f"{index:02d}",
+ rearm_after_process=False,
+ )
+ for index in (1, 2)
+ if index not in completed
+ and (cursor is None or f"{index:02d}" > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ index = int(item.observation)
+ if index == 1:
+ first_started.set()
+ await release_first.wait()
+ else:
+ second_started.set()
+ completed.add(index)
+
+ handler = _SamePartitionCallbacks()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ )
+ supervisor.register(RuntimeWorkLane.RUN_CALLBACKS, handler)
+ await supervisor.activate()
+ handler.ready = True
+ supervisor.notify(RuntimeWorkLane.RUN_CALLBACKS)
+
+ await asyncio.wait_for(first_started.wait(), 1)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert scans == 1
+ assert not second_started.is_set()
+
+ release_first.set()
+ await asyncio.wait_for(second_started.wait(), 1)
+ assert completed == {1, 2}
+ await supervisor.stop()
+
+
+async def test_hfr_158_live_owner_release_rewinds_skipped_partition_rows() -> None:
+ live_entered = asyncio.Event()
+ release_live = asyncio.Event()
+ recovered: list[int] = []
+ both_recovered = asyncio.Event()
+ active_recoveries = 0
+ peak_recoveries = 0
+
+ class _HiddenRecoveryRows(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del occupied
+ if not self.ready:
+ return [], False
+ rows = [
+ RuntimeWorkItem(
+ "session-a",
+ index,
+ cursor_key=f"{index:02d}",
+ rearm_after_process=False,
+ )
+ for index in (1, 2)
+ if index not in recovered
+ and (cursor is None or f"{index:02d}" > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ nonlocal active_recoveries, peak_recoveries
+ active_recoveries += 1
+ peak_recoveries = max(peak_recoveries, active_recoveries)
+ await asyncio.sleep(0)
+ recovered.append(int(item.observation))
+ active_recoveries -= 1
+ if len(recovered) == 2:
+ both_recovered.set()
+
+ async def live_owner() -> None:
+ live_entered.set()
+ await release_live.wait()
+
+ handler = _HiddenRecoveryRows()
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ )
+ supervisor.register(RuntimeWorkLane.RUN_CALLBACKS, handler)
+ await supervisor.activate()
+ live = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.RUN_CALLBACKS,
+ "session-a",
+ live_owner,
+ )
+ )
+ await asyncio.wait_for(live_entered.wait(), 1)
+ handler.ready = True
+ supervisor.notify(RuntimeWorkLane.RUN_CALLBACKS)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert recovered == []
+
+ release_live.set()
+ await live
+ await asyncio.wait_for(both_recovered.wait(), 1)
+ assert sorted(recovered) == [1, 2]
+ assert peak_recoveries == 1
+ await supervisor.stop()
+
+
+async def test_hfr_162_backoff_owns_rewind_for_a_skipped_partition() -> None:
+ first_attempt = asyncio.Event()
+ retry_waiting = asyncio.Event()
+ release_retry = asyncio.Event()
+ second_recovered = asyncio.Event()
+ attempts: dict[int, int] = {}
+ completed: set[int] = set()
+
+ async def controlled_retry(_delay: float) -> None:
+ retry_waiting.set()
+ await release_retry.wait()
+
+ class _RetryingPartition(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del occupied
+ rows = [
+ RuntimeWorkItem("session-a", index, cursor_key=f"{index:02d}")
+ for index in (1, 2)
+ if index not in completed
+ and (cursor is None or f"{index:02d}" > cursor)
+ ]
+ return rows[:limit], len(rows) > limit
+
+ async def process(self, item: RuntimeWorkItem) -> bool:
+ index = int(item.observation)
+ attempts[index] = attempts.get(index, 0) + 1
+ if index == 1 and attempts[index] == 1:
+ first_attempt.set()
+ return False
+ completed.add(index)
+ if index == 2:
+ second_recovered.set()
+ return True
+
+ supervisor = RuntimeWorkSupervisor(
+ reconcile_interval=3600,
+ lane_capacity=2,
+ scan_page_size=2,
+ retry_wait=controlled_retry,
+ )
+ supervisor.register(RuntimeWorkLane.RUN_CALLBACKS, _RetryingPartition())
+ await supervisor.activate()
+ await asyncio.wait_for(first_attempt.wait(), 1)
+ await asyncio.wait_for(retry_waiting.wait(), 1)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert not second_recovered.is_set()
+
+ release_retry.set()
+ await asyncio.wait_for(second_recovered.wait(), 1)
+ assert attempts == {1: 2, 2: 1}
+ await supervisor.stop()
+
+
+async def test_hfr_160_live_partition_owner_blocks_recovery_and_unregisters_by_join() -> None:
+ """HFR-160/HFR-166: one exact owner survives wake and registration teardown."""
+
+ live_entered = asyncio.Event()
+ release_live = asyncio.Event()
+ scan_observed = threading.Event()
+ recovered_started = asyncio.Event()
+
+ class _Recovery(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied
+ if not self.ready:
+ return [], False
+ if cursor is not None:
+ return [], False
+ scan_observed.set()
+ return [RuntimeWorkItem("claude\x1fruntime-a", {})], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+ recovered_started.set()
+
+ async def live_owner() -> str:
+ live_entered.set()
+ await release_live.wait()
+ return "settled"
+
+ handler = _Recovery()
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ token = supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, handler)
+ await supervisor.activate()
+ live = asyncio.create_task(
+ supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ live_owner,
+ )
+ )
+ await asyncio.wait_for(live_entered.wait(), 1)
+ handler.ready = True
+ supervisor.notify(RuntimeWorkLane.ACTIVITY_OUTPUTS)
+ assert await asyncio.to_thread(scan_observed.wait, 1)
+ assert not recovered_started.is_set()
+
+ unregister = supervisor.begin_unregister(token)
+ await asyncio.sleep(0)
+ assert not unregister.done()
+ release_live.set()
+ assert await live == "settled"
+ await unregister
+ assert not recovered_started.is_set()
+ await supervisor.stop()
+
+
+async def test_hfr_160_canceled_sync_worker_remains_owner_until_thread_exits() -> None:
+ """HFR-160: cancellation cannot abandon a still-running store thread."""
+
+ started = threading.Event()
+ release = threading.Event()
+
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+
+ def blocking_store_call() -> str:
+ started.set()
+ release.wait()
+ return "done"
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ token = supervisor.register(RuntimeWorkLane.REQUESTS, _Idle())
+ await supervisor.activate()
+
+ async def operation() -> str:
+ return await supervisor.run_sync(blocking_store_call)
+
+ owner = asyncio.create_task(
+ supervisor.run_in_partition(RuntimeWorkLane.REQUESTS, "run-a", operation)
+ )
+ assert await asyncio.to_thread(started.wait, 1)
+ owner.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await owner
+ unregister = supervisor.begin_unregister(token)
+ await asyncio.sleep(0)
+ assert not unregister.done()
+
+ release.set()
+ await unregister
+ await supervisor.stop()
+
+
+async def test_hfr_164_unregister_joins_partition_not_outer_caller_task() -> None:
+ """HFR-164: lane teardown joins only the exact protected operation."""
+
+ operation_started = asyncio.Event()
+ release_operation = asyncio.Event()
+ caller_continued = asyncio.Event()
+ release_caller = asyncio.Event()
+
+ class _Idle(RuntimeWorkHandler):
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+
+ async def operation() -> None:
+ operation_started.set()
+ await release_operation.wait()
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ token = supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, _Idle())
+ await supervisor.activate()
+
+ async def caller() -> None:
+ await supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "runtime-a",
+ operation,
+ )
+ caller_continued.set()
+ await release_caller.wait()
+
+ caller_task = asyncio.create_task(caller())
+ await asyncio.wait_for(operation_started.wait(), 1)
+ unregister = supervisor.begin_unregister(token)
+ release_operation.set()
+ await asyncio.wait_for(caller_continued.wait(), 1)
+ await asyncio.wait_for(unregister, 1)
+ assert not caller_task.done()
+
+ release_caller.set()
+ await caller_task
+ await supervisor.stop()
+
+
+async def test_hfr_165_old_generation_delayed_wake_cannot_rearm_replacement() -> None:
+ """HFR-165: delayed eligibility belongs to one registration generation."""
+
+ class _Idle(RuntimeWorkHandler):
+ def __init__(self) -> None:
+ self.scanned = threading.Event()
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ self.scanned.set()
+ return [], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ del item
+
+ first = _Idle()
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ first_token = supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, first)
+ await supervisor.activate()
+ assert await asyncio.to_thread(first.scanned.wait, 1)
+ supervisor.notify_after(first_token, 60)
+ assert first_token in supervisor._delayed_wakes
+ await supervisor.unregister(first_token)
+ assert first_token not in supervisor._delayed_wakes
+
+ second = _Idle()
+ second_token = supervisor.register(RuntimeWorkLane.ACTIVITY_OUTPUTS, second)
+ assert await asyncio.to_thread(second.scanned.wait, 1)
+ registration = supervisor._registrations[RuntimeWorkLane.ACTIVITY_OUTPUTS]
+ registration.event.clear()
+ supervisor._fire_delayed_wake(first_token)
+ assert registration.token == second_token
+ assert not registration.event.is_set()
+ await supervisor.stop()
+
+
+async def test_hfr_175_global_lease_loss_joins_every_registration(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ owns_lease = True
+ scanned = threading.Event()
+ processed: list[str] = []
+
+ class _LeaseHandler(RuntimeWorkHandler):
+ ready = False
+
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ scanned.set()
+ if not self.ready:
+ return [], False
+ return [RuntimeWorkItem("work", {})], False
+
+ async def process(self, item: RuntimeWorkItem) -> None:
+ processed.append(item.partition_key)
+
+ monkeypatch.setattr(
+ "core.runtime_work.runtime.current_process_owns_service_instance",
+ lambda: owns_lease,
+ )
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ supervisor._requires_service_lease = True
+ handlers = {
+ RuntimeWorkLane.SESSION_DELIVERIES: _LeaseHandler(),
+ RuntimeWorkLane.REQUESTS: _LeaseHandler(),
+ }
+ for lane, handler in handlers.items():
+ supervisor.register(lane, handler)
+ await supervisor.activate()
+ assert await asyncio.to_thread(scanned.wait, 1)
+
+ owns_lease = False
+ for handler in handlers.values():
+ handler.ready = True
+ supervisor.notify(*handlers)
+ for _ in range(100):
+ if supervisor._stop_task is not None:
+ break
+ await asyncio.sleep(0)
+ assert supervisor._stop_task is not None
+ await supervisor._stop_task
+ assert supervisor._registrations == {}
+ assert processed == []
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 3034d4b09..b3973b758 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -7,7 +7,9 @@ import os
import sqlite3
import subprocess
import sys
+import threading
import time
+from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
from contextlib import suppress
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -54,6 +56,7 @@ from core.runtime_activation import RuntimeActivationRegistry
from core.runtime_work import (
RuntimeWorkLane,
RuntimeWorkRegistrationToken,
+ RuntimeWorkSupervisor,
)
from core.services.dispatch import SOURCE_SCHEDULED, TurnDispatchOutcome
from core.session_activities import SessionActivityRegistry
@@ -85,6 +88,7 @@ from storage.db import create_sqlite_engine
from storage.background import (
COMMAND_SNAPSHOT_METADATA_KEY,
COMMAND_TIMED_OUT_METADATA_KEY,
+ DefinitionWriteConflict,
SQLiteBackgroundTaskStore,
definition_lifecycle_detail,
)
@@ -92,8 +96,10 @@ from storage.models import (
agent_events,
agent_runs,
agent_sessions,
+ metadata,
messages,
run_definitions,
+ vault_requests,
)
from storage.pagination import PageRequest
from storage.session_activities import SQLiteSessionActivityStore
@@ -126,6 +132,25 @@ class _StubScheduler:
return list(self.jobs.values())
+async def _fire_and_finish_scheduled_task(
+ service: ScheduledTaskService,
+ task_id: str,
+) -> None:
+ """Fire through the scheduler producer, then let the request owner consume it."""
+
+ await service._run_task(task_id)
+ pending = [
+ request
+ for request in service.request_store.list_pending()
+ if request.task_id == task_id and request.source_kind == "scheduler"
+ ]
+ for request in pending:
+ await service._process_pending_request(request)
+ executions = tuple(service._inflight_executions.values())
+ if executions:
+ await asyncio.gather(*executions)
+
+
def test_parse_session_key_accepts_channel_and_thread() -> None:
parsed = parse_session_key("slack::channel::C123::thread::171717.123")
@@ -431,6 +456,93 @@ def test_scheduled_task_store_uses_sqlite_when_path_is_default(tmp_path: Path, m
assert sqlite.get_scheduled_task(task.id)["prompt"] == "hello"
+def test_hfr_172_task_definition_wake_follows_commit_and_not_rollback(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from core import inbox_events
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ events: list[tuple[str, dict[str, Any]]] = []
+ subscription = inbox_events.bus.subscribe_callback(
+ lambda event_type, payload: events.append((event_type, payload))
+ )
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", True)
+ original_save = store._save
+ entered = threading.Event()
+ release = threading.Event()
+ failure: list[BaseException] = []
+
+ def blocking_save() -> None:
+ entered.set()
+ assert release.wait(timeout=1)
+ original_save()
+
+ def add_task() -> None:
+ try:
+ store.add_task(
+ name="Wake contract",
+ session_key="avibe::agent::default",
+ prompt="hello",
+ schedule_type="at",
+ run_at="2026-08-04T01:00:00+00:00",
+ timezone_name="UTC",
+ )
+ except BaseException as exc: # pragma: no cover - asserted below
+ failure.append(exc)
+
+ monkeypatch.setattr(store, "_save", blocking_save)
+ writer = threading.Thread(target=add_task)
+ writer.start()
+ assert entered.wait(timeout=1)
+ assert events == []
+ release.set()
+ writer.join(timeout=1)
+ assert not writer.is_alive()
+ assert failure == []
+ assert events == [
+ (inbox_events.DEFINITIONS_UPDATED_EVENT, {"definition_type": "scheduled"})
+ ]
+
+ events.clear()
+ task = store.list_tasks()[0]
+ monkeypatch.setattr(store, "_save", lambda: (_ for _ in ()).throw(OSError("disk full")))
+ with pytest.raises(OSError, match="disk full"):
+ store.set_enabled(task.id, False)
+ assert events == []
+ inbox_events.bus.unsubscribe(subscription)
+
+
+def test_hfr_172_losing_task_definition_cas_emits_no_wake(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from core import inbox_events
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", True)
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ name="CAS wake contract",
+ session_key="avibe::agent::default",
+ prompt="hello",
+ schedule_type="at",
+ run_at="2026-08-04T01:00:00+00:00",
+ timezone_name="UTC",
+ )
+ events: list[tuple[str, dict[str, Any]]] = []
+ subscription = inbox_events.bus.subscribe_callback(
+ lambda event_type, payload: events.append((event_type, payload))
+ )
+ assert store.sqlite_backend is not None
+ monkeypatch.setattr(store.sqlite_backend, "upsert_scheduled_task", lambda *args, **kwargs: False)
+
+ with pytest.raises(DefinitionWriteConflict):
+ store.set_enabled(task.id, False)
+ assert events == []
+ inbox_events.bus.unsubscribe(subscription)
+
+
def test_sqlite_update_task_persists_changes(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = ScheduledTaskStore()
@@ -1351,7 +1463,7 @@ def test_run_task_records_scheduled_handler_error(tmp_path: Path) -> None:
)
service = ScheduledTaskService(controller=controller, store=store)
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
reloaded = ScheduledTaskStore(path)
updated = reloaded.get_task(task.id)
@@ -1389,6 +1501,425 @@ def test_run_task_stays_queued_until_target_transport_is_ready(tmp_path: Path) -
assert updated.enabled is True
+def test_hfr_161_scheduler_only_enqueues_one_successor_behind_active_work(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+ request_store = TaskExecutionStore()
+ notifications: list[tuple[RuntimeWorkLane, ...]] = []
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": object()},
+ runtime_work_supervisor=SimpleNamespace(
+ notify=lambda *lanes: notifications.append(lanes)
+ ),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=store,
+ request_store=request_store,
+ )
+
+ async def _exercise() -> None:
+ await service._run_task(task.id)
+ first = request_store.list_pending()
+ assert len(first) == 1
+ claimed = request_store.claim(first[0].id)
+ assert claimed is not None
+
+ await service._run_task(task.id)
+ assert request_store.list_pending() == []
+
+ assert request_store.mark_execution_started(claimed.id)
+
+ await asyncio.gather(
+ service._run_task(task.id),
+ service._run_task(task.id),
+ service._run_task(task.id),
+ )
+
+ asyncio.run(_exercise())
+
+ queued = request_store.list_pending()
+ assert len(queued) == 1
+ assert queued[0].task_id == task.id
+ assert len(notifications) == 2
+ assert all(lanes == (RuntimeWorkLane.REQUESTS,) for lanes in notifications)
+
+
+def test_hfr_161_file_scheduler_fence_includes_claimed_pre_execution_run(
+ tmp_path: Path,
+) -> None:
+ task_store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = task_store.add_task(
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+
+ first = request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ )
+ assert first is not None
+ assert request_store.claim(first.id) is not None
+
+ assert request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ ) is None
+
+ assert request_store.mark_execution_started(first.id)
+ successor = request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ )
+ assert successor is not None
+ assert request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ ) is None
+
+
+def test_hfr_158_request_scan_fills_page_across_recovery_and_queued_work(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ recovering = request_store.enqueue_hook_send(
+ session_key="slack::channel::recovering",
+ prompt="recover",
+ )
+ assert request_store.claim(recovering.id) is not None
+ queued = request_store.enqueue_hook_send(
+ session_key="slack::channel::recovering",
+ prompt="queued",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ request_store=request_store,
+ )
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.REQUESTS,
+ )
+
+ items, _has_more = handler.scan(
+ limit=2,
+ occupied=frozenset(),
+ cursor=None,
+ )
+
+ assert [item.observation[0] for item in items] == ["fallback", "queued"]
+ assert items[0].partition_key == "key:slack::channel::recovering"
+ assert items[1].partition_key == items[0].partition_key
+ assert items[1].observation[1].id == queued.id
+
+
+def test_hfr_166_activity_scan_never_sleeps_ahead_of_due_runtime() -> None:
+ scheduled: list[tuple[RuntimeWorkLane, float]] = []
+
+ class _Registry:
+ @staticmethod
+ def scan_recovered_output_runtimes(
+ *,
+ limit,
+ cursor,
+ grace_seconds,
+ ): # noqa: ANN001, ANN202
+ del limit, cursor
+ assert grace_seconds("claude") == 10.0
+ return [("claude", "b-due")], False, 30.0, "claude\x1fb-due"
+
+ service = SimpleNamespace(
+ _activity_registry=lambda: _Registry(),
+ _activity_output_grace_seconds=lambda _backend: 10.0,
+ _schedule_runtime_work_wake=(
+ lambda lane, delay: scheduled.append((lane, delay))
+ ),
+ )
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ )
+
+ items, has_more = handler.scan(
+ limit=1,
+ occupied=frozenset(),
+ cursor=None,
+ )
+
+ assert [item.partition_key for item in items] == ["claude\x1fb-due"]
+ assert has_more is False
+ assert scheduled == [(RuntimeWorkLane.ACTIVITY_OUTPUTS, 30.0)]
+
+
+async def test_hfr_166_recovered_runtime_rewinds_until_every_batch_is_drained() -> None:
+ activities = [SimpleNamespace(id="activity-a"), SimpleNamespace(id="activity-b")]
+
+ class _Registry:
+ def claim_completed_output(self, *_args, **_kwargs): # noqa: ANN002, ANN003, ANN202
+ return activities.pop(0) if activities else None
+
+ @staticmethod
+ def has_completed_output(*_args): # noqa: ANN002, ANN205
+ return bool(activities)
+
+ @staticmethod
+ def has_recovered_output(*_args): # noqa: ANN002, ANN205
+ return bool(activities)
+
+ registry = _Registry()
+ wake = Mock()
+ service = SimpleNamespace(
+ _activity_registry=lambda: registry,
+ _deliver_recovered_activity_output=AsyncMock(),
+ _settle_pending_recovered_activity_terminals=Mock(),
+ _wake_runtime_work=wake,
+ )
+
+ assert await ScheduledTaskService._process_recovered_activity_output(
+ service,
+ "claude",
+ "runtime-a",
+ )
+ wake.assert_called_once_with(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ reset_cursor=True,
+ )
+ assert [activity.id for activity in activities] == ["activity-b"]
+
+ assert await ScheduledTaskService._process_recovered_activity_output(
+ service,
+ "claude",
+ "runtime-a",
+ )
+ assert activities == []
+ assert wake.call_count == 1
+
+
+def test_hfr_168_stale_lane_arms_its_configured_remaining_interval() -> None:
+ scheduled: list[tuple[RuntimeWorkLane, float]] = []
+ service = SimpleNamespace(
+ _stale_run_sweep_delay_seconds=lambda: 5.0,
+ _schedule_runtime_work_wake=(
+ lambda lane, delay: scheduled.append((lane, delay))
+ ),
+ )
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.STALE_RUNS,
+ )
+
+ items, has_more = handler.scan(limit=1, occupied=frozenset(), cursor=None)
+ assert [item.partition_key for item in items] == ["run-cancellations"]
+ assert has_more is False
+ assert scheduled == [(RuntimeWorkLane.STALE_RUNS, 5.0)]
+
+
+def test_task_reload_and_scheduler_snapshot_share_one_mirror_lock(
+ tmp_path: Path,
+) -> None:
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ enabled = ScheduledTask(
+ id="task-a",
+ name=None,
+ session_key="slack::channel::C123",
+ prompt="run",
+ schedule_type="cron",
+ cron="* * * * *",
+ )
+ disabled = ScheduledTask.from_dict({**enabled.to_dict(), "enabled": False})
+ store._tasks = {enabled.id: enabled}
+ load_started = threading.Event()
+ release_load = threading.Event()
+
+ class _SQLite:
+ probes = 0
+
+ def maybe_reload(self) -> bool:
+ self.probes += 1
+ return self.probes == 1
+
+ @staticmethod
+ def list_scheduled_tasks():
+ load_started.set()
+ assert release_load.wait(timeout=1)
+ return [disabled.to_dict()]
+
+ store._sqlite = _SQLite() # type: ignore[assignment]
+ refresh_entered = threading.Event()
+
+ def refresh() -> ScheduledTask | None:
+ refresh_entered.set()
+ return store.refresh_task(enabled.id)
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ reload_future = executor.submit(store.maybe_reload)
+ assert load_started.wait(timeout=1)
+ refresh_future = executor.submit(refresh)
+ assert refresh_entered.wait(timeout=1)
+ try:
+ with pytest.raises(FutureTimeoutError):
+ refresh_future.result(timeout=0.05)
+ finally:
+ release_load.set()
+
+ assert reload_future.result(timeout=1) is True
+ refreshed = refresh_future.result(timeout=1)
+
+ assert refreshed is not None
+ assert refreshed.enabled is False
+
+
+def test_hfr_282_task_reload_waits_for_result_stamp_mirror_commit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="run once",
+ schedule_type="at",
+ run_at="2030-01-01T00:00:00+00:00",
+ timezone_name="UTC",
+ )
+ write_entered = threading.Event()
+ release_write = threading.Event()
+ load_entered = threading.Event()
+ original_save = store._save
+ original_load = store._load_unlocked
+
+ def blocked_save() -> None:
+ write_entered.set()
+ assert release_write.wait(timeout=1)
+ original_save()
+
+ def observed_load() -> None:
+ load_entered.set()
+ original_load()
+
+ monkeypatch.setattr(store, "_save", blocked_save)
+ monkeypatch.setattr(store, "_load_unlocked", observed_load)
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ stamp_future = executor.submit(store.mark_task_result, task.id, error=None)
+ assert write_entered.wait(timeout=1)
+ reload_future = executor.submit(store.load)
+ try:
+ with pytest.raises(FutureTimeoutError):
+ reload_future.result(timeout=0.05)
+ assert not load_entered.is_set()
+ finally:
+ release_write.set()
+
+ assert stamp_future.result(timeout=1) is True
+ reload_future.result(timeout=1)
+
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ assert reloaded.enabled is False
+
+
+def test_hfr_165_vault_scan_arms_exact_pending_expiry(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine = create_sqlite_engine()
+ metadata.create_all(engine)
+ expires_at = datetime.now(timezone.utc) + timedelta(seconds=20)
+ with engine.begin() as conn:
+ conn.execute(
+ vault_requests.insert().values(
+ id="vrq_future",
+ request_type="sign",
+ status="pending",
+ created_at=datetime.now(timezone.utc).isoformat(),
+ expires_at=expires_at.isoformat(),
+ )
+ )
+
+ scheduled: list[tuple[RuntimeWorkLane, float]] = []
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ )
+ service._schedule_runtime_work_wake = ( # type: ignore[method-assign]
+ lambda lane, delay: scheduled.append((lane, delay))
+ )
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.VAULT_CALLBACKS,
+ )
+
+ items, has_more = handler.scan(
+ limit=1,
+ occupied=frozenset(),
+ cursor=None,
+ )
+
+ assert items == []
+ assert has_more is False
+ assert len(scheduled) == 1
+ lane, delay = scheduled[0]
+ assert lane is RuntimeWorkLane.VAULT_CALLBACKS
+ assert 0 < delay <= 20
+
+
+async def test_hfr_166_activity_lane_lives_for_the_controller_generation(
+ tmp_path: Path,
+) -> None:
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ controller = SimpleNamespace(
+ runtime_work_supervisor=supervisor,
+ platform_settings_managers={},
+ agent_service=SimpleNamespace(activities=None, agents={}),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ )
+
+ [token] = service.register_controller_runtime_work_lanes()
+ assert token.lane is RuntimeWorkLane.ACTIVITY_OUTPUTS
+ await supervisor.activate()
+ assert await supervisor.run_in_partition(
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ "claude\x1fruntime-a",
+ lambda: asyncio.sleep(0, result="delivered"),
+ ) == "delivered"
+
+ assert service._begin_runtime_work_unregistration() is None
+ registration = supervisor._registrations[RuntimeWorkLane.ACTIVITY_OUTPUTS]
+ assert registration.live is True
+ await supervisor.stop()
+
+
def test_reconcile_jobs_skips_invalid_tasks_and_keeps_valid_jobs(tmp_path: Path) -> None:
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
valid = store.add_task(
@@ -3540,7 +4071,10 @@ def test_run_task_uses_tracked_execution_for_lease_loss(tmp_path: Path, monkeypa
service._execute_claimed_request = fake_execute # type: ignore[assignment]
async def _exercise() -> None:
- run_task = asyncio.create_task(service._run_task(task.id))
+ await service._run_task(task.id)
+ pending = service.request_store.list_pending()
+ assert len(pending) == 1
+ assert await service._process_pending_request(pending[0]) is True
await started.wait()
assert len(service._inflight_executions) == 1
execution = next(iter(service._inflight_executions.values()))
@@ -3548,14 +4082,147 @@ def test_run_task_uses_tracked_execution_for_lease_loss(tmp_path: Path, monkeypa
assert service._owns_service_instance() is False
with pytest.raises(asyncio.CancelledError):
await execution
- with pytest.raises(asyncio.CancelledError):
- await run_task
asyncio.run(_exercise())
assert service._running is False
+def test_request_partitions_use_the_canonical_session_identity(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ from storage.sessions_service import SQLiteSessionsService
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ target = parse_session_key("slack::channel::C123")
+ sessions = SQLiteSessionsService(paths.get_sqlite_state_path())
+ try:
+ session_id = sessions.reserve_agent_session(
+ scope_key=target.session_scope,
+ agent_backend="codex",
+ session_anchor=session_anchor_for_target(target),
+ )
+ finally:
+ sessions.close()
+ assert session_id is not None
+
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=ScheduledTaskStore(tmp_path / "tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "requests"),
+ )
+ by_id = TaskExecutionRequest(
+ id="by-session-id",
+ request_type="hook_send",
+ session_id=session_id,
+ )
+ by_key = TaskExecutionRequest(
+ id="by-session-key",
+ request_type="hook_send",
+ session_key=target.to_key(),
+ )
+
+ assert service._request_partition_key(by_id) == service._request_partition_key(
+ by_key
+ )
+
+
+def test_request_capacity_is_reserved_before_claim(tmp_path: Path) -> None:
+ request_store = TaskExecutionStore(tmp_path / "requests")
+ first = request_store.enqueue_hook_send(
+ session_key="slack::channel::A",
+ prompt="first",
+ )
+ second = request_store.enqueue_hook_send(
+ session_key="slack::channel::B",
+ prompt="second",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=ScheduledTaskStore(tmp_path / "tasks.json"),
+ request_store=request_store,
+ )
+ service._running = True
+ for index in range(service._MAX_CONCURRENT_EXECUTIONS - 1):
+ service._inflight_executions[f"busy-{index}"] = Mock()
+ claim_started = asyncio.Event()
+ release_claim = asyncio.Event()
+ claims: list[str] = []
+ spawned: list[str] = []
+
+ async def _run_sync(operation, /, *args, **kwargs): # noqa: ANN001, ANN202
+ if operation == service._claim_pending_request:
+ claims.append(args[0].id)
+ claim_started.set()
+ await release_claim.wait()
+ return operation(*args, **kwargs)
+
+ service._run_runtime_sync = _run_sync # type: ignore[method-assign]
+ service._spawn_execution = ( # type: ignore[method-assign]
+ lambda request, _lock_key: spawned.append(request.id)
+ )
+
+ async def _exercise() -> None:
+ first_task = asyncio.create_task(service._process_pending_request(first))
+ await claim_started.wait()
+ assert await service._process_pending_request(second) is False
+ release_claim.set()
+ assert await first_task is True
+
+ asyncio.run(_exercise())
+
+ assert claims == [first.id]
+ assert spawned == [first.id]
+ assert service._request_capacity_reservations == set()
+
+
+def test_claimed_request_is_requeued_when_its_lane_generation_stops(
+ tmp_path: Path,
+) -> None:
+ request_store = TaskExecutionStore(tmp_path / "requests")
+ pending = request_store.enqueue_hook_send(
+ session_key="slack::channel::A",
+ prompt="run after restart",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=ScheduledTaskStore(tmp_path / "tasks.json"),
+ request_store=request_store,
+ )
+ service._running = True
+ token = RuntimeWorkRegistrationToken(RuntimeWorkLane.REQUESTS, 1)
+ service._runtime_work_tokens[RuntimeWorkLane.REQUESTS] = token
+ claim_started = asyncio.Event()
+ release_claim = asyncio.Event()
+ spawned: list[str] = []
+
+ async def _run_sync(operation, /, *args, **kwargs): # noqa: ANN001, ANN202
+ if operation == service._claim_pending_request:
+ claim_started.set()
+ await release_claim.wait()
+ return operation(*args, **kwargs)
+
+ service._run_runtime_sync = _run_sync # type: ignore[method-assign]
+ service._spawn_execution = ( # type: ignore[method-assign]
+ lambda request, _lock_key: spawned.append(request.id)
+ )
+
+ async def _exercise() -> None:
+ processing = asyncio.create_task(service._process_pending_request(pending))
+ await claim_started.wait()
+ service._running = False
+ service._runtime_work_tokens.pop(RuntimeWorkLane.REQUESTS)
+ release_claim.set()
+ assert await processing is True
+
+ asyncio.run(_exercise())
+
+ assert spawned == []
+ assert request_store.get_run(pending.id)["status"] == "queued"
+ assert service._request_capacity_reservations == set()
+
+
def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:
request_store = TaskExecutionStore(tmp_path / "task_requests")
request = request_store.enqueue_hook_send(
@@ -7590,6 +8257,57 @@ def test_recovered_silent_directive_activity_settles_without_emit() -> None:
service.controller.emit_agent_message.assert_not_awaited()
+def test_hfr_169_recovered_activity_without_run_reaches_its_session(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ sqlite_store = request_store.sqlite_backend
+ assert sqlite_store is not None
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ original = SessionActivityRegistry(activity_store)
+ original.start(
+ backend="claude",
+ runtime_key="runtime-without-run",
+ session_id=session_id,
+ activity_id="task-without-run",
+ kind="background_task",
+ )
+ original.complete(
+ backend="claude",
+ runtime_key="runtime-without-run",
+ activity_id="task-without-run",
+ status="completed",
+ metadata={"summary": "Recovered without a Run row"},
+ expects_output=True,
+ )
+
+ recovered = SessionActivityRegistry(activity_store)
+ controller = _avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ )
+ controller.agent_service = SimpleNamespace(activities=recovered)
+ delivered: list[tuple[str, str]] = []
+
+ async def emit(context, _kind, text, **_kwargs): # noqa: ANN001, ANN202
+ delivered.append((context.platform_specific["agent_session_id"], text))
+ return "message-without-run"
+
+ controller.emit_agent_message = emit
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ assert delivered == [(session_id, "Recovered without a Run row")]
+ assert activity_store.list_activities() == []
+
+
def test_restart_background_activity_persists_without_outward_delivery(
tmp_path: Path,
monkeypatch,
@@ -8839,6 +9557,239 @@ def test_watch_store_does_not_respawn_after_stop(tmp_path: Path) -> None:
asyncio.run(_exercise())
+def test_hfr_164_hfr_165_service_restart_joins_only_its_harness_lane_generations(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ class _Supervisor:
+ def __init__(self) -> None:
+ self.generations: dict[RuntimeWorkLane, int] = {}
+ self.current: dict[RuntimeWorkLane, RuntimeWorkRegistrationToken] = {}
+ self.unregistered: list[RuntimeWorkLane] = []
+
+ def register(self, lane, _handler): # noqa: ANN001, ANN202
+ assert lane not in self.current
+ generation = self.generations.get(lane, 0) + 1
+ self.generations[lane] = generation
+ token = RuntimeWorkRegistrationToken(lane=lane, generation=generation)
+ self.current[lane] = token
+ return token
+
+ def begin_unregister(self, token): # noqa: ANN001, ANN202
+ assert self.current.get(token.lane) == token
+ self.current.pop(token.lane)
+ self.unregistered.append(token.lane)
+
+ async def _joined() -> None:
+ return None
+
+ return asyncio.create_task(_joined())
+
+ def notify(self, *_lanes) -> None: # noqa: ANN002
+ return None
+
+ async def _exercise() -> None:
+ supervisor = _Supervisor()
+ supervisor.register(RuntimeWorkLane.SESSION_DELIVERIES, object())
+ controller = SimpleNamespace(
+ platform_settings_managers={},
+ runtime_work_supervisor=supervisor,
+ )
+ service = ScheduledTaskService(controller=controller)
+ service.scheduler = _StubScheduler()
+ service.start()
+ expected_service_lanes = {
+ RuntimeWorkLane.TASK_DEFINITIONS,
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.VAULT_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ RuntimeWorkLane.STALE_RUNS,
+ }
+ expected_controller_lanes = {
+ RuntimeWorkLane.SESSION_DELIVERIES,
+ RuntimeWorkLane.ACTIVITY_OUTPUTS,
+ }
+ assert set(supervisor.current) == {
+ *expected_controller_lanes,
+ *expected_service_lanes,
+ }
+ assert service._reconcile_task is None
+
+ await service.stop()
+ assert set(supervisor.current) == expected_controller_lanes
+ assert set(supervisor.unregistered) == expected_service_lanes
+
+ for expected_generation in (2, 3):
+ service.scheduler = _StubScheduler()
+ service.start()
+ assert set(supervisor.current) == {
+ *expected_controller_lanes,
+ *expected_service_lanes,
+ }
+ assert all(
+ supervisor.generations[lane] == expected_generation
+ for lane in expected_service_lanes
+ )
+ await service.stop()
+ assert set(supervisor.current) == expected_controller_lanes
+
+ asyncio.run(_exercise())
+
+
+def test_hfr_176_legacy_file_probes_wake_only_their_mapped_lanes(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ notifications: list[tuple[RuntimeWorkLane, ...]] = []
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(
+ platform_settings_managers={},
+ runtime_work_supervisor=SimpleNamespace(
+ notify=lambda *lanes: notifications.append(lanes)
+ ),
+ ),
+ store=ScheduledTaskStore(tmp_path / "tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "requests"),
+ )
+ service._running = True
+ service.request_store._ensure_dirs()
+ service._legacy_request_signature = service.request_store._state_signature()
+
+ async def _one_probe(delay: float) -> None:
+ assert delay == 2
+ (service.request_store.pending_dir / "edge.json").write_text(
+ "{}",
+ encoding="utf-8",
+ )
+ service._running = False
+
+ monkeypatch.setattr(scheduled_tasks.asyncio, "sleep", _one_probe)
+ asyncio.run(service._legacy_request_directory_probe())
+
+ assert notifications == [
+ (
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.STALE_RUNS,
+ )
+ ]
+
+ notifications.clear()
+ service._running = True
+ service._legacy_task_signature = scheduled_tasks._path_signature(
+ service.store.path
+ )
+
+ async def _task_probe(delay: float) -> None:
+ assert delay == 2
+ service.store.path.write_text('{"tasks": []}', encoding="utf-8")
+ service._running = False
+
+ monkeypatch.setattr(scheduled_tasks.asyncio, "sleep", _task_probe)
+ asyncio.run(service._legacy_task_definition_probe())
+ assert notifications == [(RuntimeWorkLane.TASK_DEFINITIONS,)]
+
+
+def test_failure_notice_scan_arms_the_earliest_retry_deadline() -> None:
+ retry_at = (datetime.now(timezone.utc) + timedelta(seconds=8)).isoformat()
+ sqlite_store = SimpleNamespace(
+ list_owed_failure_notices=lambda **_kwargs: [],
+ next_owed_failure_notice_at=lambda: retry_at,
+ )
+ schedule_wake = Mock()
+ service = SimpleNamespace(
+ request_store=SimpleNamespace(sqlite_backend=sqlite_store),
+ _schedule_runtime_work_wake=schedule_wake,
+ )
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
+
+ items, has_more = handler.scan(limit=10, occupied=frozenset(), cursor=None)
+
+ assert items == []
+ assert has_more is False
+ lane, delay = schedule_wake.call_args.args
+ assert lane is RuntimeWorkLane.FAILURE_NOTICES
+ assert 0 < delay <= 8
+
+
+def test_stale_lane_applies_leaked_lock_cleanup_on_the_controller_loop(
+ tmp_path: Path,
+) -> None:
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=ScheduledTaskStore(tmp_path / "tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "requests"),
+ )
+ sweep_threads: list[int] = []
+ cleanup_threads: list[int] = []
+ service._propagate_requested_cancellations_async = AsyncMock() # type: ignore[method-assign]
+
+ def _sweep(*, release_leaked_locks: bool = True) -> None:
+ assert release_leaked_locks is False
+ sweep_threads.append(threading.get_ident())
+
+ service._sweep_stale_runs = _sweep # type: ignore[method-assign]
+ service._release_leaked_session_locks = ( # type: ignore[method-assign]
+ lambda: cleanup_threads.append(threading.get_ident()) or set()
+ )
+ scheduled = Mock()
+ service._stale_run_sweep_delay_seconds = lambda: 7.0 # type: ignore[method-assign]
+ service._schedule_runtime_work_wake = scheduled # type: ignore[method-assign]
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.STALE_RUNS,
+ )
+
+ async def _exercise() -> int:
+ loop_thread = threading.get_ident()
+ assert await handler.process(
+ scheduled_tasks.RuntimeWorkItem("stale-runs", None)
+ )
+ return loop_thread
+
+ loop_thread = asyncio.run(_exercise())
+
+ assert sweep_threads and sweep_threads[0] != loop_thread
+ assert cleanup_threads == [loop_thread]
+ scheduled.assert_called_once_with(RuntimeWorkLane.STALE_RUNS, 7.0)
+
+
+def test_hfr_286_cancellation_wake_is_not_gated_by_stale_sweep_cadence(
+ tmp_path: Path,
+) -> None:
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=ScheduledTaskStore(tmp_path / "tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "requests"),
+ )
+ cancellations = AsyncMock()
+ sweep = Mock()
+ scheduled = Mock()
+ service._propagate_requested_cancellations_async = cancellations # type: ignore[method-assign]
+ service._sweep_stale_runs = sweep # type: ignore[method-assign]
+ service._stale_run_sweep_delay_seconds = lambda: 29.0 # type: ignore[method-assign]
+ service._schedule_runtime_work_wake = scheduled # type: ignore[method-assign]
+ handler = scheduled_tasks._ScheduledRuntimeWorkHandler(
+ service,
+ RuntimeWorkLane.STALE_RUNS,
+ )
+
+ items, has_more = handler.scan(limit=4, occupied=frozenset(), cursor=None)
+
+ assert [item.partition_key for item in items] == ["run-cancellations"]
+ assert has_more is False
+ scheduled.assert_called_once_with(RuntimeWorkLane.STALE_RUNS, 29.0)
+ asyncio.run(handler.process(items[0]))
+ cancellations.assert_awaited_once_with()
+ sweep.assert_not_called()
+
+
@pytest.mark.parametrize("stop_entrypoint", ["stop", "lease_loss"])
def test_request_recovery_registration_is_owned_by_exact_service_generation(
tmp_path: Path,
@@ -9176,15 +10127,23 @@ def test_drain_does_not_block_on_hung_execution(tmp_path: Path) -> None:
asyncio.run(_exercise())
-def test_drain_defers_im_runs_until_transport_ready_without_blocking_workbench(tmp_path: Path) -> None:
+def test_hfr_177_transport_ready_wakes_requests_and_resumes_skipped_run(
+ tmp_path: Path,
+) -> None:
async def _exercise() -> None:
store = TaskExecutionStore(tmp_path / "reqs")
workbench = store.enqueue_hook_send(session_key="avibe::project::proj_test", prompt="local")
discord = store.enqueue_hook_send(session_key="discord::channel::C123", prompt="remote")
ready_platforms = {"avibe"}
+ notifications: list[tuple[tuple[RuntimeWorkLane, ...], bool]] = []
controller = SimpleNamespace(
platform_settings_managers={},
is_im_transport_ready=lambda platform: platform in ready_platforms,
+ runtime_work_supervisor=SimpleNamespace(
+ notify=lambda *lanes, reset_cursor=False: notifications.append(
+ (lanes, reset_cursor)
+ )
+ ),
)
service = ScheduledTaskService(
controller=controller,
@@ -9207,7 +10166,7 @@ def test_drain_defers_im_runs_until_transport_ready_without_blocking_workbench(t
ready_platforms.add("discord")
service.notify_transport_ready("discord")
- assert service._drain_dirty is True
+ assert notifications == [((RuntimeWorkLane.REQUESTS,), True)]
await service._drain_requests()
await asyncio.sleep(0)
@@ -10151,7 +11110,7 @@ def test_execute_task_notifies_then_pauses_after_three_unresolvable_failures(
notices = _spy_binding_notices(service)
for attempt in range(1, 4):
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
current = store.get_task(task.id)
assert current is not None
assert current.enabled is (attempt < 3)
@@ -10196,14 +11155,14 @@ def test_unresolvable_target_errors_follow_the_configured_language(
)
service = _binding_service(tmp_path, store, [], language=language)
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
retry_error = store.get_task(task.id).last_error
assert retry_copy in retry_error
assert "sesdoesnotexist" in retry_error
assert f"vibe task update {task.id} --session-id <id>" in retry_error
- asyncio.run(service._run_task(task.id))
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
paused_error = store.get_task(task.id).last_error
assert paused_copy in paused_error
assert "sesdoesnotexist" in paused_error
@@ -10232,7 +11191,7 @@ def test_existing_policy_never_rebinds(tmp_path: Path, monkeypatch) -> None:
service = _binding_service(tmp_path, store, [])
for _ in range(3):
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
updated = store.get_task(task.id)
assert updated is not None
@@ -10264,7 +11223,7 @@ def test_create_once_rebinds_when_session_deleted(tmp_path: Path, monkeypatch) -
service = _binding_service(tmp_path, store, calls)
notices = _spy_binding_notices(service)
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
updated = store.get_task(task.id)
assert updated is not None
@@ -10298,7 +11257,7 @@ def test_repeated_binding_failures_notify_only_on_state_transitions(tmp_path: Pa
notices = _spy_binding_notices(service)
for _ in range(3):
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
assert [notice.action for notice in notices] == ["failing", "paused"]
@@ -10331,7 +11290,7 @@ def test_transient_resolver_errors_do_not_auto_pause_a_definition(tmp_path: Path
service._execute_request = _transient_failure # type: ignore[method-assign]
for _ in range(3):
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
saved = store.get_task(task.id)
assert saved is not None and saved.enabled is True
@@ -10360,7 +11319,7 @@ def test_a_success_resets_the_unresolvable_target_auto_pause_streak(
service = _binding_service(tmp_path, store, [])
for _ in range(2):
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
current = store.get_task(task.id)
assert current is not None
@@ -10373,7 +11332,7 @@ def test_a_success_resets_the_unresolvable_target_auto_pause_streak(
assert claimed is not None
service.request_store.complete(claimed, ok=True, task_id=task.id)
- asyncio.run(service._run_task(task.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, task.id))
saved = store.get_task(task.id)
assert saved is not None and saved.enabled is True
@@ -16195,7 +17154,7 @@ def test_a_definition_does_not_fire_while_its_own_worker_may_be_alive(
)
# Scoped to the definition: another definition's fire is not held up by it.
- asyncio.run(service._run_task(other.id))
+ asyncio.run(_fire_and_finish_scheduled_task(service, other.id))
assert other_ran.exists(), (
"one definition's live worker blocked every other definition's fire"
)
diff --git a/tests/test_session_activities.py b/tests/test_session_activities.py
index 753928bc8..74f3ea164 100644
--- a/tests/test_session_activities.py
+++ b/tests/test_session_activities.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from contextlib import nullcontext
+from datetime import datetime, timedelta, timezone
from pathlib import Path
import threading
from types import SimpleNamespace
@@ -64,6 +65,160 @@ def test_activity_lifecycle_keeps_state_axes_orthogonal():
assert registry.has_completed_output("claude", "runtime-1") is False
+def test_hfr_166_recovered_unbound_grace_uses_first_durable_completion(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ first = datetime(2026, 8, 4, 0, 0, tzinfo=timezone.utc)
+ for activity_id, completed_at in (
+ ("task-a", first),
+ ("task-b", first + timedelta(seconds=5)),
+ ):
+ activity = SessionActivity(
+ id=activity_id,
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ kind="background_task",
+ status="completed",
+ turn_id="turn-1",
+ completed_at=completed_at.isoformat(),
+ updated_at=completed_at.isoformat(),
+ )
+ store.upsert_activity(activity.to_dict(), phase="awaiting_output")
+
+ recovered = SessionActivityRegistry(store)
+ assert recovered.recovered_output_delay_seconds(
+ "claude",
+ "runtime-1",
+ grace_seconds=10,
+ now=first + timedelta(seconds=6),
+ ) == 4
+
+ claimed = recovered.claim_completed_output_batch("claude", "runtime-1")
+ assert [activity.id for activity in claimed] == ["task-a", "task-b"]
+ assert recovered.requeue_completed_outputs(claimed) == 2
+ assert recovered.recovered_output_delay_seconds(
+ "claude",
+ "runtime-1",
+ grace_seconds=10,
+ now=first + timedelta(seconds=6),
+ ) == 0
+ engine.dispose()
+
+
+def test_hfr_166_recovered_runtime_scan_applies_keyset_limit_in_registry() -> None:
+ completed_at = datetime.now(timezone.utc).isoformat()
+
+ class _Store:
+ @staticmethod
+ def list_activities():
+ return [
+ {
+ "activity": SessionActivity(
+ id=f"activity-{index}",
+ backend="claude",
+ runtime_key=f"runtime-{index:03d}",
+ session_id=f"session-{index}",
+ kind="background_task",
+ status="completed",
+ completed_at=completed_at,
+ metadata={"output_batch_id": f"batch-{index}"},
+ ).to_dict(),
+ "phase": "awaiting_output",
+ }
+ for index in range(100)
+ ]
+
+ grace_calls = 0
+
+ def grace_seconds(_backend: str) -> float:
+ nonlocal grace_calls
+ grace_calls += 1
+ return 10.0
+
+ registry = SessionActivityRegistry(_Store())
+ page, has_more, retry_after, scanned_cursor = (
+ registry.scan_recovered_output_runtimes(
+ limit=2,
+ cursor=None,
+ grace_seconds=grace_seconds,
+ )
+ )
+
+ assert page == [
+ ("claude", "runtime-000"),
+ ("claude", "runtime-001"),
+ ]
+ assert has_more is True
+ assert retry_after is None
+ assert scanned_cursor == "claude\x1fruntime-001"
+ assert grace_calls == 2
+
+ next_page, has_more, _retry_after, scanned_cursor = (
+ registry.scan_recovered_output_runtimes(
+ limit=2,
+ cursor="claude\x1fruntime-001",
+ grace_seconds=grace_seconds,
+ )
+ )
+ assert next_page == [
+ ("claude", "runtime-002"),
+ ("claude", "runtime-003"),
+ ]
+ assert has_more is True
+ assert scanned_cursor == "claude\x1fruntime-003"
+ assert grace_calls == 4
+
+
+def test_hfr_285_deferred_runtime_scan_bounds_raw_rows_and_indexes_deadline() -> None:
+ completed_at = datetime.now(timezone.utc).isoformat()
+
+ class _Store:
+ @staticmethod
+ def list_activities():
+ return [
+ {
+ "activity": SessionActivity(
+ id=f"activity-{index}",
+ backend="claude",
+ runtime_key=f"runtime-{index:03d}",
+ session_id=f"session-{index}",
+ kind="background_task",
+ status="completed",
+ completed_at=completed_at,
+ ).to_dict(),
+ "phase": "awaiting_output",
+ }
+ for index in range(100)
+ ]
+
+ grace_calls = 0
+
+ def grace_seconds(_backend: str) -> float:
+ nonlocal grace_calls
+ grace_calls += 1
+ return 30.0
+
+ registry = SessionActivityRegistry(_Store())
+ page, has_more, retry_after, scanned_cursor = (
+ registry.scan_recovered_output_runtimes(
+ limit=2,
+ cursor=None,
+ grace_seconds=grace_seconds,
+ )
+ )
+
+ assert page == []
+ assert has_more is True
+ assert retry_after is not None and 0 < retry_after <= 30
+ assert scanned_cursor == "claude\x1fruntime-001"
+ assert grace_calls == 3
+
+
def test_activity_batch_claim_leaves_interleaved_output_in_place():
registry = SessionActivityRegistry()
for activity_id, turn_id in (
@@ -98,11 +253,15 @@ def test_activity_batch_claim_leaves_interleaved_output_in_place():
"task-current-a",
"task-current-b",
]
+ for activity in claimed:
+ registry.ack_completed_output(activity)
older = registry.claim_completed_output_batch("claude", "runtime-1")
+ for activity in older:
+ registry.ack_completed_output(activity)
other = registry.claim_completed_output_batch("claude", "runtime-1")
assert [activity.id for activity in older] == ["task-old"]
assert [activity.id for activity in other] == ["task-other"]
- for activity in [*claimed, *older, *other]:
+ for activity in other:
registry.ack_completed_output(activity)
@@ -142,14 +301,13 @@ def test_activity_batch_requeue_restores_global_fifo_position():
restored = []
while activity := registry.claim_completed_output("claude", "runtime-1"):
restored.append(activity)
+ registry.ack_completed_output(activity)
assert [activity.id for activity in restored] == [
"task-old",
"task-current-b",
"task-other",
"task-new",
]
- for activity in restored:
- registry.ack_completed_output(activity)
def test_activity_output_native_id_is_stable_across_recovery_contexts():
diff --git a/tests/test_session_archive.py b/tests/test_session_archive.py
index 96d9aea1a..a34436b5e 100644
--- a/tests/test_session_archive.py
+++ b/tests/test_session_archive.py
@@ -250,6 +250,71 @@ def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:
assert request_statuses[other_req["id"]] == "pending"
+def test_hfr_287_new_session_teardown_publishes_run_updates_after_commit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from storage import background
+
+ service = SQLiteSessionsService(tmp_path / "vibe.sqlite")
+ published: list[tuple[set[str], dict[str, tuple[str, bool]]]] = []
+ try:
+ session_id = _bind_session(
+ service,
+ channel="C_NEW_WAKE",
+ anchor="slack_new_wake",
+ native="native-new-wake",
+ )
+ with service.engine.begin() as conn:
+ _insert_run(
+ conn,
+ run_id="run-running",
+ session_id=session_id,
+ status="running",
+ )
+ _insert_run(
+ conn,
+ run_id="run-queued",
+ session_id=session_id,
+ status="queued",
+ )
+
+ def _capture(rows) -> None: # noqa: ANN001
+ with service.engine.connect() as conn:
+ committed = {
+ str(row.id): (str(row.status), bool(row.cancel_requested))
+ for row in conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ ).where(
+ agent_runs.c.id.in_(("run-running", "run-queued"))
+ )
+ )
+ }
+ published.append(({str(row["id"]) for row in rows}, committed))
+
+ monkeypatch.setattr(background, "_publish_run_rows_updated", _capture)
+
+ assert service.delete_agent_sessions(
+ scope_key="slack::channel::C_NEW_WAKE",
+ agent_name="claude",
+ ) == 1
+ finally:
+ service.close()
+
+ assert published == [
+ (
+ {"run-running", "run-queued"},
+ {
+ "run-running": ("running", True),
+ "run-queued": ("canceled", True),
+ },
+ )
+ ]
+
+
def test_archive_release_vault_scopes_runs_in_threadpool(monkeypatch) -> None:
from vibe import api, ui_server
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 3f004d5fb..312853eab 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1,5 +1,7 @@
+import asyncio
import gzip
import json
+import threading
from types import SimpleNamespace
import pytest
@@ -33,6 +35,64 @@ def _raw_client_get(client, path: str, *, headers: dict[str, str] | None = None)
return response, body
+def test_archive_definition_wakes_do_not_block_the_asgi_loop(monkeypatch):
+ published: list[tuple[int, str]] = []
+
+ def _publish(*, definition_type: str) -> None:
+ published.append((threading.get_ident(), definition_type))
+
+ monkeypatch.setattr(
+ "core.inbox_events.publish_definitions_updated",
+ _publish,
+ )
+
+ async def _exercise() -> int:
+ loop_thread = threading.get_ident()
+ await ui_server._archive_publish_definition_updates(
+ {"tasks": 1, "watches": 1}
+ )
+ return loop_thread
+
+ loop_thread = asyncio.run(_exercise())
+
+ assert {definition_type for _, definition_type in published} == {
+ "scheduled",
+ "watch",
+ }
+ assert all(thread_id != loop_thread for thread_id, _ in published)
+
+
+def test_hfr_283_archive_run_cancellations_wake_runtime_consumers(monkeypatch):
+ published: list[tuple[str, dict[str, str], float]] = []
+
+ async def _publish(event_type, data, *, timeout): # noqa: ANN001, ANN202
+ published.append((event_type, data, timeout))
+ return {"ok": True}
+
+ monkeypatch.setattr("vibe.internal_client.publish_event", _publish)
+
+ asyncio.run(
+ ui_server._archive_publish_run_updates(
+ "session-a",
+ {"runs": 2},
+ )
+ )
+ asyncio.run(
+ ui_server._archive_publish_run_updates(
+ "session-b",
+ {"runs": 0},
+ )
+ )
+
+ assert published == [
+ (
+ "runs.updated",
+ {"session_id": "session-a", "reason": "session_archived"},
+ 1.5,
+ )
+ ]
+
+
def test_websocket_echo_is_disabled_by_default(monkeypatch):
monkeypatch.delenv("VIBE_UI_ENABLE_WS_ECHO", raising=False)
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index 7a1dda2e2..40b479f58 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -332,11 +332,15 @@ def test_create_list_delete_roundtrip(monkeypatch):
def test_create_vault_secret_publishes_update_event(monkeypatch):
published = []
+ bridged = []
monkeypatch.setattr(
"vibe.sse_broker.broker.publish",
lambda event_type, data: published.append((event_type, data)),
)
- monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+ monkeypatch.setattr(
+ "vibe.internal_client.publish_event_sync",
+ lambda *args, **kwargs: bridged.append((args, kwargs)),
+ )
monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
api.create_vault_secret(
@@ -347,6 +351,10 @@ def test_create_vault_secret_publishes_update_event(monkeypatch):
)
assert ("vaults.updated", {"scope": "secret", "secret_name": "EVENT_KEY"}) in published
+ assert len(bridged) == 1
+ assert bridged[0][0][0] == "vaults.updated"
+ assert bridged[0][0][1]["scope"] == "secret"
+ assert bridged[0][0][1]["_event_id"]
def test_standard_rest_create_rejects_plaintext_value(monkeypatch):
diff --git a/tests/test_watches.py b/tests/test_watches.py
index 87e3b5eb3..228fb8df1 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -4,6 +4,7 @@ import asyncio
import json
import os
import sys
+import threading
import time
from datetime import datetime
from pathlib import Path
@@ -14,14 +15,22 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
-from core import watch_worker
+from core import watch_worker, watches as watches_module
from core.process_isolation import (
PersistedProcessIdentity,
ProcessIdentity,
fingerprint_process_marker,
)
+from core.runtime_work import RuntimeWorkItem, RuntimeWorkLane, RuntimeWorkSupervisor
from core.scheduled_tasks import TaskExecutionStore
-from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore, _CycleResult
+from core.watches import (
+ ManagedWatchService,
+ ManagedWatchStore,
+ WatchRuntimeStateStore,
+ _CycleResult,
+ _ManagedWatchRuntimeWorkHandler,
+ _StaleWorkerRecovery,
+)
from storage.background import SQLiteBackgroundTaskStore
TEST_MARKER = "test-watch-worker"
@@ -178,6 +187,40 @@ def test_managed_watch_store_round_trip(tmp_path: Path) -> None:
assert saved.post_to == "channel"
+def test_hfr_174_watch_definition_commit_emits_watch_hint(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from core import inbox_events
+
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", True)
+ events: list[tuple[str, dict]] = []
+ subscription = inbox_events.bus.subscribe_callback(
+ lambda event_type, payload: events.append((event_type, payload))
+ )
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ store.add_watch(
+ name="Definition wake",
+ session_key="avibe::agent::default",
+ command=["true"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=30,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ inbox_events.bus.unsubscribe(subscription)
+
+ assert events == [
+ (inbox_events.DEFINITIONS_UPDATED_EVENT, {"definition_type": "watch"})
+ ]
+
+
def test_managed_watch_store_preserves_zero_values_on_reload(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
watch = store.add_watch(
@@ -1686,7 +1729,11 @@ def test_managed_watch_service_start_keeps_recovery_off_event_loop(
request_store=TaskExecutionStore(tmp_path / "task_requests"),
runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
)
- monkeypatch.setattr(service, "_reap_stale_workers", lambda: time.sleep(0.15))
+ def inspect_stale_workers() -> _StaleWorkerRecovery:
+ time.sleep(0.15)
+ return _StaleWorkerRecovery(True)
+
+ monkeypatch.setattr(service, "_inspect_stale_workers", inspect_stale_workers)
monkeypatch.setattr(service, "reconcile_watches", lambda: False)
async def _run() -> None:
@@ -1703,6 +1750,365 @@ def test_managed_watch_service_start_keeps_recovery_off_event_loop(
asyncio.run(_run())
+def test_hfr_164_watch_restart_replaces_only_its_registration_generation(
+ tmp_path: Path,
+) -> None:
+ class EmptyHandler:
+ def scan(self, *, limit, occupied, cursor): # noqa: ANN001, ANN202
+ del limit, occupied, cursor
+ return [], False
+
+ async def process(self, item) -> None: # noqa: ANN001
+ raise AssertionError(item)
+
+ async def _run() -> None:
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ delivery_token = supervisor.register(
+ RuntimeWorkLane.SESSION_DELIVERIES,
+ EmptyHandler(),
+ )
+ await supervisor.activate()
+ service = ManagedWatchService(
+ controller=SimpleNamespace(runtime_work_supervisor=supervisor),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+
+ await _start_watch_service(service)
+ first = service._runtime_work_token
+ assert first is not None
+ assert RuntimeWorkLane.SESSION_DELIVERIES in supervisor._registrations
+ await service.stop()
+ assert RuntimeWorkLane.WATCH_DEFINITIONS not in supervisor._registrations
+ assert supervisor._registrations[RuntimeWorkLane.SESSION_DELIVERIES].token == delivery_token
+
+ await _start_watch_service(service)
+ second = service._runtime_work_token
+ assert second is not None
+ assert second.generation > first.generation
+ await service.stop()
+ await supervisor.stop()
+
+ asyncio.run(_run())
+
+
+def test_hfr_176_legacy_watch_probe_only_wakes_watch_definitions(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ notified: list[RuntimeWorkLane] = []
+ service = ManagedWatchService(
+ controller=SimpleNamespace(
+ runtime_work_supervisor=SimpleNamespace(
+ notify=lambda *lanes: notified.extend(lanes),
+ )
+ ),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ service._running = True
+ service._legacy_watch_signature = (1, 1, 1)
+ monkeypatch.setattr(watches_module, "_path_signature", lambda _path: (2, 2, 2))
+
+ async def stop_after_tick(_delay: float) -> None:
+ service._running = False
+
+ monkeypatch.setattr(watches_module.asyncio, "sleep", stop_after_tick)
+ asyncio.run(service._legacy_runtime_work_probe())
+
+ assert notified == [RuntimeWorkLane.WATCH_DEFINITIONS]
+
+
+def test_hfr_179_watch_store_phases_are_single_flight_and_apply_on_loop(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ service._recovery_pending = False
+ service._runtime_state_dirty = False
+ scan_entered = threading.Event()
+ release_scan = threading.Event()
+ guarded_entered = threading.Event()
+ scan_threads: list[int] = []
+ reconcile_threads: list[int] = []
+
+ def blocking_reload() -> bool:
+ scan_threads.append(threading.get_ident())
+ scan_entered.set()
+ assert release_scan.wait(timeout=1)
+ return True
+
+ monkeypatch.setattr(service.store, "maybe_reload", blocking_reload)
+
+ async def _run() -> None:
+ loop_thread = threading.get_ident()
+ handler = _ManagedWatchRuntimeWorkHandler(service)
+ scan = asyncio.create_task(
+ asyncio.to_thread(
+ handler.scan,
+ limit=1,
+ occupied=frozenset(),
+ cursor=None,
+ )
+ )
+ assert await asyncio.to_thread(scan_entered.wait, 1)
+
+ guarded = asyncio.create_task(
+ service._watch_store_call_async(
+ "watch-a",
+ "guarded-test",
+ lambda: guarded_entered.set() or True,
+ guarded=True,
+ )
+ )
+ await asyncio.sleep(0)
+ assert not guarded_entered.is_set()
+ release_scan.set()
+ items, has_more = await scan
+ assert not has_more
+ assert await guarded is True
+
+ def reconcile(watches) -> bool: # noqa: ANN001
+ del watches
+ reconcile_threads.append(threading.get_ident())
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", reconcile)
+ assert await handler.process(items[0]) is True
+ assert scan_threads and scan_threads[0] != loop_thread
+ assert reconcile_threads == [loop_thread]
+
+ asyncio.run(_run())
+
+
+def test_hfr_179_watch_wake_during_reconcile_replays_after_owner_release(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(runtime_work_supervisor=supervisor),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ service._recovery_pending = False
+ service._reconcile_dirty = False
+ service._runtime_state_dirty = True
+ reload_calls = 0
+ persist_entered = asyncio.Event()
+ release_persist = asyncio.Event()
+ second_reload = threading.Event()
+
+ def reload_store() -> bool:
+ nonlocal reload_calls
+ reload_calls += 1
+ if reload_calls == 2:
+ second_reload.set()
+ return False
+
+ async def persist_runtime_state() -> None:
+ persist_entered.set()
+ await release_persist.wait()
+ service._runtime_state_dirty = False
+
+ monkeypatch.setattr(service.store, "maybe_reload", reload_store)
+ monkeypatch.setattr(service, "_persist_runtime_state", persist_runtime_state)
+
+ async def _run() -> None:
+ supervisor.register(
+ RuntimeWorkLane.WATCH_DEFINITIONS,
+ _ManagedWatchRuntimeWorkHandler(service),
+ )
+ await supervisor.activate()
+ await asyncio.wait_for(persist_entered.wait(), 1)
+
+ supervisor.notify(RuntimeWorkLane.WATCH_DEFINITIONS)
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert reload_calls == 1
+
+ release_persist.set()
+ assert await asyncio.to_thread(second_reload.wait, 1)
+ assert reload_calls == 2
+ await supervisor.stop()
+
+ asyncio.run(_run())
+
+
+def test_hfr_179_blocked_watch_recovery_arms_generation_scoped_recheck(
+ tmp_path: Path,
+) -> None:
+ delayed: list[tuple[object, float]] = []
+ supervisor = SimpleNamespace(
+ notify_after=lambda token, delay: delayed.append((token, delay)),
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(runtime_work_supervisor=supervisor),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ token = object()
+ service._runtime_work_token = token # type: ignore[assignment]
+ service._recovery_pending = False
+ service._reconcile_dirty = False
+ service._runtime_state_dirty = False
+ service._recovery_blocked_watch_ids.add("watch-a")
+ handler = _ManagedWatchRuntimeWorkHandler(service)
+ item = RuntimeWorkItem(
+ "managed-watches",
+ {
+ "recovery": _StaleWorkerRecovery(True),
+ "unblocked": (),
+ "changed": False,
+ "watches": (),
+ "store_error": None,
+ "fused": False,
+ },
+ rearm_after_process=False,
+ )
+
+ assert asyncio.run(handler.process(item)) is True
+ assert delayed == [(token, watches_module.WATCH_RECONCILE_INTERVAL_SECONDS)]
+
+
+def test_hfr_179_pending_watch_recovery_uses_watch_lane_cadence(
+ tmp_path: Path,
+) -> None:
+ delayed: list[tuple[object, float]] = []
+ supervisor = SimpleNamespace(
+ notify_after=lambda token, delay: delayed.append((token, delay)),
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(runtime_work_supervisor=supervisor),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ token = object()
+ service._runtime_work_token = token # type: ignore[assignment]
+ handler = _ManagedWatchRuntimeWorkHandler(service)
+ item = RuntimeWorkItem(
+ "managed-watches",
+ {
+ "recovery": _StaleWorkerRecovery(False),
+ "unblocked": (),
+ "changed": False,
+ "watches": (),
+ "store_error": None,
+ "fused": False,
+ },
+ rearm_after_process=False,
+ )
+
+ assert asyncio.run(handler.process(item)) is True
+ assert service._recovery_pending is True
+ assert delayed == [(token, watches_module.WATCH_RECONCILE_INTERVAL_SECONDS)]
+
+
+def test_hfr_179_watch_store_fuse_stops_generation_reads_and_retries(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ service._recovery_pending = False
+ service._reconcile_dirty = False
+ service._runtime_state_dirty = False
+ reads = 0
+
+ def fail_read() -> bool:
+ nonlocal reads
+ reads += 1
+ raise OSError("watch store unavailable")
+
+ monkeypatch.setattr(service.store, "maybe_reload", fail_read)
+ handler = _ManagedWatchRuntimeWorkHandler(service)
+
+ async def _run() -> None:
+ outcomes = []
+ for _ in range(watches_module.WATCH_STORE_RECONCILE_FUSE_FAILURES):
+ items, _has_more = await asyncio.to_thread(
+ handler.scan,
+ limit=1,
+ occupied=frozenset(),
+ cursor=None,
+ )
+ outcomes.append(await handler.process(items[0]))
+
+ assert outcomes[:-1] == [False] * (len(outcomes) - 1)
+ assert outcomes[-1] is True
+ assert service._store_error_fused is True
+ assert reads == watches_module.WATCH_STORE_RECONCILE_FUSE_FAILURES
+
+ persisted = 0
+
+ async def persist_runtime_state() -> None:
+ nonlocal persisted
+ persisted += 1
+ service._runtime_state_dirty = False
+
+ monkeypatch.setattr(service, "_persist_runtime_state", persist_runtime_state)
+ service._runtime_state_dirty = True
+ items, _has_more = await asyncio.to_thread(
+ handler.scan,
+ limit=1,
+ occupied=frozenset(),
+ cursor=None,
+ )
+ assert await handler.process(items[0]) is True
+ assert reads == watches_module.WATCH_STORE_RECONCILE_FUSE_FAILURES
+ assert persisted == 1
+
+ asyncio.run(_run())
+
+
+def test_watch_runtime_state_persistence_failure_rearms_maintenance(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ service._recovery_pending = False
+ service._reconcile_dirty = False
+ service._runtime_state_dirty = True
+
+ async def _persist_but_remain_dirty() -> None:
+ service._runtime_state_dirty = True
+
+ monkeypatch.setattr(service, "_persist_runtime_state", _persist_but_remain_dirty)
+ handler = _ManagedWatchRuntimeWorkHandler(service)
+ item = RuntimeWorkItem(
+ "managed-watches",
+ {
+ "recovery": _StaleWorkerRecovery(True),
+ "unblocked": (),
+ "changed": False,
+ "watches": (),
+ },
+ rearm_after_process=False,
+ )
+
+ assert asyncio.run(handler.process(item)) is False
+ assert service._runtime_state_dirty is True
+
+
def test_managed_watch_service_start_retries_unreadable_runtime_before_reconcile(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
diff --git a/vibe/api.py b/vibe/api.py
index de4aa5555..26ab1deec 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1584,7 +1584,10 @@ def _publish_vaults_updated(
"""Publish a UI-server-local vault update event for refetch-on-event pages."""
try:
+ from uuid import uuid4
+
from core.inbox_events import VAULTS_UPDATED_EVENT, vaults_updated_payload
+ from vibe.inbox_bridge import remember_local_event
from vibe.sse_broker import broker
payload = vaults_updated_payload(
@@ -1595,16 +1598,25 @@ def _publish_vaults_updated(
grant_status=grant_status,
secret_name=secret_name,
)
+ event_id = uuid4().hex
+ except Exception:
+ logger.debug("vaults.updated event construction failed", exc_info=True)
+ return
+ try:
broker.publish(VAULTS_UPDATED_EVENT, payload)
- if broker.subscriber_count() == 0:
- try:
- from vibe import internal_client
+ remember_local_event(event_id)
+ except Exception:
+ logger.debug("vaults.updated local publish failed", exc_info=True)
+ try:
+ from vibe import internal_client
- internal_client.publish_event_sync(VAULTS_UPDATED_EVENT, payload, timeout=1.5)
- except Exception:
- logger.debug("vaults.updated bridge publish failed", exc_info=True)
+ internal_client.publish_event_sync(
+ VAULTS_UPDATED_EVENT,
+ {**payload, "_event_id": event_id},
+ timeout=1.5,
+ )
except Exception:
- logger.debug("vaults.updated publish failed", exc_info=True)
+ logger.debug("vaults.updated bridge publish failed", exc_info=True)
def _notify_vault_request_created(request: dict | None) -> None:
diff --git a/vibe/inbox_bridge.py b/vibe/inbox_bridge.py
index ddd81f34f..023eaa8f8 100644
--- a/vibe/inbox_bridge.py
+++ b/vibe/inbox_bridge.py
@@ -19,6 +19,8 @@ from __future__ import annotations
import asyncio
import logging
+import threading
+from collections import deque
from core.inbox_events import WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT
from vibe import internal_client
@@ -32,6 +34,38 @@ logger = logging.getLogger(__name__)
_BACKOFF_INITIAL = 1.0
_BACKOFF_MAX = 15.0
_bridge_connected = False
+_LOCAL_EVENT_IDS_MAX = 256
+_local_event_ids: set[str] = set()
+_local_event_order: deque[str] = deque()
+_local_event_lock = threading.Lock()
+
+
+def remember_local_event(event_id: str) -> None:
+ identity = str(event_id or "").strip()
+ if not identity:
+ return
+ with _local_event_lock:
+ if identity in _local_event_ids:
+ return
+ _local_event_ids.add(identity)
+ _local_event_order.append(identity)
+ while len(_local_event_order) > _LOCAL_EVENT_IDS_MAX:
+ _local_event_ids.discard(_local_event_order.popleft())
+
+
+def _consume_local_event(event_id: str) -> bool:
+ identity = str(event_id or "").strip()
+ if not identity:
+ return False
+ with _local_event_lock:
+ if identity not in _local_event_ids:
+ return False
+ _local_event_ids.discard(identity)
+ try:
+ _local_event_order.remove(identity)
+ except ValueError:
+ pass
+ return True
def is_bridge_connected() -> bool:
@@ -63,6 +97,13 @@ async def run_inbox_bridge() -> None:
backoff = _BACKOFF_INITIAL
if event_type == "connected":
_set_bridge_connected(True)
+ event_id = (
+ str(data.get("_event_id") or "")
+ if isinstance(data, dict)
+ else ""
+ )
+ if _consume_local_event(event_id):
+ continue
broker.publish(event_type, data)
except asyncio.CancelledError:
_set_bridge_connected(False)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4f7e490cb..60bb9fc95 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6980,6 +6980,54 @@ async def _archive_release_vault_scopes(session_id: str, revoked_vault_scopes: l
logger.debug("archive: resident-agent grant release failed for %s", session_id, exc_info=True)
+async def _archive_publish_definition_updates(reclaimed: dict[str, Any]) -> None:
+ definition_types = [
+ definition_type
+ for definition_type, key in (("scheduled", "tasks"), ("watch", "watches"))
+ if reclaimed.get(key)
+ ]
+ if not definition_types:
+ return
+ from core.inbox_events import publish_definitions_updated
+
+ await asyncio.gather(
+ *(
+ asyncio.to_thread(
+ publish_definitions_updated,
+ definition_type=definition_type,
+ )
+ for definition_type in definition_types
+ )
+ )
+
+
+async def _archive_publish_run_updates(
+ session_id: str,
+ reclaimed: dict[str, Any],
+) -> None:
+ """Wake post-commit Run consumers for archive cancellation writes."""
+
+ if not reclaimed.get("runs"):
+ return
+ from core.inbox_events import RUNS_UPDATED_EVENT
+ from vibe import internal_client
+
+ try:
+ await internal_client.publish_event(
+ RUNS_UPDATED_EVENT,
+ {"session_id": session_id, "reason": "session_archived"},
+ timeout=1.5,
+ )
+ except internal_client.InternalServerUnavailable:
+ pass
+ except Exception:
+ logger.debug(
+ "archive: run update publish failed for %s",
+ session_id,
+ exc_info=True,
+ )
+
+
@app.route("/api/sessions/<session_id>", methods=["DELETE"])
async def sessions_archive(session_id: str):
"""Permanently archive a session and reclaim its bound resources.
@@ -7009,6 +7057,11 @@ async def sessions_archive(session_id: str):
return _coded_error_response(code, str(err), 403)
revoked_vault_scopes = session.pop("revoked_vault_grant_scopes", [])
+ reclaimed = session.get("reclaimed") or {}
+ await asyncio.gather(
+ _archive_publish_definition_updates(reclaimed),
+ _archive_publish_run_updates(session_id, reclaimed),
+ )
# Broadcast + return immediately — the archive is already committed. Other
# mounted clients (sidebars, tabs) drop the row live and leave the chat if
@@ -8811,6 +8864,9 @@ def harness_task_patch(task_id: str):
return jsonify({"ok": False, "code": "task_not_found"}), 404
store.set_definition_enabled(task_id, enabled, definition_type="scheduled")
task = store.get_scheduled_task(task_id)
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="scheduled")
return jsonify({"ok": True, "task": task})
@@ -8820,6 +8876,9 @@ def harness_task_delete(task_id: str):
if not store.get_scheduled_task(task_id):
return jsonify({"ok": False, "code": "task_not_found"}), 404
store.remove_task(task_id)
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="scheduled")
return jsonify({"ok": True, "id": task_id})
@@ -8869,6 +8928,9 @@ def harness_watch_patch(watch_id: str):
return jsonify({"ok": False, "code": "watch_not_found"}), 404
store.set_definition_enabled(watch_id, enabled, definition_type="watch")
watch = store.get_watch(watch_id)
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="watch")
return jsonify({"ok": True, "watch": watch})
@@ -8878,6 +8940,9 @@ def harness_watch_delete(watch_id: str):
if not store.get_watch(watch_id):
return jsonify({"ok": False, "code": "watch_not_found"}), 404
store.remove_task(watch_id)
+ from core.inbox_events import publish_definitions_updated
+
+ publish_definitions_updated(definition_type="watch")
return jsonify({"ok": True, "id": watch_id})