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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(harness): settle teardown-interrupted runs (#1140)
Call Whitefe821905f287
diff --git a/core/failure_notices.py b/core/failure_notices.pyindex 4350c42b5..665b11bdb 100644--- a/core/failure_notices.py+++ b/core/failure_notices.py@@ -47,6 +47,7 @@ from core.run_settlement import (INTERRUPT_REASON_RESTARTED,RUN_INTERRUPTION_REASONS,SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_INTERRUPTED,SETTLED_BY_NO_TERMINAL_RESULT,SETTLED_BY_REFUSED_CONCURRENT_TURN,SETTLED_BY_STOPPED,@@ -233,6 +234,7 @@ DEFERRAL_RECHECK_SECONDS = 30.0NOTICE_REASON_I18N_KEYS: dict[str, str] = {SETTLED_BY_STOPPED: "harness.notice.reason.stopped",SETTLED_BY_BACKEND_REFRESH: "harness.notice.reason.backendRefresh",+ SETTLED_BY_INTERRUPTED: "harness.notice.reason.interrupted",INTERRUPT_REASON_EVICTED: "harness.notice.reason.evicted",INTERRUPT_REASON_RESTARTED: "harness.notice.reason.restarted",INTERRUPT_REASON_LIFETIME_TIMEOUT: "harness.notice.reason.lifetimeTimeout",diff --git a/core/run_settlement.py b/core/run_settlement.pyindex b61bc4832..34018927b 100644--- a/core/run_settlement.py+++ b/core/run_settlement.py@@ -1,13 +1,13 @@-"""Shared vocabulary for how a turn's dispatch waiter was settled.+"""Shared vocabulary for how an active execution ended without a backend result.Two layers need to agree on these strings and neither owns the other:* ``core/services/dispatch.py`` records WHY a streaming turn's waiter wasreleased (``TurnDispatchOutcome.settled_by``), which is stamped on the liveturn sink by the three release sites.-* ``core/scheduled_tasks.py`` turns that into an ``agent_runs`` terminal state- plus ``metadata.interrupt_reason`` for a run whose backend never emitted a- terminal result.+* ``core/scheduled_tasks.py`` turns a waiter settlement or an execution-level+ teardown into an ``agent_runs`` terminal state plus+ ``metadata.interrupt_reason``.Keeping the strings here (rather than inline at each site) is what stops thevalues in ``docs/plans/agent-run-zombie-settlement.md`` from drifting apart from@@ -59,12 +59,19 @@ SETTLED_BY_TURN_ONLY_RESULT: Final = "turn_only_result"#: a cancelled task — nobody asked for this run to end, so it must not be#: reported as ``canceled`` with the user-stop explanation.#:-#: Spelled ``backend_refresh`` rather than reusing ``harness-run-reliability``'s-#: ``restarted``: that value is reserved for the *service* restarting around a-#: run, which recovery retries, while this one interrupts a live turn inside a-#: healthy process and does not.+#: Spelled ``backend_refresh`` rather than ``restarted`` because it identifies a+#: different infrastructure boundary: a live Agent runtime inside an otherwise+#: healthy service, rather than the service itself shutting down.SETTLED_BY_BACKEND_REFRESH: Final = "backend_refresh"+#: The scheduled service shut down while its exact claimed request was executing.+#: The interrupted attempt is terminal; a later process must not replay it.+SETTLED_BY_RESTARTED: Final = "restarted"++#: An in-flight claimed request was cancelled without a more specific teardown+#: cause. This is still an infrastructure interruption, never a requeue signal.+SETTLED_BY_INTERRUPTED: Final = "interrupted"+#: Settlements that mean "no terminal result will ever arrive for this run" — the#: ONLY ones a caller may terminalize a row from. Both settlement lanes test#: membership here rather than excluding ``SETTLED_BY_TERMINAL_RESULT``, so a new@@ -75,6 +82,8 @@ SETTLEMENTS_WITHOUT_RESULT: Final = frozenset(SETTLED_BY_STOPPED,SETTLED_BY_REFUSED_CONCURRENT_TURN,SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_RESTARTED,+ SETTLED_BY_INTERRUPTED,})@@ -88,12 +97,13 @@ INTERRUPT_REASON_NO_TERMINAL_RESULT: Final = SETTLED_BY_NO_TERMINAL_RESULTINTERRUPT_REASON_STOPPED: Final = SETTLED_BY_STOPPEDINTERRUPT_REASON_REFUSED_CONCURRENT_TURN: Final = SETTLED_BY_REFUSED_CONCURRENT_TURNINTERRUPT_REASON_BACKEND_REFRESH: Final = SETTLED_BY_BACKEND_REFRESH+INTERRUPT_REASON_RESTARTED: Final = SETTLED_BY_RESTARTED+INTERRUPT_REASON_INTERRUPTED: Final = SETTLED_BY_INTERRUPTED#: Reserved for ``docs/plans/harness-run-reliability.md`` (PR2 / PR4 / PR7). Named#: here now because the classification below has to be closed over them before#: they are written, or each PR would have to remember to widen it.INTERRUPT_REASON_EVICTED: Final = "evicted"-INTERRUPT_REASON_RESTARTED: Final = "restarted"INTERRUPT_REASON_LIFETIME_TIMEOUT: Final = "lifetime_timeout"#: The run could not be dispatched at all because the session it delivers to no@@ -171,6 +181,7 @@ RUN_INTERRUPTION_REASONS: Final = frozenset({SETTLED_BY_STOPPED,SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_INTERRUPTED,INTERRUPT_REASON_EVICTED,INTERRUPT_REASON_RESTARTED,INTERRUPT_REASON_LIFETIME_TIMEOUT,@@ -193,6 +204,8 @@ SETTLEMENT_I18N_KEYS: Final = {SETTLED_BY_STOPPED: "harness.run.interrupted.stopped",SETTLED_BY_REFUSED_CONCURRENT_TURN: "harness.run.interrupted.refusedConcurrentTurn",SETTLED_BY_BACKEND_REFRESH: "harness.run.interrupted.backendRefresh",+ SETTLED_BY_RESTARTED: "harness.run.interrupted.restarted",+ SETTLED_BY_INTERRUPTED: "harness.run.interrupted.interrupted",}@@ -214,6 +227,291 @@ SETTLEMENT_TERMINAL_STATUS: Final = {SETTLED_BY_STOPPED: "canceled",SETTLED_BY_REFUSED_CONCURRENT_TURN: "failed",SETTLED_BY_BACKEND_REFRESH: "failed",+ SETTLED_BY_RESTARTED: "failed",+ SETTLED_BY_INTERRUPTED: "failed",+}++def covered(test_node: str) -> tuple[str, str]:+ """Declare the consuming test that proves one teardown matrix cell."""++ return "covered", test_node+++def not_applicable(reason: str) -> tuple[str, str]:+ """Declare why an entry point cannot own one teardown matrix surface."""++ return "N/A", reason+++TEARDOWN_SETTLEMENT_ENTRY_POINTS: Final = (+ "direct_executor_cancellation",+ "graceful_service_stop",+ "service_lease_loss",+ "startup_recovery",+ "user_stop_racing_teardown",+ "running_agents_end",+ "idle_stuck_eviction",+ "backend_refresh",+ "backend_runtime_cleanup",+ "orphan_sweep",+ "workbench_control_archive",+ "watch_service_teardown",+)++TEARDOWN_SETTLEMENT_SURFACES: Final = (+ "run_row",+ "definition_projection",+ "durable_turn",+ "delivery_binding",+ "session_projection_and_queue",+ "scheduler_runtime_ownership",+ "backend_runtime",+ "callback_and_failure_notice",+ "restart_recovery",+ "runtime_registries",+)++_HFR_082 = (+ "tests/test_harness_failure_visibility.py::"+ "test_an_interruption_keeps_an_identity_distinct_from_an_ordinary_failure"+)+_HFR_100 = (+ "tests/test_scheduled_tasks.py::"+ "test_direct_inflight_cancellation_terminalizes_the_exact_run"+)+_HFR_101 = (+ "tests/test_scheduled_tasks.py::"+ "test_service_stop_terminalizes_inflight_run_without_replay"+)+_HFR_102 = (+ "tests/test_scheduled_tasks.py::"+ "test_canceled_task_execution_projects_every_result_and_only_retires_scheduler_one_shots"+)+_HFR_102_CAS = (+ "tests/test_scheduled_tasks.py::"+ "test_task_definition_projection_follows_the_exact_terminal_cas_winner"+)+_HFR_103 = (+ "tests/test_scheduled_tasks.py::"+ "test_service_teardown_terminalizes_transferred_durable_turn_without_draining_held_queue"+)+_HFR_104 = (+ "tests/test_scheduled_tasks.py::"+ "test_restart_recovery_terminalizes_started_rows_and_preserves_other_owners"+)+_HFR_106 = (+ "tests/test_scheduled_tasks.py::"+ "test_service_stop_preserves_non_durable_user_stop_cause"+)+_CANCELED_NOTICE = (+ "tests/test_harness_failure_visibility.py::"+ "test_a_succeeded_or_canceled_transition_owes_no_notice"+)+_RESTART_TURN = (+ "tests/test_session_delivery_fsm.py::"+ "test_restart_settles_agent_run_after_late_acceptance_commit"+)+_END_TURN = (+ "tests/test_running_agents_service.py::test_end_active_workbench_turn_settles_via_manager"+)+_END_RUN = (+ "tests/test_running_agents_service.py::"+ "test_end_active_agent_run_binds_stop_context_to_matching_turn_sink"+)+_END_RUNTIME = (+ "tests/test_running_agents_service.py::test_end_active_codex_frees_runtime_after_stop"+)+_EVICT_CODEX = (+ "tests/test_codex_agent.py::CodexAgentStopTests::"+ "test_evict_idle_transports_force_evicts_stuck_active_transport"+)+_EVICT_CLAUDE = (+ "tests/test_claude_agent_sessions.py::ClaudeAgentSessionTests::"+ "test_force_cleanup_stuck_active_session_retires_pending_turn"+)+_TURN_WITHOUT_RESULT = (+ "tests/test_scheduled_tasks.py::"+ "test_workbench_turn_settles_its_agent_run_when_no_result_arrives"+)+_REFRESH_RUN = (+ "tests/test_scheduled_tasks.py::"+ "test_backend_refresh_settles_its_run_as_a_refresh_not_a_user_stop"+)+_REFRESH_TURN = (+ "tests/test_internal_server.py::test_release_for_backend_refresh_cancels_matching_turn_and_sets_idle"+)+_EOF_TURN = (+ "tests/test_claude_agent_sessions.py::ClaudeAgentSessionTests::"+ "test_handle_message_receiver_eof_without_result_settles_current_turn"+)+_EOF_RUNTIME = (+ "tests/test_claude_agent_sessions.py::ClaudeAgentSessionTests::"+ "test_receiver_eof_cleans_runtime_before_terminal_emit_releases_gate"+)+_SWEEP_RUN = "tests/test_scheduled_tasks.py::test_sweep_terminalizes_orphaned_running_run"+_SWEEP_TURN = (+ "tests/test_session_delivery_fsm.py::"+ "test_owned_run_sweep_retries_terminal_turn_settlement_before_orphaning"+)+_SEND_NOW = (+ "tests/test_internal_server.py::"+ "test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head"+)+_SEND_NOW_RESTART = (+ "tests/test_internal_server.py::"+ "test_agent_run_send_now_restart_preserves_refused_queue_behind_durable_owner"+)+_WATCH_STOP = "tests/test_watches.py::test_managed_watch_service_stop_terminates_running_waiter"++#: Entry point x surface closure for teardown settlement. This is evidence+#: metadata, never a lifecycle writer. Every row spells all surfaces explicitly:+#: adding either dimension makes HFR-105 fail until the new cells name a consuming+#: test or a precise ownership reason.+TEARDOWN_SETTLEMENT_MATRIX: Final = {+ "direct_executor_cancellation": {+ "run_row": covered(_HFR_102_CAS),+ "definition_projection": covered(_HFR_102_CAS),+ "durable_turn": not_applicable("ownership already transferred to SessionTurnManager"),+ "delivery_binding": not_applicable("no durable Delivery on the drain-owned lane"),+ "session_projection_and_queue": not_applicable("no durable Session owner on this lane"),+ "scheduler_runtime_ownership": covered(_HFR_102_CAS),+ "backend_runtime": not_applicable("executor cancellation does not dismantle a backend runtime"),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": not_applicable("the process remains live"),+ "runtime_registries": covered(_HFR_100),+ },+ "graceful_service_stop": {+ "run_row": covered(_HFR_102_CAS),+ "definition_projection": covered(_HFR_102_CAS),+ "durable_turn": covered(_HFR_103),+ "delivery_binding": covered(_HFR_103),+ "session_projection_and_queue": covered(_HFR_103),+ "scheduler_runtime_ownership": covered(_HFR_102_CAS),+ "backend_runtime": not_applicable("controller backend cleanup is a later entry point"),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": covered(_HFR_101),+ "runtime_registries": covered(_HFR_103),+ },+ "service_lease_loss": {+ "run_row": covered(_HFR_102_CAS),+ "definition_projection": covered(_HFR_102_CAS),+ "durable_turn": covered(_HFR_103),+ "delivery_binding": covered(_HFR_103),+ "session_projection_and_queue": covered(_HFR_103),+ "scheduler_runtime_ownership": covered(_HFR_102_CAS),+ "backend_runtime": not_applicable("the scheduler lease does not own backend processes"),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": not_applicable("lease loss settles while the process is live"),+ "runtime_registries": covered(_HFR_103),+ },+ "startup_recovery": {+ "run_row": covered(_HFR_104),+ "definition_projection": covered(_HFR_104),+ "durable_turn": covered(_RESTART_TURN),+ "delivery_binding": covered(_RESTART_TURN),+ "session_projection_and_queue": covered(_RESTART_TURN),+ "scheduler_runtime_ownership": covered(_HFR_104),+ "backend_runtime": not_applicable("the previous backend process is already gone"),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": covered(_HFR_104),+ "runtime_registries": covered(_HFR_104),+ },+ "user_stop_racing_teardown": {+ "run_row": covered(_HFR_106),+ "definition_projection": covered(_HFR_106),+ "durable_turn": covered(_HFR_103),+ "delivery_binding": covered(_HFR_103),+ "session_projection_and_queue": covered(_HFR_103),+ "scheduler_runtime_ownership": covered(_HFR_106),+ "backend_runtime": not_applicable("Stop precedence does not choose backend cleanup"),+ "callback_and_failure_notice": covered(_CANCELED_NOTICE),+ "restart_recovery": covered(_HFR_104),+ "runtime_registries": covered(_HFR_103),+ },+ "running_agents_end": {+ "run_row": covered(_END_RUN),+ "definition_projection": covered(_HFR_103),+ "durable_turn": covered(_END_TURN),+ "delivery_binding": covered(_END_RUN),+ "session_projection_and_queue": covered(_END_TURN),+ "scheduler_runtime_ownership": not_applicable("End does not stop the scheduler"),+ "backend_runtime": covered(_END_RUNTIME),+ "callback_and_failure_notice": covered(_CANCELED_NOTICE),+ "restart_recovery": not_applicable("End is a live user action"),+ "runtime_registries": covered(_END_RUNTIME),+ },+ "idle_stuck_eviction": {+ "run_row": covered(_TURN_WITHOUT_RESULT),+ "definition_projection": covered(_HFR_103),+ "durable_turn": covered(_EVICT_CLAUDE),+ "delivery_binding": covered(_TURN_WITHOUT_RESULT),+ "session_projection_and_queue": covered(_TURN_WITHOUT_RESULT),+ "scheduler_runtime_ownership": not_applicable("runtime eviction does not stop the scheduler"),+ "backend_runtime": covered(_EVICT_CODEX),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": not_applicable("eviction settles while the process is live"),+ "runtime_registries": covered(_EVICT_CODEX),+ },+ "backend_refresh": {+ "run_row": covered(_REFRESH_RUN),+ "definition_projection": covered(_HFR_103),+ "durable_turn": covered(_REFRESH_TURN),+ "delivery_binding": covered(_REFRESH_TURN),+ "session_projection_and_queue": covered(_REFRESH_TURN),+ "scheduler_runtime_ownership": covered(_HFR_102),+ "backend_runtime": covered(_REFRESH_TURN),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": not_applicable("rolling refresh has a live Turn owner"),+ "runtime_registries": covered(_REFRESH_TURN),+ },+ "backend_runtime_cleanup": {+ "run_row": covered(_EOF_TURN),+ "definition_projection": covered(_HFR_103),+ "durable_turn": covered(_EOF_TURN),+ "delivery_binding": covered(_TURN_WITHOUT_RESULT),+ "session_projection_and_queue": covered(_TURN_WITHOUT_RESULT),+ "scheduler_runtime_ownership": not_applicable("backend cleanup does not stop the scheduler"),+ "backend_runtime": covered(_EOF_RUNTIME),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": not_applicable("runtime EOF is settled by the live terminal boundary"),+ "runtime_registries": covered(_EOF_RUNTIME),+ },+ "orphan_sweep": {+ "run_row": covered(_SWEEP_RUN),+ "definition_projection": not_applicable("the sweep excludes scheduled and watch Run rows"),+ "durable_turn": covered(_SWEEP_TURN),+ "delivery_binding": covered(_SWEEP_TURN),+ "session_projection_and_queue": not_applicable("live Session owners are sweep exemptions"),+ "scheduler_runtime_ownership": not_applicable("the sweep never owns scheduler jobs"),+ "backend_runtime": not_applicable("the sweep observes vanished owners only"),+ "callback_and_failure_notice": covered(_HFR_082),+ "restart_recovery": not_applicable("the sweep is a live fallback, not startup recovery"),+ "runtime_registries": covered(_SWEEP_TURN),+ },+ "workbench_control_archive": {+ "run_row": covered(_SEND_NOW),+ "definition_projection": covered(_HFR_103),+ "durable_turn": covered(_SEND_NOW),+ "delivery_binding": covered(_SEND_NOW),+ "session_projection_and_queue": covered(_SEND_NOW),+ "scheduler_runtime_ownership": not_applicable("Workbench control does not stop the scheduler"),+ "backend_runtime": not_applicable("replacement reuses the existing backend runtime"),+ "callback_and_failure_notice": covered(_CANCELED_NOTICE),+ "restart_recovery": covered(_SEND_NOW_RESTART),+ "runtime_registries": covered(_SEND_NOW),+ },+ "watch_service_teardown": {+ "run_row": not_applicable("enqueued work transfers to ScheduledTaskService or Delivery"),+ "definition_projection": not_applicable("Watch service owns waiter state, not fire results"),+ "durable_turn": not_applicable("accepted Turns are already owned by SessionTurnManager"),+ "delivery_binding": not_applicable("accepted Deliveries are already owned by SessionTurnManager"),+ "session_projection_and_queue": not_applicable("Watch service cannot drain Session queues"),+ "scheduler_runtime_ownership": not_applicable("Watch service has its own waiter scheduler"),+ "backend_runtime": not_applicable("Watch service never owns an agent backend process"),+ "callback_and_failure_notice": not_applicable("terminal Run projection begins after enqueue"),+ "restart_recovery": not_applicable("watch_runtime rows are explicit recovery exemptions"),+ "runtime_registries": covered(_WATCH_STOP),+ },}diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex ec266d8c3..4be29e76f 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import osimport tempfileimport timefrom dataclasses import asdict, dataclass, field@@ -41,7 +42,10 @@ from core.run_settlement import (INTERRUPT_REASON_DELIVERY_TARGET_MISSING,RUN_INTERRUPTION_REASONS,SETTLEMENTS_WITHOUT_RESULT,+ SETTLED_BY_INTERRUPTED,SETTLED_BY_NO_TERMINAL_RESULT,+ SETTLED_BY_RESTARTED,+ SETTLED_BY_STOPPED,SETTLEMENT_I18N_KEYS,SETTLEMENT_TERMINAL_STATUS,SWEEP_I18N_KEYS,@@ -1474,11 +1478,24 @@ class ScheduledTaskStore:task.updated_at = _utc_now_iso()return self._write_task(task, expect)- def mark_task_result(self, task_id: str, *, error: Optional[str], disable_one_shot: bool = True) -> bool:+ def mark_task_result(+ self,+ task_id: str,+ *,+ error: Optional[str],+ disable_one_shot: bool = True,+ expected_binding: Optional[tuple[Optional[str], str, str]] = None,+ ) -> bool:self.maybe_reload()task = self._tasks.get(task_id)if task is None:return False+ if expected_binding is not None and (+ task.session_id,+ task.session_key,+ task.schedule_type,+ ) != expected_binding:+ return Falseexpect = self._read_state(task)task.last_run_at = _utc_now_iso()task.last_error = error@@ -1547,9 +1564,27 @@ class TaskExecutionStore:}[state]return directory / f"{request_id}.json"- def recover_processing(self) -> None:+ def recover_processing(+ self,+ *,+ interruption_error: Optional[str] = None,+ interrupt_reason: str = SETTLED_BY_RESTARTED,+ cancellation_error: Optional[str] = None,+ ) -> None:+ interruption_error = interruption_error or i18n_t(+ SETTLEMENT_I18N_KEYS[interrupt_reason],+ "en",+ )+ cancellation_error = cancellation_error or i18n_t(+ SETTLEMENT_I18N_KEYS[SETTLED_BY_STOPPED],+ "en",+ )if self._sqlite is not None:- self._sqlite.recover_processing_runs()+ self._sqlite.recover_processing_runs(+ interruption_error=interruption_error,+ interrupt_reason=interrupt_reason,+ cancellation_error=cancellation_error,+ )returnself._ensure_dirs()for path in self.processing_dir.glob("*.json"):@@ -1561,7 +1596,74 @@ class TaskExecutionStore:if completed_path.exists():path.unlink(missing_ok=True)continue- path.replace(pending_path)+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ payload = {}+ if not isinstance(payload, dict) or not payload.get("pid"):+ path.replace(pending_path)+ continue+ now = _utc_now_iso()+ metadata = payload.get("metadata")+ canceled = bool(payload.get("cancel_requested"))+ effective_error = cancellation_error if canceled else interruption_error+ effective_reason = SETTLED_BY_STOPPED if canceled else interrupt_reason+ payload.update(+ {+ "status": "canceled" if canceled else "failed",+ "ok": False,+ "error": effective_error,+ "completed_at": now,+ "updated_at": now,+ "metadata": {+ **(metadata if isinstance(metadata, dict) else {}),+ "interrupt_reason": effective_reason,+ },+ }+ )+ with tempfile.NamedTemporaryFile(+ mode="w",+ dir=self.completed_dir,+ suffix=".tmp",+ delete=False,+ encoding="utf-8",+ ) as handle:+ json.dump(payload, handle, indent=2)+ tmp_path = Path(handle.name)+ tmp_path.replace(completed_path)+ path.unlink(missing_ok=True)++ def mark_execution_started(self, request_id: str) -> bool:+ """Persist the boundary between a bare claim and executing its coroutine."""++ now = _utc_now_iso()+ if self._sqlite is not None:+ return self._sqlite.mark_run_execution_started(+ request_id,+ pid=os.getpid(),+ updated_at=now,+ )+ processing_path = self._request_path(request_id, state="processing")+ if not processing_path.exists():+ return False+ try:+ payload = json.loads(processing_path.read_text(encoding="utf-8"))+ except Exception:+ return False+ if not isinstance(payload, dict):+ return False+ payload.update({"pid": os.getpid(), "started_at": now, "updated_at": now})+ with tempfile.NamedTemporaryFile(+ mode="w",+ dir=self.processing_dir,+ suffix=".tmp",+ delete=False,+ encoding="utf-8",+ ) as handle:+ json.dump(payload, handle, indent=2)+ tmp_path = Path(handle.name)+ tmp_path.replace(processing_path)+ return True@staticmethoddef queued_run_payload(request: TaskExecutionRequest) -> dict[str, Any]:@@ -2358,10 +2460,11 @@ class TaskExecutionStore:def requeue(self, request_id: str, *, metadata: Optional[dict[str, Any]] = None) -> None:if self._sqlite is not None:- if metadata is not None:- self._sqlite.mark_run_queued_from_running(request_id, updated_at=_utc_now_iso(), metadata=metadata)- else:- self._sqlite.update_run_status(request_id, status="queued", updated_at=_utc_now_iso())+ self._sqlite.mark_run_queued_from_running(+ request_id,+ updated_at=_utc_now_iso(),+ metadata=metadata,+ )returnprocessing_path = self._request_path(request_id, state="processing")pending_path = self._request_path(request_id, state="pending")@@ -2383,11 +2486,11 @@ class TaskExecutionStore:session_id: Optional[str] = None,interrupt_reason: Optional[str] = None,failure_code: Optional[str] = None,- ) -> None:+ ) -> Optional[str]:"""Settle one claimed request.``interrupt_reason`` is the caller's structured CLASS for a failure that has- one — today only ``delivery_target_missing`` (see ``_execute_claimed_request``).+ one, such as ``delivery_target_missing`` or an infrastructure teardown cause.It rides the SAME statement as the terminal transition, because that statementis also the one that stamps the owed failure notice: ``_merge_owed_failure_notice``applies ``extra_metadata`` to the run's ``metadata_json`` BEFORE@@ -2401,6 +2504,9 @@ class TaskExecutionStore:arguments are merged verbatim into a run's metadata, and a wide-openpassthrough at a completion site is how an unrelated key comes to overwrite``interrupt_reason``, ``failure_code`` or the notice blob itself.++ Returns the exact terminal status this call wrote, or ``None`` when another+ terminal owner already won."""extra_metadata: dict[str, Any] = {"ok": ok}@@ -2415,7 +2521,7 @@ class TaskExecutionStore:# whenever the claimed-request layer finished with an error. The identity# columns are still written either way (see ``settle_run_terminal``), so# routing through the guard costs nothing a caller depended on.- self._sqlite.settle_run_terminal(+ return self._sqlite.settle_run_terminal(request.id,terminal_status="succeeded" if ok else "failed",error=error,@@ -2425,9 +2531,11 @@ class TaskExecutionStore:session_id=session_id if session_id is not None else request.session_id,metadata=extra_metadata,)- returnprocessing_path = self._request_path(request.id, state="processing")completed_path = self._request_path(request.id, state="completed")+ if not processing_path.exists():+ return None+ terminal_status = "succeeded" if ok else "failed"payload = request.to_dict()payload.update({@@ -2462,6 +2570,7 @@ class TaskExecutionStore:tmp_path = Path(handle.name)tmp_path.replace(completed_path)processing_path.unlink(missing_ok=True)+ return terminal_statusdef settle_turn_participants(self,@@ -2508,6 +2617,7 @@ class ScheduledTaskService:self.request_store = request_store or TaskExecutionStore()self.scheduler = AsyncIOScheduler(timezone="UTC")self._reconcile_task: Optional[asyncio.Task] = None+ self._service_teardown_task: Optional["asyncio.Task[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.@@ -2518,6 +2628,13 @@ 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]"] = {}+ # The exact claims behind those tasks. The done callback uses this as a+ # terminalization backstop when asyncio cancels a task before its coroutine+ # executes even one line.+ self._inflight_requests: Dict[str, TaskExecutionRequest] = {}+ # request id -> infrastructure cause chosen before cancellation. A raw+ # cancellation falls back to ``interrupted`` in the execution wrapper.+ self._inflight_cancellation_causes: Dict[str, str] = {}# Canonical conversation keys with an execution in flight. Used to# serialize turns per session (never two at once for the same# conversation) while still running different sessions concurrently.@@ -2538,7 +2655,10 @@ class ScheduledTaskService:self._requires_service_lease = runtime.service_instance_lock_attached_to_process()self._drain_dirty = Trueself._recover_activity_lifecycle()- self.request_store.recover_processing()+ self.request_store.recover_processing(+ interruption_error=self._t(SETTLEMENT_I18N_KEYS[SETTLED_BY_RESTARTED]),+ cancellation_error=self._t(SETTLEMENT_I18N_KEYS[SETTLED_BY_STOPPED]),+ )def _t(self, key: str, **kwargs: Any) -> str:"""Translate a user-visible string in the configured language.@@ -2552,6 +2672,12 @@ class ScheduledTaskService:lang = str(getattr(config, "language", "en") or "en")return i18n_t(key, lang, **kwargs)+ def _execution_interruption(self, execution_id: str) -> str:+ return self._inflight_cancellation_causes.get(+ execution_id,+ SETTLED_BY_INTERRUPTED,+ )+@staticmethoddef _activity_run_ids(activity: Any) -> list[str]:run_ids: list[str] = []@@ -2794,6 +2920,43 @@ class ScheduledTaskService:except RuntimeError:return None+ async def _settle_service_teardown_owners(self) -> None:+ manager = getattr(self.controller, "session_turns", None)+ release_durable = getattr(manager, "release_for_service_shutdown", None)+ if not callable(release_durable):+ return+ try:+ await release_durable()+ except Exception:+ logger.exception(+ "Failed to settle durable Session Turns during service shutdown",+ )++ def _ensure_service_teardown_task(self) -> Optional["asyncio.Task[None]"]:+ if self._service_teardown_task is not None:+ return self._service_teardown_task+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return None+ self._service_teardown_task = loop.create_task(+ self._settle_service_teardown_owners()+ )+ return self._service_teardown_task++ def _shutdown_interruption_for(self, request_id: str) -> str:+ try:+ run = self.request_store.get_run(request_id)+ except Exception:+ logger.exception(+ "Failed to read Run %s before service shutdown cancellation",+ request_id,+ )+ return SETTLED_BY_RESTARTED+ if run is not None and bool(run.get("cancel_requested")):+ return SETTLED_BY_STOPPED+ return SETTLED_BY_RESTARTED+def _begin_stop(self, *, cancel_reconcile: bool = True) -> None:self._running = Falsecurrent_task = self._current_asyncio_task()@@ -2805,13 +2968,17 @@ class ScheduledTaskService:# outlives shutdown. The identity check is the only exemption it needs.if self._notice_drain_task and self._notice_drain_task is not current_task:self._notice_drain_task.cancel()- for task in list(self._inflight_executions.values()):+ for request_id, task in list(self._inflight_executions.items()):if task is not current_task:+ self._inflight_cancellation_causes[request_id] = (+ self._shutdown_interruption_for(request_id)+ )task.cancel()try:self.scheduler.shutdown(wait=False)except Exception:logger.debug("Failed to shut down scheduler", exc_info=True)+ self._ensure_service_teardown_task()def _owns_service_instance(self) -> bool:if not self._requires_service_lease:@@ -2842,17 +3009,21 @@ class ScheduledTaskService:except (asyncio.CancelledError, Exception):passself._notice_drain_task = None- # Cancel any in-flight executions so shutdown is clean. Cancellation is- # caught by ``_execute_claimed_request``, which requeues the run, so it- # is picked up again on the next start (and ``recover_processing`` on- # init backstops anything left ``running`` after a hard crash).+ # Await each exact in-flight execution so its guarded terminal write lands+ # before shutdown returns. Queued requests were never claimed and remain+ # queued for the next start.inflight = list(self._inflight_executions.values())for task in inflight:try:await taskexcept (asyncio.CancelledError, Exception):pass+ teardown = self._ensure_service_teardown_task()+ if teardown is not None:+ await teardownself._inflight_executions.clear()+ self._inflight_requests.clear()+ self._inflight_cancellation_causes.clear()self._inflight_sessions.clear()self._session_lock_owners.clear()@@ -4861,6 +5032,7 @@ class ScheduledTaskService:self._session_lock_owners[lock_key] = request.idtask = asyncio.create_task(self._execute_claimed_request(request))self._inflight_executions[request.id] = task+ self._inflight_requests[request.id] = requesttask.add_done_callback(lambda finished, rid=request.id, key=lock_key: self._on_execution_done(rid, key, finished))@@ -4869,6 +5041,11 @@ class ScheduledTaskService:self, request_id: str, lock_key: Optional[str], task: "asyncio.Task[Any]") -> None:self._inflight_executions.pop(request_id, None)+ request = self._inflight_requests.pop(request_id, None)+ interruption = self._inflight_cancellation_causes.pop(+ request_id,+ SETTLED_BY_INTERRUPTED,+ )if lock_key is not None:self._inflight_sessions.discard(lock_key)# Only if it is still OURS: a later execution may already have taken the@@ -4877,15 +5054,52 @@ class ScheduledTaskService:if self._session_lock_owners.get(lock_key) == request_id:self._session_lock_owners.pop(lock_key, None)self._drain_dirty = True- # ``_execute_claimed_request`` already records failures and requeues on- # cancellation; this only surfaces unexpected crashes in the wrapper.+ # ``_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.if task.cancelled():+ if request is not None:+ try:+ current = self.request_store.get_run(request.id)+ if not current or current.get("status") in TERMINAL_RUN_STATUSES:+ return+ if (+ current.get("pid") is None+ ):+ self.request_store.requeue(request.id)+ return+ written_status = self.request_store.complete(+ request,+ ok=False,+ error=self._t(SETTLEMENT_I18N_KEYS[interruption]),+ interrupt_reason=interruption,+ )+ if written_status is not None and request.task_id and request.request_type in {+ "task_run",+ "scheduled",+ }:+ self._project_terminal_definition_result(+ self.request_store.get_run(request.id),+ execution_id=request.id,+ expected_status=written_status,+ )+ self.reconcile_jobs()+ except Exception:+ logger.exception(+ "Failed to terminalize canceled claimed request %s",+ request_id,+ )returnexc = task.exception()if exc is not None:logger.error("Claimed request %s crashed: %r", request_id, exc, exc_info=exc)async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:+ if not self.request_store.mark_execution_started(request.id):+ # A terminal result or explicit cancellation won after claim but before+ # this coroutine entered. Do not dispatch work whose Run no longer owns+ # the execution boundary.+ returnrequest = self.request_store.refresh_claimed_request(request)error: Optional[str] = None#: The structured CLASS of this run's failure, when the failure has one. Kept@@ -4897,6 +5111,7 @@ class ScheduledTaskService:settled_out_of_band = Falserecover_queue_on_return = Falsereconcile_delivery_on_return = False+ project_terminal_definition_on_cancel = Falsetask_id = request.task_idsession_key = request.session_keysession_id = request.session_id@@ -4999,8 +5214,15 @@ class ScheduledTaskService:else:raise ValueError(f"unknown task request type: {request.request_type}")except asyncio.CancelledError:- self.request_store.requeue(request.id)- should_complete = False+ interrupt_reason = self._execution_interruption(request.id)+ error = self._t(SETTLEMENT_I18N_KEYS[interrupt_reason])+ should_complete = True+ settled_out_of_band = False+ recover_queue_on_return = False+ project_terminal_definition_on_cancel = request.request_type in {+ "task_run",+ "scheduled",+ }raiseexcept UnresolvableSessionTarget as exc:# THE RUN'S DELIVERY TARGET IS GONE, and that is a CLASS of failure rather@@ -5057,7 +5279,7 @@ class ScheduledTaskService:settled_out_of_band = Falsefinally:if should_complete:- self.request_store.complete(+ written_status = self.request_store.complete(request,ok=not error,error=error,@@ -5067,6 +5289,13 @@ class ScheduledTaskService:interrupt_reason=interrupt_reason,failure_code=failure_code,)+ if project_terminal_definition_on_cancel and written_status is not None:+ self._project_terminal_definition_result(+ self.request_store.get_run(request.id),+ execution_id=request.id,+ expected_status=written_status,+ )+ self.reconcile_jobs()if reconcile_delivery_on_return and session_id:manager = getattr(self.controller, "session_turns", None)reconcile_delivery = getattr(@@ -5095,6 +5324,7 @@ class ScheduledTaskService:or settled_out_of_bandor recover_queue_on_return)+ and interrupt_reason is None):manager = getattr(self.controller, "session_turns", None)recover_queue = getattr(@@ -5160,9 +5390,6 @@ class ScheduledTaskService:complete_on_return = dispatch_result.complete_on_returnelse:error = dispatch_result- except asyncio.CancelledError:- self.reconcile_jobs()- raiseexcept UnresolvableSessionTarget as exc:# The pinned session no longer resolves. Left alone this definition# re-fires and re-fails on every schedule with nobody told, so classify@@ -5203,9 +5430,6 @@ class ScheduledTaskService:complete_on_return = dispatch_result.complete_on_returnelse:error = dispatch_result- except asyncio.CancelledError:- self.reconcile_jobs()- raiseexcept Exception as retry_exc:error = str(retry_exc)logger.error(@@ -5439,7 +5663,12 @@ class ScheduledTaskService:error_text = self._t(SETTLEMENT_I18N_KEYS.get(settled_by, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT]))- if not self._settle_agent_run_without_result(execution_id, settled_by=settled_by, error=error_text):+ supported, _settled = self._settle_agent_run_without_result(+ execution_id,+ settled_by=settled_by,+ error=error_text,+ )+ if not supported:# Legacy file store: no guarded writer exists, so fall back to the# ``finally`` completion path rather than leave the run open.return AgentRunExecutionResult(error=error_text, complete_on_return=True)@@ -5475,10 +5704,19 @@ class ScheduledTaskService:execution_id = str(raw_execution_id or "").strip()if not execution_id:continue- if self._settle_agent_run_without_result(- execution_id, settled_by=settled_by, error=error_text- ):- settled_any = True+ _supported, settled = self._settle_agent_run_without_result(+ execution_id,+ settled_by=settled_by,+ error=error_text,+ )+ if settled is None:+ continue+ settled_any = True+ self._project_terminal_definition_result(+ self.request_store.get_run(execution_id),+ execution_id=execution_id,+ expected_status=settled,+ )if settled_any:self._drain_dirty = True@@ -5575,13 +5813,110 @@ class ScheduledTaskService:if settled_any:self._drain_dirty = True+ def _project_terminal_definition_result(+ self,+ run: Optional[dict[str, Any]],+ *,+ execution_id: str,+ expected_status: str,+ ) -> None:+ """Project only the exact terminal transition the caller actually won."""++ if run is None:+ return+ status = str(run.get("status") or "").strip()+ if status != expected_status or status not in TERMINAL_RUN_STATUSES:+ return+ definition_id = str(+ run.get("definition_id") or run.get("task_id") or ""+ ).strip()+ if not definition_id:+ return+ self.store.maybe_reload()+ task = self.store.get_task(definition_id)+ if task is None:+ return+ run_session_id = str(run.get("session_id") or "").strip()+ task_session_id = str(task.session_id or "").strip()+ run_session_key = str(+ run.get("legacy_session_key") or run.get("session_key") or ""+ ).strip()+ task_session_key = str(task.session_key or "").strip()+ if (+ run_session_id != task_session_id+ or run_session_key != task_session_key+ ):+ logger.warning(+ "Run %s no longer matches scheduled definition %s; skipping result projection",+ execution_id,+ definition_id,+ )+ return+ error = None if status == "succeeded" else str(run.get("error") or "").strip()+ if status != "succeeded" and not error:+ metadata = run.get("metadata")+ interruption = (+ str(metadata.get("interrupt_reason") or "").strip()+ if isinstance(metadata, dict)+ else ""+ )+ key = SETTLEMENT_I18N_KEYS.get(interruption)+ if key is not None:+ error = self._t(key)+ if status != "succeeded" and not error:+ logger.warning(+ "Terminal Run %s has no failure detail; skipping definition %s projection",+ execution_id,+ definition_id,+ )+ return+ retire_one_shot = (+ str(run.get("source_kind") or "") == "scheduler"+ and task.schedule_type == "at"+ )+ try:+ recorded = self.store.mark_task_result(+ task.id,+ error=error,+ disable_one_shot=retire_one_shot,+ expected_binding=(+ task.session_id,+ task.session_key,+ task.schedule_type,+ ),+ )+ except Exception:+ logger.exception(+ "Failed to project terminal Run %s to definition %s",+ execution_id,+ definition_id,+ )+ return+ if not recorded:+ logger.warning(+ "Definition %s changed before terminal Run %s could be projected",+ definition_id,+ execution_id,+ )+ return+ if retire_one_shot:+ try:+ if self.scheduler.get_job(task.id) is not None:+ self.scheduler.remove_job(task.id)+ self._job_signatures.pop(task.id, None)+ except Exception:+ logger.exception(+ "Failed to retire scheduler job for terminal definition %s",+ definition_id,+ )+def _settle_agent_run_without_result(self,execution_id: str,*,settled_by: str,error: str,- ) -> bool:+ ) -> tuple[bool, Optional[str]]:"""Terminalize a run whose turn ended without a terminal result.Deliberately NOT routed through ``_execute_claimed_request``'s ``finally``:@@ -5593,13 +5928,13 @@ class ScheduledTaskService:The terminal status comes from ``SETTLEMENT_TERMINAL_STATUS``: an explicituser stop is ``canceled``, an infrastructure fault is ``failed``.- Returns ``True`` when this store owns the terminal write (whether or not this- call is the one that performed it — an already-terminal row is settled too),- and ``False`` only when the store has no guarded writer at all.+ Returns whether the guarded writer exists and the status written by this+ exact terminal compare-and-set. An already-terminal row returns a supported+ writer with no status, so callers cannot project a result they did not settle."""if not self.request_store.supports_guarded_settlement():- return False+ return False, Nonesettled = self.request_store.settle_without_result(execution_id,terminal_status=SETTLEMENT_TERMINAL_STATUS.get(settled_by, "failed"),@@ -5619,7 +5954,7 @@ class ScheduledTaskService:settled,settled_by,)- return True+ return True, settled# --- pinned session binding recovery -------------------------------------#diff --git a/core/session_turns.py b/core/session_turns.pyindex dc424e356..15c94fe4b 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -33,6 +33,7 @@ from core.run_settlement import (SETTLED_BY_BACKEND_REFRESH,SETTLED_BY_NO_TERMINAL_RESULT,SETTLED_BY_REFUSED_CONCURRENT_TURN,+ SETTLED_BY_RESTARTED,SETTLED_BY_STOPPED,SETTLED_BY_TERMINAL_RESULT,)@@ -2882,6 +2883,7 @@ class SessionTurnManager:replay_unknown_start: bool = False,abandon_unaccepted_start: bool = False,retire_unwritten_delivery_ids: set[str] | None = None,+ resume_successors: bool = True,) -> dict[str, Any]:if not self._durable_schema_available():return {@@ -3163,7 +3165,7 @@ class SessionTurnManager:)if retired is None:raise RuntimeError("archived P0 successor retirement lost")- else:+ elif resume_successors:started = delivery_store.activate_waiting_successor(conn,turn=successor,@@ -3174,8 +3176,40 @@ class SessionTurnManager:"P0 successor claim lost after terminal proof")claimed_successor = successor_turn_id+ else:+ deferred = self._write_terminal_snapshot(+ conn,+ successor_turn_id,+ outcome="not_written",+ settled_by=settled_by,+ evidence_kind="service_shutdown_deferred_successor",+ evidence={"reason": "service_shutdown"},+ )+ queued = delivery_store.cas_delivery(+ conn,+ successor_delivery_id,+ expected_version=int(successor_delivery["version"]),+ expected_states=("interrupt_waiting",),+ values={+ "state": "queued",+ "priority": "p3",+ "turn_id": None,+ "turn_role": None,+ "turn_position": None,+ },+ history_event={+ "kind": "interrupt_join",+ "turn_id": turn_id,+ "outcome": "service_shutdown_deferred",+ },+ )+ if not deferred.get("changed") or queued is None:+ raise RuntimeError(+ "service shutdown lost its deferred successor"+ )if (claimed_successor is None+ and resume_successorsand replayed_unknown_startand session_status == "active"):@@ -3201,6 +3235,7 @@ class SessionTurnManager:)if (claimed_successor is None+ and resume_successorsand outcome == "completed"and session_status == "active"):@@ -3328,11 +3363,22 @@ class SessionTurnManager:try:if cancelled:+ interruption = settled_by or SETTLED_BY_STOPPEDreturn self._terminalize_durable_turn(turn_id,- "canceled",- settled_by=settled_by or SETTLED_BY_STOPPED,- evidence_kind="runner_release",+ "canceled" if interruption == SETTLED_BY_STOPPED else "failed",+ settled_by=interruption,+ evidence_kind=(+ "service_shutdown"+ if interruption == SETTLED_BY_RESTARTED+ else "runner_release"+ ),+ evidence=(+ {"reason": "scheduled_service_shutdown"}+ if interruption == SETTLED_BY_RESTARTED+ else None+ ),+ resume_successors=interruption != SETTLED_BY_RESTARTED,)if failed:# Dispatch may have written before raising. Preserve starting work@@ -4420,7 +4466,10 @@ class SessionTurnManager:await self._resume_post_terminal(session_id)else:await self.flush_queue(session_id)- elif durable_turn_registered:+ elif (+ durable_turn_registered+ and settled_by != SETTLED_BY_RESTARTED+ ):# Stop may persist the old Turn's terminal snapshot before# releasing this runner. In that ordering the terminal CAS# already activated the linked P0 successor, so this runner@@ -4749,6 +4798,109 @@ class SessionTurnManager:result["owner"] = ownerreturn result+ async def release_for_service_shutdown(self) -> int:+ """Fail exact accepted Run owners without draining replacement work."""++ if not self._durable_schema_available():+ return 0++ def live_owners() -> dict[str, dict[str, Any]]:+ with self._sqlite_engine().connect() as conn:+ rows = conn.execute(+ select(+ session_turn_rows.c.id.label("turn_id"),+ session_turn_rows.c.session_id,+ session_turn_rows.c.control_mode,+ agent_runs.c.cancel_requested,+ )+ .join(+ delivery_rows,+ delivery_rows.c.turn_id == session_turn_rows.c.id,+ )+ .join(+ agent_runs,+ agent_runs.c.delivery_id == delivery_rows.c.id,+ )+ .where(+ session_turn_rows.c.state.in_(+ delivery_store.TURN_OWNER_STATES+ )+ )+ .where(delivery_rows.c.state == "accepted")+ .where(+ agent_runs.c.status.in_(+ ["queued", "pending", "running", "processing"]+ )+ )+ ).mappings()+ owners: dict[str, dict[str, Any]] = {}+ for row in rows:+ turn_id = str(row["turn_id"])+ owner = owners.setdefault(+ turn_id,+ {+ "turn_id": turn_id,+ "session_id": str(row["session_id"]),+ "control_mode": row["control_mode"],+ "cancel_requested": False,+ },+ )+ owner["cancel_requested"] = bool(+ owner["cancel_requested"] or row["cancel_requested"]+ )+ return owners++ owners = live_owners()+ done_tasks: list[asyncio.Task] = []+ for owner in owners.values():+ projected = self.in_flight.get(str(owner["session_id"]))+ if (+ projected is not None+ and projected.logical_turn_id == owner["turn_id"]+ and projected.task.done()+ ):+ done_tasks.append(projected.task)+ if done_tasks:+ await asyncio.gather(*done_tasks, return_exceptions=True)++ owners = live_owners()+ tasks_to_cancel: list[asyncio.Task] = []+ released_sessions: set[str] = set()+ for owner in owners.values():+ session_id = str(owner["session_id"])+ turn_id = str(owner["turn_id"])+ projected = self.in_flight.get(session_id)+ if projected is None or projected.logical_turn_id != turn_id:+ continue+ user_stopped = bool(+ owner["control_mode"] == "stop_only"+ or owner["cancel_requested"]+ or projected.cancel_settled_by == SETTLED_BY_STOPPED+ )+ settled_by = SETTLED_BY_STOPPED if user_stopped else SETTLED_BY_RESTARTED+ terminal = self._terminalize_durable_turn(+ turn_id,+ "canceled" if user_stopped else "failed",+ settled_by=settled_by,+ evidence_kind=(+ "service_shutdown_after_user_stop"+ if user_stopped+ else "service_shutdown"+ ),+ evidence={"reason": "scheduled_service_shutdown"},+ resume_successors=False,+ )+ if terminal.get("changed"):+ released_sessions.add(session_id)+ if not projected.task.done():+ projected.cancel_settled_by = settled_by+ projected.task.cancel()+ tasks_to_cancel.append(projected.task)++ if tasks_to_cancel:+ await asyncio.gather(*tasks_to_cancel, return_exceptions=True)+ return len(released_sessions)+async def release_for_backend_refresh(self,*,@@ -5396,13 +5548,21 @@ class SessionTurnManager:finally:sink = self.get_turn_sink(session_key)settled_by = str((sink or {}).get("settled_by") or "")+ current = self.in_flight.get(session_id)+ turn = (+ current+ if current is not None+ and current.task is asyncio.current_task()+ else None+ )effective_settled_by = (- SETTLED_BY_STOPPED if cancelled else settled_by+ (turn.cancel_settled_by if turn is not None else None)+ or SETTLED_BY_STOPPED+ if cancelled+ else settled_by)terminal_evidence = (sink or {}).get("terminal_evidence")self.pop_turn_sink(session_key, done)- current = self.in_flight.get(session_id)- turn = current if current is not None and current.task is asyncio.current_task() else Noneterminal_is_error = bool(turn is not None and turn.terminal_is_error)@@ -5417,14 +5577,22 @@ class SessionTurnManager:try:durable_terminal_result = self._terminalize_durable_turn(turn_token,- self._durable_terminal_outcome(- is_error=terminal_is_error,- settled_by=effective_settled_by or None,+ (+ "failed"+ if effective_settled_by == SETTLED_BY_RESTARTED+ else self._durable_terminal_outcome(+ is_error=terminal_is_error,+ settled_by=effective_settled_by or None,+ )),settled_by=(effective_settled_by or SETTLED_BY_TERMINAL_RESULT),- evidence_kind="agent_initiated_terminal",+ evidence_kind=(+ "service_shutdown"+ if effective_settled_by == SETTLED_BY_RESTARTED+ else "agent_initiated_terminal"+ ),evidence=(dict(terminal_evidence)if isinstance(terminal_evidence, dict)@@ -5450,7 +5618,10 @@ class SessionTurnManager:await self.flush_queue(session_id)except Exception:logger.debug("agent-initiated turn: queue resume failed", exc_info=True)- elif durable_turn_registered:+ elif (+ durable_turn_registered+ and effective_settled_by != SETTLED_BY_RESTARTED+ ):await self._resume_linked_control_successor(session_id,turn_token,diff --git a/storage/background.py b/storage/background.pyindex 85aa5a25c..7f43457c1 100644--- a/storage/background.py+++ b/storage/background.py@@ -1212,6 +1212,7 @@ RUN_INTERRUPTION_REASONS = frozenset({"stopped","backend_refresh",+ "interrupted","evicted","restarted","lifetime_timeout",@@ -3147,7 +3148,12 @@ class SQLiteBackgroundTaskStore:update(agent_runs).where(agent_runs.c.id == run_id).where(agent_runs.c.status.in_(_status_query_values("queued")))- .values(status="running", started_at=started_at, updated_at=started_at)+ .values(+ status="running",+ started_at=started_at,+ pid=None,+ updated_at=started_at,+ ))if not result.rowcount:return None@@ -3158,6 +3164,36 @@ class SQLiteBackgroundTaskStore:_publish_run_rows_updated([row_to_publish])return payload+ def mark_run_execution_started(+ self,+ run_id: str,+ *,+ pid: int,+ updated_at: Optional[str] = None,+ ) -> bool:+ """Fence startup recovery once the claimed request coroutine has entered."""++ now = updated_at or _utc_now_iso()+ row_to_publish = None+ with self.engine.begin() as conn:+ result = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(agent_runs.c.status.in_(_status_query_values("running")))+ .where(agent_runs.c.pid.is_(None))+ .values(pid=pid, updated_at=now)+ )+ if result.rowcount:+ row_to_publish = dict(+ conn.execute(+ select(agent_runs)+ .where(agent_runs.c.id == run_id)+ .limit(1)+ ).mappings().one()+ )+ _publish_run_rows_updated([row_to_publish])+ return row_to_publish is not None+def update_run_status(self,run_id: str,@@ -3414,6 +3450,7 @@ class SQLiteBackgroundTaskStore:values: dict[str, Any] = {"status": "queued","started_at": None,+ "pid": None,"updated_at": now,}if metadata is not None:@@ -4015,32 +4052,151 @@ class SQLiteBackgroundTaskStore:).mappings().first()return self._run_from_row(row) if row else None- def recover_processing_runs(self) -> None:+ def recover_processing_runs(+ self,+ *,+ interruption_error: str,+ interrupt_reason: str,+ cancellation_error: str,+ ) -> None:with run_update_event_transaction(self.engine) as conn:now = _utc_now_iso()rows = list(conn.execute(- select(agent_runs.c.id, agent_runs.c.result_payload_json)+ select(agent_runs).where(agent_runs.c.status.in_(_status_query_values("running"))).where(agent_runs.c.run_type != "watch_runtime").where(agent_runs.c.delivery_id.is_(None))).mappings())- recovered_ids = []+ requeued_ids: list[str] = []+ terminal_ids: list[str] = []for row in rows:result_payload = _json_loads(row["result_payload_json"], {})if isinstance(result_payload, dict) and result_payload.get("deferred_terminal_status"):continue- recovered_ids.append(str(row["id"]))- if recovered_ids:+ run_id = str(row["id"])+ if row["pid"] is None:+ requeued_ids.append(run_id)+ continue+ status, guards = _cancel_aware_terminal_status(row, "failed")+ effective_error = (+ cancellation_error if status == "canceled" else interruption_error+ )+ effective_reason = (+ "stopped" if status == "canceled" else interrupt_reason+ )+ values: dict[str, Any] = {+ "status": status,+ "completed_at": now,+ "updated_at": now,+ "error": effective_error,+ "pid": None,+ }+ _merge_owed_failure_notice(+ values,+ conn=conn,+ run_id=run_id,+ status=status,+ source_kind=row["source_kind"],+ parent_run_id=row["parent_run_id"],+ row_metadata_json=row["metadata_json"],+ extra_metadata={+ "ok": False,+ "interrupt_reason": effective_reason,+ },+ now=now,+ )+ transition = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(agent_runs.c.pid == row["pid"])+ .where(*guards)+ .values(**values)+ )+ if not transition.rowcount:+ continue+ terminal_ids.append(run_id)++ definition_id = str(row["definition_id"] or "").strip()+ if not definition_id:+ continue+ definition = conn.execute(+ select(run_definitions)+ .where(run_definitions.c.id == definition_id)+ .where(run_definitions.c.deleted_at.is_(None))+ .limit(1)+ ).mappings().first()+ if definition is None:+ continue+ run_session_id = str(row["session_id"] or "").strip() or None+ definition_session_id = (+ str(definition["session_id"] or "").strip() or None+ )+ run_session_key = (+ str(row["legacy_session_key"] or "").strip() or None+ )+ definition_session_key = (+ str(definition["legacy_session_key"] or "").strip() or None+ )+ if (+ definition_session_id != run_session_id+ or definition_session_key != run_session_key+ ):+ continue+ expectation = DefinitionWriteExpectation.from_read(+ session_id=definition["session_id"],+ enabled=definition["enabled"],+ deleted_at=definition["deleted_at"],+ metadata=_json_loads(definition["metadata_json"], {}),+ )+ definition_values: dict[str, Any] = {+ "last_run_at": now,+ "last_error": effective_error,+ "updated_at": now,+ }+ if (+ str(definition["definition_type"] or "") == "scheduled"+ and str(definition["schedule_type"] or "") == "at"+ and str(row["source_kind"] or "") == "scheduler"+ ):+ definition_values["enabled"] = 0+ conn.execute(+ update(run_definitions)+ .where(run_definitions.c.id == definition_id)+ .where(*definition_state_unchanged(expectation))+ .where(+ unchanged_text(+ run_definitions.c.legacy_session_key,+ definition_session_key,+ )+ )+ .where(+ run_definitions.c.definition_type+ == definition["definition_type"]+ )+ .where(+ unchanged_text(+ run_definitions.c.schedule_type,+ definition["schedule_type"],+ )+ )+ .values(**definition_values)+ )+ if requeued_ids:conn.execute(update(agent_runs)- .where(agent_runs.c.id.in_(recovered_ids))+ .where(agent_runs.c.id.in_(requeued_ids))+ .where(agent_runs.c.status.in_(_status_query_values("running")))+ .where(agent_runs.c.pid.is_(None)).values(status="queued", started_at=None, pid=None, updated_at=now))- _defer_run_ids_updated_from_connection(conn, recovered_ids)+ _defer_run_ids_updated_from_connection(+ conn,+ terminal_ids + requeued_ids,+ )def record_run_skip_reason(self, run_id: str, *, reason: str, at: Optional[str] = None) -> bool:"""Record WHY the drain deferred a queued run — only when it changes.diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 2385c120e..46e7e14b4 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -29,12 +29,12 @@ scenarios:backend: sharedtest: tests/test_scheduled_tasks.py::test_dead_accepted_owner_converges_run_session_and_persisted_fifo- id: HFR-003- name: canceled scheduler execution requeues its claimed Run+ name: queued but unstarted Run remains queued behind its live Session ownerstatus: covered- kind: cancellation+ kind: safetylayer: contractbackend: shared- test: tests/test_scheduled_tasks.py::test_drain_requests_requeues_cancelled_task_run+ test: tests/test_scheduled_tasks.py::test_drain_serializes_executions_per_session- id: HFR-004name: restart recovers held run queues without flushing user-owned queue headsstatus: covered@@ -2316,6 +2316,55 @@ scenarios:# property every round of this review has verified as unchanged, so it is a scoped# follow-up for the plan owner and not a close-out edit.test: tests/test_harness_failure_visibility.py::test_a_successful_rebind_is_delivered_through_the_retried_notice_path+ - id: HFR-100+ name: direct in-flight cancellation terminalizes the exact Run and releases ownership+ status: covered+ kind: cancellation+ layer: contract+ backend: shared+ test: tests/test_scheduled_tasks.py::test_direct_inflight_cancellation_terminalizes_the_exact_run+ - id: HFR-101+ name: service stop terminalizes an in-flight Run so restart cannot replay it+ status: covered+ kind: restart+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_service_stop_terminalizes_inflight_run_without_replay+ - id: HFR-102+ name: every canceled task execution projects a result and only scheduler one-shots retire+ status: covered+ kind: cancellation+ layer: contract+ backend: shared+ test: tests/test_scheduled_tasks.py::test_canceled_task_execution_projects_every_result_and_only_retires_scheduler_one_shots+ - id: HFR-103+ name: every service teardown settles the transferred scheduled Turn without draining held work+ status: covered+ kind: cancellation+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_service_teardown_terminalizes_transferred_durable_turn_without_draining_held_queue+ - id: HFR-104+ name: restart recovery fails executed Runs and preserves separately owned rows+ status: covered+ kind: restart+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_restart_recovery_terminalizes_started_rows_and_preserves_other_owners+ - id: HFR-105+ name: every teardown entry point and state surface cell has evidence or an explicit owner+ status: covered+ kind: safety+ layer: contract+ backend: shared+ test: tests/test_scheduled_tasks.py::test_every_teardown_settlement_surface_is_reached_or_explicitly_owned_elsewhere+ - id: HFR-106+ name: user Stop cause wins when graceful shutdown cancels the same non-durable Run+ status: covered+ kind: cancellation+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_service_stop_preserves_non_durable_user_stop_cause- id: HFR-240name: the backend-wide clear does not delete a superseded rowstatus: covereddiff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex d8c5e0143..664c1e953 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import astimport jsonimport sqlite3import sys@@ -24,10 +25,18 @@ from core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.message_mirror import mirror_harness_inboundfrom core.message_output import MessageOutput, stop_output_forfrom core.run_settlement import (+ RUN_INTERRUPTION_REASONS,SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_RESTARTED,SETTLED_BY_STOPPED,SETTLED_BY_TERMINAL_RESULT,SETTLED_BY_TURN_ONLY_RESULT,+ SETTLEMENT_I18N_KEYS,+ SETTLEMENT_TERMINAL_STATUS,+ SETTLEMENTS_WITHOUT_RESULT,+ TEARDOWN_SETTLEMENT_ENTRY_POINTS,+ TEARDOWN_SETTLEMENT_MATRIX,+ TEARDOWN_SETTLEMENT_SURFACES,)from core.services.dispatch import SOURCE_SCHEDULED, TurnDispatchOutcomefrom core.session_activities import SessionActivityRegistry@@ -1668,62 +1677,1055 @@ def test_recover_processing_drops_completed_requests(tmp_path: Path) -> None:assert not (store.pending_dir / f"{request.id}.json").exists()-def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:- """HFR-003: cancellation requeues the claim and releases its Session slot."""+def test_direct_inflight_cancellation_terminalizes_the_exact_run(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """HFR-100: a canceled claimed execution releases ownership and fails its Run."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))path = tmp_path / "scheduled_tasks.json"- request_store = TaskExecutionStore(tmp_path / "task_requests")+ request_store = TaskExecutionStore()store = ScheduledTaskStore(path)task = store.add_task(session_key="slack::channel::C123",- prompt="send digest",+ prompt="send digest",+ schedule_type="at",+ run_at="2026-03-31T09:00:00+08:00",+ timezone_name="Asia/Shanghai",+ )+ request = request_store.enqueue_task_run(task.id)+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))+ started = asyncio.Event()++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ started.set()+ await asyncio.Event().wait()++ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),+ )+ service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)++ async def _exercise() -> None:+ await service._drain_requests()+ execution = service._inflight_executions.get(request.id)+ assert execution is not None+ await asyncio.wait_for(started.wait(), timeout=1)+ execution.cancel()+ with pytest.raises(asyncio.CancelledError):+ await execution+ await asyncio.sleep(0)+ assert request.id not in service._inflight_executions+ assert "key:slack::channel::C123" not in service._inflight_sessions+ assert "key:slack::channel::C123" not in service._session_lock_owners++ asyncio.run(_exercise())++ settled = request_store.get_run(request.id)+ assert settled is not None+ assert settled["status"] == "failed"+ assert settled["metadata"]["interrupt_reason"] == "interrupted"+ assert settled["error"]+ assert request_store.list_pending() == []+++def test_service_stop_terminalizes_inflight_run_without_replay(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """HFR-101: shutdown records the interruption and restart never repeats the prompt."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ task_path = tmp_path / "scheduled_tasks.json"+ store = ScheduledTaskStore(task_path)+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="interrupted prompt",+ schedule_type="at",+ run_at="2026-03-31T09:00:00+08:00",+ timezone_name="Asia/Shanghai",+ )+ request_store = TaskExecutionStore()+ request = request_store.enqueue_task_run(+ task.id,+ source_kind="scheduler",+ task=task,+ )+ successor = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="queued successor",+ )+ started = asyncio.Event()+ prompts: list[str] = []+ settings_manager = SimpleNamespace(+ get_store=lambda: SimpleNamespace(+ get_user=lambda *_args, **_kwargs: None,+ )+ )++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ prompts.append(message)+ if message == "interrupted prompt":+ started.set()+ await asyncio.Event().wait()++ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),+ )+ service = ScheduledTaskService(+ controller=controller,+ store=store,+ request_store=request_store,+ )++ async def _stop_in_flight() -> None:+ await service._drain_requests()+ await asyncio.wait_for(started.wait(), timeout=1)+ await service.stop()+ assert prompts == ["interrupted prompt"]++ asyncio.run(_stop_in_flight())++ settled = request_store.get_run(request.id)+ assert settled is not None+ assert settled["status"] == "failed"+ assert settled["metadata"]["interrupt_reason"] == "restarted"+ assert settled["error"]+ queued = request_store.get_run(successor.id)+ assert queued is not None+ assert queued["status"] == "queued"+ retired = ScheduledTaskStore(task_path).get_task(task.id)+ assert retired is not None+ assert retired.enabled is False+ assert retired.last_error == settled["error"]++ restarted_store = TaskExecutionStore()+ restarted = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(task_path),+ request_store=restarted_store,+ )+ restarted.reconcile_jobs()+ assert restarted.scheduler.get_job(task.id) is None++ async def _restart_and_drain_successor() -> None:+ await restarted._drain_requests()+ successor_task = restarted._inflight_executions.get(successor.id)+ assert successor_task is not None+ await successor_task++ asyncio.run(_restart_and_drain_successor())++ assert prompts == ["interrupted prompt", "queued successor"]+ successor_result = restarted_store.get_run(successor.id)+ assert successor_result is not None+ assert successor_result["status"] == "succeeded"+ assert restarted_store.list_pending() == []+ assert not (request_store.processing_dir / f"{request.id}.json").exists()+ assert not (request_store.completed_dir / f"{request.id}.json").exists()+++def test_service_stop_preserves_non_durable_user_stop_cause(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """HFR-106: user Stop wins when graceful shutdown cancels the same Run."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="stop before shutdown",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )+ request_store = TaskExecutionStore()+ request = request_store.enqueue_task_run(+ task.id,+ source_kind="scheduler",+ task=task,+ )+ started = asyncio.Event()++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ started.set()+ await asyncio.Event().wait()++ settings_manager = SimpleNamespace(+ get_store=lambda: SimpleNamespace(+ get_user=lambda *_args, **_kwargs: None,+ )+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(+ handle_scheduled_message=_handle_scheduled_message,+ ),+ ),+ store=store,+ request_store=request_store,+ )++ async def _stop_after_user() -> None:+ await service._drain_requests()+ await asyncio.wait_for(started.wait(), timeout=1)+ assert request_store.cancel_run(request.id)+ await service.stop()++ asyncio.run(_stop_after_user())++ settled = request_store.get_run(request.id)+ projected = ScheduledTaskStore().get_task(task.id)+ assert settled is not None+ assert settled["status"] == "canceled"+ assert settled["metadata"]["interrupt_reason"] == SETTLED_BY_STOPPED+ assert settled["error"] == service._t(+ SETTLEMENT_I18N_KEYS[SETTLED_BY_STOPPED]+ )+ assert projected is not None+ assert projected.enabled is True+ assert projected.last_error == settled["error"]+ assert request_store.sqlite_backend is not None+ assert request_store.sqlite_backend.owed_failure_notice(request.id) is None+++def test_service_stop_keeps_claim_cancelled_before_execution_starts_queued(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """A bare claim stays queued when teardown wins before coroutine entry."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ task_path = tmp_path / "scheduled_tasks.json"+ store = ScheduledTaskStore(task_path)+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="never dispatched",+ schedule_type="at",+ run_at="2026-03-31T09:00:00+08:00",+ timezone_name="Asia/Shanghai",+ )+ request_store = TaskExecutionStore()+ request = request_store.enqueue_task_run(+ task.id,+ source_kind="scheduler",+ task=task,+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=request_store,+ )++ async def _stop_before_start() -> None:+ claimed = request_store.claim(request.id)+ assert claimed is not None+ service._spawn_execution(claimed, "key:slack::channel::C123")+ await service.stop()++ asyncio.run(_stop_before_start())++ settled = request_store.get_run(request.id)+ assert settled is not None+ assert settled["status"] == "queued"+ assert "interrupt_reason" not in settled["metadata"]+ preserved = ScheduledTaskStore(task_path).get_task(task.id)+ assert preserved is not None+ assert preserved.enabled is True+ assert preserved.last_run_at is None+ assert preserved.last_error is None+++ ("schedule_type", "source_kind", "expected_enabled"),+ [+ ("cron", "scheduler", True),+ ("at", "cli", True),+ ("at", "scheduler", False),+ ],+)+def test_canceled_task_execution_projects_every_result_and_only_retires_scheduler_one_shots(+ tmp_path: Path,+ monkeypatch,+ schedule_type: str,+ source_kind: str,+ expected_enabled: bool,+) -> None:+ """HFR-102: every interrupted fire records a result; only owned one-shots retire."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ task_path = tmp_path / "scheduled_tasks.json"+ store = ScheduledTaskStore(task_path)+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="record this interruption",+ schedule_type=schedule_type,+ cron="0 * * * *" if schedule_type == "cron" else None,+ run_at=(+ "2026-03-31T09:00:00+08:00"+ if schedule_type == "at"+ else None+ ),+ timezone_name="Asia/Shanghai",+ )+ request_store = TaskExecutionStore()+ request = request_store.enqueue_task_run(+ task.id,+ source_kind=source_kind,+ task=task,+ )+ started = asyncio.Event()++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ started.set()+ await asyncio.Event().wait()++ settings_manager = SimpleNamespace(+ get_store=lambda: SimpleNamespace(+ get_user=lambda *_args, **_kwargs: None,+ )+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(+ handle_scheduled_message=_handle_scheduled_message,+ ),+ ),+ store=store,+ request_store=request_store,+ )+ service.scheduler = _StubScheduler()+ service.scheduler.jobs[task.id] = SimpleNamespace(id=task.id)++ async def _cancel() -> None:+ await service._drain_requests()+ execution = service._inflight_executions[request.id]+ await asyncio.wait_for(started.wait(), timeout=1)+ execution.cancel()+ with pytest.raises(asyncio.CancelledError):+ await execution+ await asyncio.sleep(0)++ asyncio.run(_cancel())++ settled = request_store.get_run(request.id)+ projected = ScheduledTaskStore(task_path).get_task(task.id)+ assert settled is not None and settled["status"] == "failed"+ assert projected is not None+ assert projected.enabled is expected_enabled+ assert projected.last_run_at is not None+ assert projected.last_error == settled["error"]+ assert (task.id in service.scheduler.jobs) is expected_enabled++[email protected]("cancellation_entrypoint", ["direct", "service_stop", "lease_loss"])[email protected]("settlement_winner", ["interruption", "natural_terminal", "user_stop"])+def test_task_definition_projection_follows_the_exact_terminal_cas_winner(+ tmp_path: Path,+ monkeypatch,+ cancellation_entrypoint: str,+ settlement_winner: str,+) -> None:+ """HFR-102: definition projection follows the exact terminal CAS winner."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="settle this exact fire",+ schedule_type="at",+ run_at="2026-08-04T00:00:00+00:00",+ timezone_name="UTC",+ )+ request_store = TaskExecutionStore()+ request = request_store.enqueue_task_run(+ task.id,+ source_kind="scheduler",+ task=task,+ )+ started = asyncio.Event()++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ started.set()+ await asyncio.Event().wait()++ settings_manager = SimpleNamespace(+ get_store=lambda: SimpleNamespace(+ get_user=lambda *_args, **_kwargs: None,+ )+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(+ handle_scheduled_message=_handle_scheduled_message,+ ),+ ),+ store=store,+ request_store=request_store,+ )+ service.scheduler = _StubScheduler()+ service.scheduler.jobs[task.id] = SimpleNamespace(id=task.id)++ async def _race_terminal_with_cancellation() -> None:+ await service._drain_requests()+ execution = service._inflight_executions[request.id]+ await asyncio.wait_for(started.wait(), timeout=1)+ if settlement_winner == "natural_terminal":+ assert store.mark_task_result(+ task.id,+ error=None,+ disable_one_shot=True,+ )+ assert request_store.complete(request, ok=True) == "succeeded"+ service.reconcile_jobs()+ elif settlement_winner == "user_stop":+ assert request_store.cancel_run(request.id)+ if cancellation_entrypoint == "direct":+ if settlement_winner == "user_stop":+ service._inflight_cancellation_causes[request.id] = SETTLED_BY_STOPPED+ execution.cancel()+ with pytest.raises(asyncio.CancelledError):+ await execution+ elif cancellation_entrypoint == "service_stop":+ await service.stop()+ else:+ service._running = True+ service._requires_service_lease = True+ monkeypatch.setattr(+ "core.scheduled_tasks.runtime.current_process_owns_service_instance",+ lambda: False,+ )+ assert service._owns_service_instance() is False+ teardown = service._service_teardown_task+ assert teardown is not None+ await teardown+ await service.stop()+ await asyncio.sleep(0)++ asyncio.run(_race_terminal_with_cancellation())++ settled = request_store.get_run(request.id)+ projected = ScheduledTaskStore().get_task(task.id)+ assert settled is not None+ expected_status = {+ "interruption": "failed",+ "natural_terminal": "succeeded",+ "user_stop": "canceled",+ }[settlement_winner]+ assert settled["status"] == expected_status+ assert projected is not None+ assert projected.enabled is False+ assert projected.last_run_at is not None+ assert projected.last_error == settled["error"]+ assert task.id not in service.scheduler.jobs+ if settlement_winner == "natural_terminal":+ assert "interrupt_reason" not in settled["metadata"]+ elif settlement_winner == "user_stop":+ assert settled["metadata"]["interrupt_reason"] == SETTLED_BY_STOPPED++[email protected]("shutdown_entrypoint", ["stop", "lease_loss"])[email protected]("user_stopped", [False, True])+def test_service_teardown_terminalizes_transferred_durable_turn_without_draining_held_queue(+ tmp_path: Path,+ monkeypatch,+ shutdown_entrypoint: str,+ user_stopped: bool,+) -> None:+ """HFR-103: every service teardown settles the transferred scheduled Run."""+ from storage.background import attach_agent_run_delivery_in_connection++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ session_id = _make_avibe_session(monkeypatch, tmp_path, agent_backend="codex")+ definition_store = ScheduledTaskStore()+ definition = definition_store.add_task(+ session_key="",+ session_id=session_id,+ session_policy="existing",+ prompt="durable prompt interrupted by shutdown",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )+ request_store = TaskExecutionStore()+ run_id = request_store.enqueue_task_run(+ definition.id,+ source_kind="scheduler",+ task=definition,+ ).id+ _force_run_columns(+ request_store,+ run_id,+ status="running",+ started_at=_ago(30),+ pid=1234,+ )+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ session = conn.execute(+ select(agent_sessions).where(agent_sessions.c.id == session_id)+ ).mappings().one()+ delivery_id = message_deliveries.new_delivery_id()+ turn_id = message_deliveries.new_turn_id()+ delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id=session_id,+ priority="p3",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=session["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type="harness",+ text="durable prompt interrupted by shutdown",+ native_message_id=f"agent_run:{run_id}",+ metadata={},+ ),+ dispatch_text="durable prompt interrupted by shutdown",+ )+ assert attach_agent_run_delivery_in_connection(+ conn,+ run_id,+ session_id=session_id,+ delivery_id=delivery_id,+ )+ message_deliveries.claim_start_batch(+ conn,+ turn_id=turn_id,+ session_id=session_id,+ backend="codex",+ deliveries=[delivery],+ dispatch_text="durable prompt interrupted by shutdown",+ )+ turn = message_deliveries.get_turn(conn, turn_id)+ assert turn is not None+ assert message_deliveries.bind_native_start(+ conn,+ turn_id,+ expected_version=int(turn["version"]),+ runtime_key="runtime-key",+ runtime_turn_id="runtime-turn",+ native_turn_id="native-turn",+ ) is not None+ assert message_deliveries.materialize_start_acceptance(+ conn,+ turn_id=turn_id,+ evidence={"kind": "native_acceptance"},+ )+ message_deliveries.set_queue_hold(conn, session_id, held=True)+ queued = message_deliveries.enqueue_queued(+ conn,+ scope_id=session["scope_id"],+ session_id=session_id,+ author="user",+ source="user",+ message_type="user",+ text="keep me held",+ native_message_id="held-after-shutdown",+ )+ successor_delivery_id = None+ successor_turn_id = None+ if not user_stopped:+ successor_delivery_id = message_deliveries.new_delivery_id()+ successor_turn_id = message_deliveries.new_turn_id()+ successor_delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id=successor_delivery_id,+ session_id=session_id,+ priority="p0",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=session["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="user",+ source="user",+ message_type="user",+ text="do not start this replacement",+ native_message_id="replacement-after-shutdown",+ metadata={},+ ),+ dispatch_text="do not start this replacement",+ )+ message_deliveries.insert_turn(+ conn,+ turn_id=successor_turn_id,+ session_id=session_id,+ initial_delivery_id=successor_delivery_id,+ state="waiting",+ backend="codex",+ )+ assert message_deliveries.cas_delivery(+ conn,+ successor_delivery_id,+ expected_version=int(successor_delivery["version"]),+ expected_states=("reserved",),+ values={+ "state": "interrupt_waiting",+ "turn_id": successor_turn_id,+ "turn_role": "initial",+ "turn_position": 0,+ },+ ) is not None+ active = message_deliveries.get_turn(conn, turn_id)+ assert active is not None+ assert message_deliveries.cas_turn(+ conn,+ turn_id,+ expected_version=int(active["version"]),+ expected_states=("active",),+ values={+ "control_state": "interrupting",+ "control_mode": "replace",+ "control_successor_delivery_id": successor_delivery_id,+ "control_successor_turn_id": successor_turn_id,+ },+ ) is not None+ if user_stopped:+ active = message_deliveries.get_turn(conn, turn_id)+ assert active is not None+ assert message_deliveries.cas_turn(+ conn,+ turn_id,+ expected_version=int(active["version"]),+ expected_states=("active",),+ values={"control_mode": "stop_only"},+ ) is not None+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .values(cancel_requested=1)+ )++ dispatch_started = asyncio.Event()+ prompts: list[str] = []++ async def _never_returns(_controller, _context, text, **_kwargs):+ prompts.append(text)+ dispatch_started.set()+ await asyncio.Event().wait()+ raise AssertionError("unreachable")++ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _never_returns)+ controller = SimpleNamespace(+ config=SimpleNamespace(language="en"),+ set_agent_status=lambda *_args, **_kwargs: None,+ _get_session_key=lambda ctx: f"avibe::{ctx.channel_id}",+ )+ service = ScheduledTaskService(+ controller=controller,+ store=definition_store,+ request_store=request_store,+ )+ service.scheduler = _StubScheduler()+ manager = SessionTurnManager(controller)+ manager._engine = engine+ controller.session_turns = manager+ controller.scheduled_task_service = service+ context = MessageContext(+ user_id="scheduled",+ channel_id=session_id,+ platform="avibe",+ platform_specific={+ "task_execution_id": run_id,+ "task_definition_id": definition.id,+ "task_trigger_kind": "scheduled",+ "accepted_agent_run_ids": [run_id],+ "agent_session_target": {"agent_backend": "codex"},+ },+ )++ async def _stop() -> None:+ await manager._run(+ session_id,+ context,+ "durable prompt interrupted by shutdown",+ source=SOURCE_SCHEDULED,+ logical_turn_id=turn_id,+ delivery_id=delivery_id,+ durable_preallocated=True,+ )+ await asyncio.wait_for(dispatch_started.wait(), timeout=1)+ if shutdown_entrypoint == "stop":+ await service.stop()+ return+ service._running = True+ service._requires_service_lease = True+ monkeypatch.setattr(+ "core.scheduled_tasks.runtime.current_process_owns_service_instance",+ lambda: False,+ )+ assert service._owns_service_instance() is False+ teardown = service._service_teardown_task+ assert teardown is not None+ assert service._owns_service_instance() is False+ assert service._service_teardown_task is teardown+ await teardown+ await service.stop()+ assert service._service_teardown_task is teardown++ asyncio.run(_stop())++ settled = request_store.get_run(run_id)+ assert settled is not None+ expected_status = "canceled" if user_stopped else "failed"+ expected_reason = SETTLED_BY_STOPPED if user_stopped else SETTLED_BY_RESTARTED+ assert settled["status"] == expected_status+ assert settled["metadata"]["interrupt_reason"] == expected_reason+ projected_definition = ScheduledTaskStore().get_task(definition.id)+ assert projected_definition is not None+ assert projected_definition.enabled is True+ assert projected_definition.last_run_at is not None+ assert projected_definition.last_error == settled["error"]+ with engine.connect() as conn:+ terminal_turn = message_deliveries.get_turn(conn, turn_id)+ accepted = message_deliveries.get_delivery(conn, delivery_id)+ held = message_deliveries.get_delivery(conn, queued["id"])+ successor_turn = (+ message_deliveries.get_turn(conn, successor_turn_id)+ if successor_turn_id+ else None+ )+ successor_delivery = (+ message_deliveries.get_delivery(conn, successor_delivery_id)+ if successor_delivery_id+ else None+ )+ assert message_deliveries.queue_is_held(conn, session_id) is True+ assert terminal_turn is not None+ assert terminal_turn["state"] == "terminal"+ assert terminal_turn["terminal_outcome"] == expected_status+ assert terminal_turn["settled_by"] == expected_reason+ assert terminal_turn["terminal_evidence_kind"] == (+ "service_shutdown_after_user_stop"+ if user_stopped+ else "service_shutdown"+ )+ assert accepted is not None and accepted["state"] == "accepted"+ assert held is not None and held["state"] == "queued"+ if successor_turn_id:+ assert successor_turn is not None+ assert successor_turn["state"] == "terminal"+ assert successor_turn["terminal_outcome"] == "not_written"+ assert successor_delivery is not None+ assert successor_delivery["state"] == "queued"+ assert successor_delivery["priority"] == "p3"+ assert successor_delivery["turn_id"] is None+ assert manager.in_flight == {}+ assert prompts == ["durable prompt interrupted by shutdown"]+++def test_service_stop_preserves_terminal_run_that_won_the_race(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """A recorded terminal outcome wins over the teardown fallback."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store = TaskExecutionStore()+ request = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="finish before shutdown",+ )+ started = asyncio.Event()++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ started.set()+ await asyncio.Event().wait()++ settings_manager = SimpleNamespace(+ get_store=lambda: SimpleNamespace(+ get_user=lambda *_args, **_kwargs: None,+ )+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(+ handle_scheduled_message=_handle_scheduled_message,+ ),+ ),+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ async def _settle_then_stop() -> None:+ await service._drain_requests()+ await asyncio.wait_for(started.wait(), timeout=1)+ request_store.complete(request, ok=True)+ await service.stop()++ asyncio.run(_settle_then_stop())++ settled = request_store.get_run(request.id)+ assert settled is not None+ assert settled["status"] == "succeeded"+ assert "interrupt_reason" not in settled["metadata"]+++def test_restart_recovery_terminalizes_started_rows_and_preserves_other_owners(+ monkeypatch,+ tmp_path,+) -> None:+ """HFR-104: startup fails executed Runs while preserving every exempt owner."""+ from storage.background import attach_agent_run_delivery_in_connection++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ definition_store = ScheduledTaskStore()+ scheduler_at = definition_store.add_task(+ session_key="slack::channel::C123",+ prompt="scheduler at",schedule_type="at",run_at="2026-03-31T09:00:00+08:00",timezone_name="Asia/Shanghai",)- request = request_store.enqueue_task_run(task.id)- settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))+ scheduler_cron = definition_store.add_task(+ session_key="slack::channel::C123",+ prompt="scheduler cron",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )+ manual_at = definition_store.add_task(+ session_key="slack::channel::C123",+ prompt="manual at",+ schedule_type="at",+ run_at="2026-03-31T09:00:00+08:00",+ timezone_name="Asia/Shanghai",+ )+ request_store = TaskExecutionStore()- async def _handle_scheduled_message(context, message, parsed_session_key=None):- raise asyncio.CancelledError()+ started_runs: dict[str, str] = {}+ for label, task, source_kind in (+ ("scheduler_at", scheduler_at, "scheduler"),+ ("scheduler_cron", scheduler_cron, "scheduler"),+ ("manual_at", manual_at, "cli"),+ ):+ request = request_store.enqueue_task_run(+ task.id,+ source_kind=source_kind,+ task=task,+ )+ assert request_store.claim(request.id) is not None+ _force_run_columns(request_store, request.id, pid=4321)+ started_runs[label] = request.id- controller = SimpleNamespace(- platform_settings_managers={"slack": settings_manager},- message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),+ pre_execution = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="claimed but coroutine never entered",)- service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)+ assert request_store.claim(pre_execution.id) is not None- async def _exercise() -> None:- # The drain now dispatches concurrently and returns immediately, so- # the CancelledError surfaces on the spawned execution task rather- # than out of _drain_requests itself. Awaiting it lets the requeue- # path (in _execute_claimed_request) run.- await service._drain_requests()- execution = service._inflight_executions.get(request.id)- assert execution is not None- try:- await execution- except asyncio.CancelledError:- pass- else:- raise AssertionError("expected CancelledError on the execution task")- await asyncio.sleep(0)- assert request.id not in service._inflight_executions- assert "key:slack::channel::C123" not in service._inflight_sessions+ watch_runtime = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="watch runtime bookkeeping",+ )+ assert request_store.claim(watch_runtime.id) is not None+ _force_run_columns(+ request_store,+ watch_runtime.id,+ run_type="watch_runtime",+ pid=4321,+ )- asyncio.run(_exercise())+ deferred = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="activity owns terminal settlement",+ )+ assert request_store.claim(deferred.id) is not None+ _force_run_columns(+ request_store,+ deferred.id,+ pid=4321,+ result_payload_json=json.dumps({"deferred_terminal_status": "succeeded"}),+ )- reloaded = ScheduledTaskStore(path)- updated = reloaded.get_task(task.id)- assert updated is not None- assert updated.last_run_at is None- assert updated.enabled is True- assert (request_store.pending_dir / f"{request.id}.json").exists()- assert not (request_store.processing_dir / f"{request.id}.json").exists()- assert not (request_store.completed_dir / f"{request.id}.json").exists()+ stopped = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="user stopped before restart",+ )+ assert request_store.claim(stopped.id) is not None+ _force_run_columns(request_store, stopped.id, pid=4321)+ assert request_store.cancel_run(stopped.id)++ delivery_owned = request_store.enqueue_agent_run(+ session_id=session_id,+ message="durable Turn owns this row",+ agent_name="codex",+ )+ assert request_store.claim(delivery_owned.id) is not None+ _force_run_columns(request_store, delivery_owned.id, pid=4321)+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ session = conn.execute(+ select(agent_sessions).where(agent_sessions.c.id == session_id)+ ).mappings().one()+ delivery = message_deliveries.enqueue_queued(+ conn,+ scope_id=session["scope_id"],+ session_id=session_id,+ author="harness",+ source="harness",+ message_type="harness",+ text="durable Turn owns this row",+ native_message_id=f"agent_run:{delivery_owned.id}",+ )+ assert attach_agent_run_delivery_in_connection(+ conn,+ delivery_owned.id,+ session_id=session_id,+ delivery_id=str(delivery["id"]),+ )++ natural = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="natural terminal wins",+ )+ claimed_natural = request_store.claim(natural.id)+ assert claimed_natural is not None+ request_store.complete(claimed_natural, ok=True)++ held_queued = request_store.enqueue_agent_run(+ session_id=session_id,+ message="held queue stays queued",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )++ restarted_store = TaskExecutionStore()+ restarted_store.recover_processing()++ for run_id in started_runs.values():+ settled = restarted_store.get_run(run_id)+ assert settled is not None+ assert settled["status"] == "failed"+ assert settled["metadata"]["interrupt_reason"] == "restarted"+ assert settled["error"]+ assert settled["completed_at"] is not None++ assert restarted_store.get_run(pre_execution.id)["status"] == "queued"+ assert restarted_store.get_run(watch_runtime.id)["status"] == "running"+ assert restarted_store.get_run(deferred.id)["status"] == "running"+ assert restarted_store.get_run(delivery_owned.id)["status"] == "running"+ assert restarted_store.get_run(natural.id)["status"] == "succeeded"+ assert restarted_store.get_run(held_queued.id)["status"] == "queued"+ recovered_stopped = restarted_store.get_run(stopped.id)+ assert recovered_stopped["status"] == "canceled"+ assert recovered_stopped["metadata"]["interrupt_reason"] == SETTLED_BY_STOPPED++ projected = ScheduledTaskStore()+ recovered_scheduler_at = projected.get_task(scheduler_at.id)+ recovered_scheduler_cron = projected.get_task(scheduler_cron.id)+ recovered_manual_at = projected.get_task(manual_at.id)+ assert recovered_scheduler_at is not None+ assert recovered_scheduler_cron is not None+ assert recovered_manual_at is not None+ assert recovered_scheduler_at.enabled is False+ assert recovered_scheduler_cron.enabled is True+ assert recovered_manual_at.enabled is True+ for definition in (+ recovered_scheduler_at,+ recovered_scheduler_cron,+ recovered_manual_at,+ ):+ assert definition.last_run_at is not None+ assert definition.last_error+++_TEARDOWN_SETTLEMENT_CELLS = [+ (entry_point, surface, TEARDOWN_SETTLEMENT_MATRIX[entry_point][surface])+ for entry_point in TEARDOWN_SETTLEMENT_ENTRY_POINTS+ for surface in TEARDOWN_SETTLEMENT_SURFACES+]+++ ("entry_point", "surface", "proof"),+ _TEARDOWN_SETTLEMENT_CELLS,+ ids=[+ f"{entry_point}-{surface}"+ for entry_point, surface, _proof in _TEARDOWN_SETTLEMENT_CELLS+ ],+)+def test_every_teardown_settlement_surface_is_reached_or_explicitly_owned_elsewhere(+ entry_point: str,+ surface: str,+ proof: tuple[str, str],+) -> None:+ """HFR-105: every entry point x surface cell has durable evidence or an owner."""+ assert set(TEARDOWN_SETTLEMENT_MATRIX) == set(+ TEARDOWN_SETTLEMENT_ENTRY_POINTS+ )+ assert set(TEARDOWN_SETTLEMENT_MATRIX[entry_point]) == set(+ TEARDOWN_SETTLEMENT_SURFACES+ )+ proof_kind, detail = proof+ assert proof_kind in {"covered", "N/A"}+ assert detail.strip()+ if proof_kind == "covered":+ test_path, *node_parts = detail.split("::")+ assert test_path.startswith("tests/")+ assert node_parts+ test_name = node_parts[-1]+ tree = ast.parse(Path(test_path).read_text(encoding="utf-8"))+ assert any(+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name == test_name+ for node in ast.walk(tree)+ ), detail++ assert set(SETTLEMENTS_WITHOUT_RESULT) == set(SETTLEMENT_I18N_KEYS)+ assert set(SETTLEMENTS_WITHOUT_RESULT) == set(SETTLEMENT_TERMINAL_STATUS)+ assert SETTLED_BY_RESTARTED in RUN_INTERRUPTION_REASONS++ from storage.background import RUN_INTERRUPTION_REASONS as storage_reasons++ assert storage_reasons == RUN_INTERRUPTION_REASONS+++def test_file_recovery_distinguishes_bare_started_and_user_stopped_claims(+ tmp_path: Path,+) -> None:+ request_store = TaskExecutionStore(tmp_path / "task_requests")++ bare = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="claim only",+ )+ assert request_store.claim(bare.id) is not None++ started = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="started",+ )+ assert request_store.claim(started.id) is not None+ assert request_store.mark_execution_started(started.id)++ stopped = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="stopped",+ )+ assert request_store.claim(stopped.id) is not None+ assert request_store.mark_execution_started(stopped.id)+ assert request_store.cancel_run(stopped.id)++ request_store.recover_processing()++ assert request_store.get_run(bare.id)["status"] == "queued"+ recovered_started = request_store.get_run(started.id)+ assert recovered_started["status"] == "failed"+ assert recovered_started["metadata"]["interrupt_reason"] == SETTLED_BY_RESTARTED+ recovered_stopped = request_store.get_run(stopped.id)+ assert recovered_stopped["status"] == "canceled"+ assert recovered_stopped["metadata"]["interrupt_reason"] == SETTLED_BY_STOPPEDdef test_restart_recovers_running_row_and_preserves_same_session_fifo(monkeypatch, tmp_path) -> None:- """HFR-004: a crash-held row restarts queued and each successor runs once."""+ """A bare-claimed row restarts queued and each successor runs once."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))request_store = TaskExecutionStore()@@ -2052,6 +3054,7 @@ def test_service_lease_loss_cancels_inflight_execution(tmp_path: Path, monkeypatstarted = asyncio.Event()async def fake_execute(claimed):+ assert request_store.mark_execution_started(claimed.id)started.set()await asyncio.Event().wait()@@ -2074,6 +3077,10 @@ def test_service_lease_loss_cancels_inflight_execution(tmp_path: Path, monkeypatasyncio.run(_exercise())assert service._running is False+ settled = request_store.get_run(request.id)+ assert settled is not None+ assert settled["status"] == "failed"+ assert settled["metadata"]["interrupt_reason"] == "restarted"def test_run_task_uses_tracked_execution_for_lease_loss(tmp_path: Path, monkeypatch) -> None:@@ -2816,10 +3823,9 @@ def test_late_terminal_result_cannot_reopen_a_stopped_run(tmp_path: Path, monkey# only thing that can close them, which also makes it the only thing that can# WRONGLY close a healthy run — so the negative cases matter as much as the positive.#-# Note on staging: ``ScheduledTaskService.__init__`` runs ``recover_processing()``,-# which requeues every ``running`` row (that is how a restart's in-flight runs get-# retried, and why the orphan class here is about owners lost WITHIN a live process).-# So these tests build the service first and stage the stale row afterwards.+# Note on staging: ``ScheduledTaskService.__init__`` runs ``recover_processing()``.+# It requeues bare claims and terminalizes executions whose coroutine had started,+# so these tests build the service first and stage the live-process orphan after it.# ---------------------------------------------------------------------------@@ -4369,9 +5375,6 @@ def test_agent_run_early_failure_settles_only_the_exact_run(tmp_path: Path, monkagent_name="codex",)run_ids.append(request.id)- claimed = request_store.claim(run_ids[0])- assert claimed is not None-async def _submit_scheduled(_sid, _ctx, _text):raise AssertionError("the direct execution path should be patched below")@@ -4385,6 +5388,8 @@ def test_agent_run_early_failure_settles_only_the_exact_run(tmp_path: Path, monkstore=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),request_store=request_store,)+ claimed = request_store.claim(run_ids[0])+ assert claimed is not Noneasync def _raise_early(**_kwargs):raise RuntimeError("target session vanished")@@ -7086,18 +8091,18 @@ def test_claimed_request_refreshes_agent_name_after_archive(monkeypatch, tmp_patprompt="continue",agent_name=agent.name,)- claimed = request_store.claim(request.id)- assert claimed is not None- assert claimed.agent_name == "pm"-- archived = agent_store.archive("pm")- assert archived is not Nonecalls: list[dict[str, Any]] = []service = ScheduledTaskService(controller=SimpleNamespace(),store=ScheduledTaskStore(),request_store=request_store,)+ claimed = request_store.claim(request.id)+ assert claimed is not None+ assert claimed.agent_name == "pm"++ archived = agent_store.archive("pm")+ assert archived is not Noneasync def _execute_request(**kwargs):calls.append(kwargs)@@ -7128,6 +8133,12 @@ def test_claimed_request_keeps_agent_identity_when_archive_lands_after_refresh(prompt="continue",agent_name=agent.name,)+ calls: list[dict[str, Any]] = []+ service = ScheduledTaskService(+ controller=SimpleNamespace(),+ store=ScheduledTaskStore(),+ request_store=request_store,+ )claimed = request_store.claim(request.id)assert claimed is not None@@ -7142,12 +8153,6 @@ def test_claimed_request_keeps_agent_identity_when_archive_lands_after_refresh(return refreshedrequest_store.refresh_claimed_request = _refresh_then_archive # type: ignore[method-assign]- calls: list[dict[str, Any]] = []- service = ScheduledTaskService(- controller=SimpleNamespace(),- store=ScheduledTaskStore(),- request_store=request_store,- )async def _execute_request(**kwargs):calls.append(kwargs)@@ -7684,8 +8689,7 @@ def test_drain_defers_im_runs_until_transport_ready_without_blocking_workbench(tdef test_drain_serializes_executions_per_session(tmp_path: Path) -> None:- """Two requests for the same session never run concurrently; the second- stays queued until the first finishes."""+ """HFR-003: an unstarted same-session request stays queued until its turn."""async def _exercise() -> None:store = TaskExecutionStore(tmp_path / "reqs")diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 31c3def77..824b5baca 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -45,6 +45,8 @@"stopped": "[Avibe Harness] This run was stopped before the Agent produced a result, so it has no final result. Any output the Agent had already sent is still kept on the run.","refusedConcurrentTurn": "[Avibe Harness] This run was skipped because another turn was already in flight for the same session. A session runs one turn at a time; trigger it again once the current turn finishes.","backendRefresh": "[Avibe Harness] This run was interrupted because its Agent runtime was refreshed while the run was in flight, usually right after an Agent setting was saved. Nothing is wrong with the run itself — trigger it again.",+ "restarted": "[Avibe Harness] This run was interrupted because the service shut down while it was in flight. The interrupted attempt was recorded and will not be replayed after restart. Trigger it again if the work still needs doing.",+ "interrupted": "[Avibe Harness] This run was interrupted while it was in flight. The interrupted attempt was recorded and was not requeued. Trigger it again if the work still needs doing.","orphaned": "[Avibe Harness] This run was left marked as running with nothing executing it, most likely because the service restarted while it was in flight. Any output it had already sent is still kept on the run. Run it again if the work still needs doing.","transportUnavailable": "[Avibe Harness] This run stayed queued because its chat platform never reconnected, so it was never delivered. Check the platform connection in Settings, then trigger it again.","queueHoldExpired": "[Avibe Harness] This run stayed queued behind its session's turn queue for too long and was never started. Check whether that session has a stuck turn, then trigger this run again."@@ -105,6 +107,7 @@"reason": {"stopped": "it was stopped manually","backendRefresh": "its Agent runtime was refreshed",+ "interrupted": "its active execution was interrupted","evicted": "its session was evicted","restarted": "the service restarted","lifetimeTimeout": "its session reached its lifetime limit",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 676c83839..70ba52895 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -45,6 +45,8 @@"stopped": "[Avibe Harness] 本次 run 在 Agent 产出结果前被停止,因此没有最终结果。Agent 此前已经发出的输出仍会保留在这次 run 上。","refusedConcurrentTurn": "[Avibe Harness] 本次 run 被跳过:同一 session 已有另一个 turn 正在执行。一个 session 同时只运行一个 turn,请在当前 turn 结束后重新触发。","backendRefresh": "[Avibe Harness] 本次 run 执行途中,它所用的 Agent 运行时被刷新,因此被中断,通常发生在刚保存 Agent 设置之后。这次 run 本身没有问题,请重新触发。",+ "restarted": "[Avibe Harness] 本次 run 执行途中服务已关闭,因此被中断。该次执行已被记录,服务重启后不会重放。如果这项工作仍需完成,请重新触发。",+ "interrupted": "[Avibe Harness] 本次 run 在执行途中被中断。该次执行已被记录,不会重新排队。如果这项工作仍需完成,请重新触发。","orphaned": "[Avibe Harness] 本次 run 一直标记为 running,但已经没有任何执行在推进它,通常是服务在它执行途中重启导致的。它此前已经发出的输出仍会保留在这次 run 上。如果这项工作仍需完成,请重新运行。","transportUnavailable": "[Avibe Harness] 本次 run 一直排队等待,因为它对应的聊天平台始终没有重新连接,消息也就无法送达。请在设置中检查该平台连接,然后重新触发。","queueHoldExpired": "[Avibe Harness] 本次 run 在所属 session 的 turn 队列后面排队过久,始终没有开始执行。请检查该 session 是否有卡住的 turn,然后重新触发这次 run。"@@ -105,6 +107,7 @@"reason": {"stopped": "被手动停止","backendRefresh": "所用的 Agent 运行时被刷新",+ "interrupted": "正在执行的任务被中断","evicted": "所属会话被回收","restarted": "服务重启","lifetimeTimeout": "所属会话达到生命周期上限",