Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(harness): persist lifecycle terminal facts (#1358)

Call Whitee993a611c97b
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 2485b6031..5957b9c56 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -19,6 +19,7 @@ from uuid import uuid4
from zoneinfo import ZoneInfo
from apscheduler.schedulers.asyncio import AsyncIOScheduler
+from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_MISSED, JobExecutionEvent
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
from sqlalchemy import select
@@ -113,6 +114,9 @@ from storage.background import (
SWEEP_REASON_ORPHANED,
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
SWEEP_REASON_TRANSPORT_UNAVAILABLE,
+ TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ TASK_RETIREMENT_SCHEDULE_MISSED,
+ TASK_SCHEDULE_CONSUMED_METADATA_KEY,
TASK_LAST_RESULT_STATUS_METADATA_KEY,
SweptRun,
WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR,
@@ -124,6 +128,7 @@ from storage.background import (
owed_notice_eligible,
require_task_resumable,
resolve_run_at,
+ task_schedule_generation,
)
from storage.models import agent_sessions, scope_settings, scopes
from storage.pagination import PageRequest, PageResult, page_sequence
@@ -550,6 +555,7 @@ class TaskExecutionResult:
exit_code: Optional[int] = None
stdout: Optional[str] = None
stderr: Optional[str] = None
+ timed_out: Optional[bool] = None
#: The Agent turn a failed ``--on-failure agent`` command fire queued, already
#: durable when this is set. It rides the run row's metadata so the settle that
#: transitions the run also records that its failure has a REPORT, which is what
@@ -1058,6 +1064,9 @@ class ScheduledTask:
created_at: str = field(default_factory=_utc_now_iso)
updated_at: str = field(default_factory=_utc_now_iso)
last_run_at: Optional[str] = None
+ last_run_id: Optional[str] = None
+ retired_at: Optional[str] = None
+ retirement_reason: Optional[str] = None
last_error: Optional[str] = None
metadata: dict[str, Any] = field(default_factory=dict)
# Command tasks run a subprocess instead of messaging an Agent. All four stay
@@ -1108,6 +1117,9 @@ class ScheduledTask:
created_at=str(payload.get("created_at") or _utc_now_iso()),
updated_at=str(payload.get("updated_at") or _utc_now_iso()),
last_run_at=payload.get("last_run_at"),
+ last_run_id=payload.get("last_run_id"),
+ retired_at=payload.get("retired_at"),
+ retirement_reason=payload.get("retirement_reason"),
last_error=payload.get("last_error"),
metadata=payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {},
shell_command=(str(payload["shell_command"]) if payload.get("shell_command") else None),
@@ -1456,6 +1468,8 @@ class ScheduledTaskStore:
expected_uncanceled_run_id: Optional[str] = None,
expected_enabled_agent_id: Optional[str] = None,
expected_reference_agent_id: Optional[str] = None,
+ expected_schedule_generation: Optional[dict[str, str]] = None,
+ expected_terminal_run_id: Optional[str] = None,
) -> bool:
"""Persist a whole task row; ``False`` means the guard refused the write.
@@ -1493,6 +1507,8 @@ class ScheduledTaskStore:
expect=expect,
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ expected_schedule_generation=expected_schedule_generation,
+ expected_terminal_run_id=expected_terminal_run_id,
)
else:
# No agent-guard kwargs: the only caller that passes a queued run is
@@ -1502,6 +1518,8 @@ class ScheduledTaskStore:
expect=expect,
run_payload=queued_run,
expected_uncanceled_run_id=expected_uncanceled_run_id,
+ expected_schedule_generation=expected_schedule_generation,
+ expected_terminal_run_id=expected_terminal_run_id,
)
except Exception:
self._reload_after_lost_write(task.id)
@@ -1659,6 +1677,8 @@ class ScheduledTaskStore:
task_id,
metadata=task.metadata,
session_id=task.session_id,
+ schedule_type=task.schedule_type,
+ retired_at=task.retired_at,
)
expect = self._read_state(task)
task.enabled = enabled
@@ -1702,6 +1722,7 @@ class ScheduledTaskStore:
# (``vibe task update`` resolved Agents and Sessions from this very object),
# and it is what the write below re-asserts.
expect = self._read_state(task)
+ previous_schedule = (task.schedule_type, task.run_at, task.timezone)
task.name = name
task.session_key = session_key
task.session_id = session_id
@@ -1718,6 +1739,12 @@ class ScheduledTaskStore:
task.cron = cron
task.run_at = run_at
task.timezone = timezone_name
+ # Changing a one-shot schedule creates a new lifecycle. The previous
+ # terminal fact remains in Run history but cannot own the new instant.
+ if (schedule_type, run_at, timezone_name) != previous_schedule:
+ task.retired_at = None
+ task.retirement_reason = None
+ task.last_run_id = None
if update_command_fields:
# Gated like ``cwd``: an edit that says nothing about the command must not
# clear it, and ``last_exit_code`` is runtime state no edit ever rewrites.
@@ -1743,6 +1770,51 @@ class ScheduledTaskStore:
return self._tasks[task_id]
return task
+ @_serialize_task_mirror
+ def retire_missed_one_shot(
+ self,
+ task_id: str,
+ *,
+ expected_run_at: str,
+ expected_timezone: str,
+ expected_updated_at: str,
+ ) -> bool:
+ """Retire the exact one-shot schedule APScheduler reported missed."""
+
+ task = self._tasks.get(task_id)
+ if (
+ task is None
+ or not task.enabled
+ or task.schedule_type != "at"
+ or task.retired_at is not None
+ or task.run_at != expected_run_at
+ or task.timezone != expected_timezone
+ or task.updated_at != expected_updated_at
+ ):
+ return False
+ if self._sqlite is not None:
+ landed = self._sqlite.retire_missed_one_shot(
+ task_id,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=expected_updated_at,
+ )
+ if landed:
+ self.load()
+ return landed
+ task.enabled = False
+ task.retired_at = _utc_now_iso()
+ task.retirement_reason = TASK_RETIREMENT_SCHEDULE_MISSED
+ task.last_run_at = None
+ task.last_run_id = None
+ task.last_error = None
+ task.last_exit_code = None
+ task.metadata.pop(COMMAND_TIMED_OUT_METADATA_KEY, None)
+ task.metadata.pop(TASK_LAST_RESULT_STATUS_METADATA_KEY, None)
+ task.updated_at = task.retired_at
+ self._save()
+ return True
+
@_serialize_task_mirror
def record_binding_recovery(
self,
@@ -1845,6 +1917,11 @@ class ScheduledTaskStore:
result_status: Optional[str] = None,
queued_run: Optional[dict[str, Any]] = None,
expected_uncanceled_run_id: Optional[str] = None,
+ expected_schedule_generation: Optional[dict[str, str]] = None,
+ expected_terminal_run_id: Optional[str] = None,
+ expected_non_owner_retired_one_shot: Optional[
+ DefinitionWriteExpectation
+ ] = None,
) -> bool:
"""Stamp a fire's outcome; ``False`` means the store refused the write.
@@ -1866,18 +1943,70 @@ class ScheduledTaskStore:
the fire being stamped has not been stopped -- see
``upsert_scheduled_task_with_queued_run``. Only meaningful alongside
``queued_run``, because it exists to stop a stopped run queuing an Agent turn.
+
+ ``expected_non_owner_retired_one_shot`` is the binding authority captured
+ before a marker-less manual or legacy Run started. Its presence means the Run
+ owns only its history and optional escalation outbox row, even if the user has
+ replaced the retired schedule before this result arrives.
"""
self.maybe_reload()
task = self._tasks.get(task_id)
if task is None:
return False
+ non_owner_expectation = expected_non_owner_retired_one_shot
+ if non_owner_expectation is None and (
+ expected_schedule_generation is None
+ and task.schedule_type == "at"
+ and task.retired_at is not None
+ ):
+ non_owner_expectation = self._read_state(task)
+ if non_owner_expectation is not None:
+ # A manual or legacy Run can still settle after a one-shot retires, but
+ # without the immutable consumed-generation marker it owns only its Run
+ # history. Keep every terminal definition fact byte-for-byte unchanged.
+ if queued_run is None:
+ return True
+ if self._sqlite is None:
+ raise ValueError(
+ "a file-backed scheduled task store cannot atomically enqueue "
+ "a task escalation"
+ )
+ try:
+ landed = self._sqlite.enqueue_task_escalation_without_definition_write(
+ task.id,
+ expect=non_owner_expectation,
+ expected_session_key=(
+ expected_binding[1]
+ if expected_binding is not None
+ else task.session_key
+ ),
+ run_payload=queued_run,
+ expected_uncanceled_run_id=str(expected_uncanceled_run_id or ""),
+ )
+ finally:
+ # A replacement may have committed after maybe_reload() above. The
+ # caller reconciles physical jobs immediately after this result.
+ self.load()
+ return landed
if expected_binding is not None and (
task.session_id,
task.session_key,
task.schedule_type,
) != expected_binding:
return False
+ if expected_schedule_generation is not None:
+ if (
+ expected_terminal_run_id is None
+ or task.schedule_type != "at"
+ or task.enabled
+ or task.run_at != expected_schedule_generation["run_at"]
+ or task.timezone != expected_schedule_generation["timezone"]
+ or task.retired_at != expected_schedule_generation["retired_at"]
+ or task.retirement_reason != TASK_RETIREMENT_SCHEDULE_CONSUMED
+ or task.last_run_id != expected_terminal_run_id
+ ):
+ return False
expect = self._read_state(task)
task.last_run_at = _utc_now_iso()
task.last_error = error
@@ -1916,8 +2045,16 @@ class ScheduledTaskStore:
# message task has none and must never blank what a command fire of the
# same definition recorded.
task.last_exit_code = int(exit_code)
- if disable_one_shot and task.schedule_type == "at":
+ # SQLite one-shots retire in the scheduler enqueue transaction, tied to
+ # the exact run_at/timezone that was consumed. A result arriving after
+ # the user replaces and resumes that schedule must not disable the new
+ # lifecycle. The legacy file backend has no atomic enqueue boundary, so
+ # it retains its result-time transition for compatibility.
+ if disable_one_shot and task.schedule_type == "at" and self._sqlite is None:
task.enabled = False
+ if task.retired_at is None:
+ task.retired_at = _utc_now_iso()
+ task.retirement_reason = TASK_RETIREMENT_SCHEDULE_CONSUMED
task.updated_at = _utc_now_iso()
# Same reasoning as ``record_binding_recovery``, and the same reason it must be
# guarded: this payload carries the mirror's ``session_id`` and ``enabled``, so
@@ -1928,6 +2065,8 @@ class ScheduledTaskStore:
expect,
queued_run=queued_run,
expected_uncanceled_run_id=expected_uncanceled_run_id,
+ expected_schedule_generation=expected_schedule_generation,
+ expected_terminal_run_id=expected_terminal_run_id,
)
@@ -2339,6 +2478,11 @@ class TaskExecutionStore:
source_kind: str = "cli",
task: Optional[ScheduledTask] = None,
suppress_scheduler_successor: bool = False,
+ expected_run_at: Optional[str] = None,
+ expected_timezone: Optional[str] = None,
+ expected_updated_at: Optional[str] = None,
+ expected_job_id: Optional[str] = None,
+ terminal_error: Optional[str] = None,
) -> Optional[TaskExecutionRequest]:
if task is None:
request = TaskExecutionRequest(
@@ -2382,6 +2526,15 @@ class TaskExecutionStore:
session_policy=task.session_policy,
metadata=metadata,
suppress_scheduler_successor=suppress_scheduler_successor,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=(
+ expected_updated_at
+ if expected_updated_at is not None
+ else task.updated_at if expected_run_at is not None else None
+ ),
+ expected_job_id=expected_job_id,
+ terminal_error=terminal_error,
)
def enqueue_definition_run(
@@ -2401,6 +2554,11 @@ class TaskExecutionStore:
parent_run_id: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
suppress_scheduler_successor: bool = False,
+ expected_run_at: Optional[str] = None,
+ expected_timezone: Optional[str] = None,
+ expected_updated_at: Optional[str] = None,
+ expected_job_id: Optional[str] = None,
+ terminal_error: Optional[str] = None,
) -> Optional[TaskExecutionRequest]:
request = TaskExecutionRequest(
id=uuid4().hex[:12],
@@ -2430,6 +2588,11 @@ class TaskExecutionStore:
snapshot = self._sqlite.enqueue_definition_run(
self.queued_run_payload(request),
suppress_scheduler_successor=suppress_scheduler_successor,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=expected_updated_at,
+ expected_job_id=expected_job_id,
+ terminal_error=terminal_error,
)
if snapshot is None:
return None
@@ -3301,6 +3464,7 @@ class TaskExecutionStore:
exit_code: Optional[int] = None,
stdout: Optional[str] = None,
stderr: Optional[str] = None,
+ timed_out: Optional[bool] = None,
escalation_run_id: Optional[str] = None,
) -> Optional[str]:
"""Settle one claimed request.
@@ -3340,6 +3504,8 @@ class TaskExecutionStore:
extra_metadata["interrupt_reason"] = interrupt_reason
if failure_code:
extra_metadata["failure_code"] = failure_code
+ if timed_out is not None:
+ extra_metadata[COMMAND_TIMED_OUT_METADATA_KEY] = bool(timed_out)
if escalation_run_id:
extra_metadata["escalation_run_id"] = escalation_run_id
if self._sqlite is not None:
@@ -3388,7 +3554,7 @@ class TaskExecutionStore:
payload["stdout"] = stdout
if stderr is not None:
payload["stderr"] = stderr
- if interrupt_reason or failure_code or escalation_run_id:
+ if interrupt_reason or failure_code or timed_out is not None or escalation_run_id:
# The file backend has no owed-notice machinery at all, so this records the
# class where its only reader — an operator looking at the completed JSON —
# can see it, rather than dropping the one fact the caller went to the
@@ -3400,6 +3566,11 @@ class TaskExecutionStore:
**(existing if isinstance(existing, dict) else {}),
**({"interrupt_reason": interrupt_reason} if interrupt_reason else {}),
**({"failure_code": failure_code} if failure_code else {}),
+ **(
+ {COMMAND_TIMED_OUT_METADATA_KEY: bool(timed_out)}
+ if timed_out is not None
+ else {}
+ ),
**({"escalation_run_id": escalation_run_id} if escalation_run_id else {}),
}
with tempfile.NamedTemporaryFile(
@@ -3858,6 +4029,9 @@ class ScheduledTaskService:
self.store = store or ScheduledTaskStore()
self.request_store = request_store or TaskExecutionStore()
self.scheduler = AsyncIOScheduler(timezone="UTC")
+ self.scheduler.add_listener(
+ self._on_scheduler_event, EVENT_JOB_MISSED | EVENT_JOB_ERROR
+ )
self._reconcile_task: Optional[asyncio.Task] = None
self._service_teardown_task: Optional["asyncio.Task[None]"] = None
self._request_recovery_token: RuntimeWorkRegistrationToken | None = None
@@ -3876,6 +4050,11 @@ class ScheduledTaskService:
# be torn down by name: cancelling the watch no longer stops it.
self._notice_drain_task: Optional["asyncio.Task[Any]"] = None
self._job_signatures: Dict[str, tuple[Any, ...]] = {}
+ # Logical Task id -> the physical APScheduler job generation. One-shot
+ # job ids are unique per registration so a queued event from a replaced
+ # DateTrigger cannot be mistaken for its successor.
+ self._job_ids: Dict[str, str] = {}
+ self._one_shot_job_identities: Dict[str, tuple[str, str, str, str]] = {}
self._running = False
self._watch_store_restart_count = 0
# Claimed requests currently executing, keyed by request id, so a
@@ -5419,8 +5598,9 @@ class ScheduledTaskService:
if not self._owns_service_instance():
return
desired_ids = set()
+ desired_job_ids = set()
for task in self.store.list_tasks():
- if not task.enabled:
+ if not task.enabled or task.retired_at is not None:
continue
desired_ids.add(task.id)
signature = (
@@ -5432,32 +5612,61 @@ class ScheduledTaskService:
task.session_key,
task.prompt,
task.enabled,
+ task.updated_at if task.schedule_type == "at" else None,
)
- if self._job_signatures.get(task.id) == signature and self.scheduler.get_job(task.id):
+ job_id = self._job_ids.get(task.id, task.id)
+ if self._job_signatures.get(task.id) == signature and self.scheduler.get_job(job_id):
+ desired_job_ids.add(job_id)
continue
- if self.scheduler.get_job(task.id):
- self.scheduler.remove_job(task.id)
+ if self.scheduler.get_job(job_id):
+ self.scheduler.remove_job(job_id)
+ self._one_shot_job_identities.pop(job_id, None)
try:
trigger = self._build_trigger(task)
+ job_id = (
+ f"{task.id}:at:{uuid4().hex[:12]}"
+ if task.schedule_type == "at"
+ else task.id
+ )
self.scheduler.add_job(
self._run_task,
trigger=trigger,
- id=task.id,
+ id=job_id,
replace_existing=True,
coalesce=True,
max_instances=1,
- args=[task.id],
+ args=[
+ task.id,
+ task.run_at if task.schedule_type == "at" else None,
+ task.timezone if task.schedule_type == "at" else None,
+ task.updated_at if task.schedule_type == "at" else None,
+ job_id,
+ ],
)
except Exception as exc:
self._job_signatures.pop(task.id, None)
+ self._job_ids.pop(task.id, None)
logger.error("Failed to reconcile scheduled task %s: %s", task.id, exc, exc_info=True)
continue
+ self._job_ids[task.id] = job_id
+ desired_job_ids.add(job_id)
+ if task.schedule_type == "at" and task.run_at:
+ self._one_shot_job_identities[job_id] = (
+ task.id,
+ task.run_at,
+ task.timezone,
+ task.updated_at,
+ )
self._job_signatures[task.id] = signature
for job in list(self.scheduler.get_jobs()):
- if job.id not in desired_ids:
+ if job.id not in desired_job_ids:
self.scheduler.remove_job(job.id)
- self._job_signatures.pop(job.id, None)
+ self._one_shot_job_identities.pop(job.id, None)
+ for task_id in set(self._job_ids) - desired_ids:
+ job_id = self._job_ids.pop(task_id)
+ self._one_shot_job_identities.pop(job_id, None)
+ self._job_signatures.pop(task_id, None)
def _build_trigger(self, task: ScheduledTask):
tz = ZoneInfo(task.timezone)
@@ -5473,21 +5682,182 @@ class ScheduledTaskService:
return DateTrigger(run_date=resolve_run_at(task.run_at, task.timezone))
raise ValueError(f"unknown schedule type: {task.schedule_type}")
- async def _run_task(self, task_id: str) -> None:
- if not self._owns_service_instance():
+ def _on_scheduler_event(self, event: JobExecutionEvent) -> None:
+ """Persist an APScheduler-observed one-shot misfire or callback failure.
+
+ A clock comparison cannot tell whether the scheduler consumed a fire.
+ Both paths re-assert the registered schedule identity, so an event queued
+ before an edit cannot terminalize the replacement definition.
+ """
+
+ job_id = str(event.job_id)
+ identity = self._one_shot_job_identities.get(job_id)
+ if identity is None:
return
- task = await self._run_runtime_sync(self.store.refresh_task, task_id)
- if not task or not task.enabled:
+ task_id, expected_run_at, expected_timezone, expected_updated_at = identity
+ try:
+ scheduled = resolve_run_at(expected_run_at, expected_timezone)
+ except Exception:
+ logger.warning(
+ "Ignoring scheduler event for task %s with an invalid registered run_at",
+ task_id,
+ exc_info=True,
+ )
return
- queued = await self._run_runtime_sync(
- self.request_store.enqueue_task_run,
+ if scheduled != event.scheduled_run_time:
+ logger.info(
+ "Ignoring stale scheduler event for task %s: event=%s registered=%s",
+ task_id,
+ event.scheduled_run_time,
+ scheduled,
+ )
+ return
+ changed = False
+ if event.code == EVENT_JOB_ERROR:
+ detail = str(event.exception or "unknown scheduler callback error")
+ changed = self._recover_failed_one_shot_fire(
+ task_id,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=expected_updated_at,
+ expected_job_id=job_id,
+ error=self._t("harness.task.schedulerCallbackFailed", detail=detail),
+ )
+ else:
+ self.store.refresh_task(task_id)
+ changed = self.store.retire_missed_one_shot(
+ task_id,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=expected_updated_at,
+ )
+ if changed:
+ self._job_signatures.pop(task_id, None)
+ _publish_task_definitions_updated()
+ if self._job_ids.get(task_id) == job_id:
+ self._job_ids.pop(task_id, None)
+ self._job_signatures.pop(task_id, None)
+ self._one_shot_job_identities.pop(job_id, None)
+ if not changed:
+ # refresh_task above consumed any cross-process invalidation. Return
+ # the refreshed desired row to the existing scheduler owner now that
+ # APScheduler has removed the stale DateTrigger that raised this event.
+ self.reconcile_jobs()
+
+ def _recover_failed_one_shot_fire(
+ self,
+ task_id: str,
+ *,
+ expected_run_at: str,
+ expected_timezone: str,
+ expected_updated_at: str,
+ expected_job_id: str,
+ error: str,
+ ) -> bool:
+ """Atomically retire an exact fire with a failed owner Run."""
+
+ task = self.store.refresh_task(task_id)
+ if (
+ task is None
+ or not task.enabled
+ or task.schedule_type != "at"
+ or task.run_at != expected_run_at
+ or task.timezone != expected_timezone
+ or task.updated_at != expected_updated_at
+ ):
+ return False
+ recovered = self.request_store.enqueue_task_run(
task.id,
source_kind="scheduler",
task=task,
suppress_scheduler_successor=True,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=expected_updated_at,
+ expected_job_id=expected_job_id,
+ terminal_error=error,
)
+ if recovered is None:
+ return False
+ self.store.load()
+ return True
+
+ async def _reconcile_rejected_one_shot_fire(self, task_id: str) -> None:
+ """Return a rejected DateTrigger callback to the existing scheduler owner."""
+
+ # The store invalidation may already have been consumed by the fallback
+ # loop before this callback observes the stale generation. Force a fresh
+ # mirror so reconciliation sees the replacement even in that ordering.
+ await self._run_runtime_sync(self.store.load)
+ self.reconcile_jobs()
+
+ async def _run_task(
+ self,
+ task_id: str,
+ expected_run_at: Optional[str] = None,
+ expected_timezone: Optional[str] = None,
+ expected_updated_at: Optional[str] = None,
+ expected_job_id: Optional[str] = None,
+ ) -> None:
+ if not self._owns_service_instance():
+ return
+ if expected_job_id is not None and self._job_ids.get(task_id) != expected_job_id:
+ if expected_run_at is not None:
+ await self._reconcile_rejected_one_shot_fire(task_id)
+ return
+ task = await self._run_runtime_sync(self.store.refresh_task, task_id)
+ if not task or not task.enabled:
+ if expected_run_at is not None:
+ await self._reconcile_rejected_one_shot_fire(task_id)
+ return
+ if expected_run_at is not None and (
+ task.schedule_type != "at"
+ or task.run_at != expected_run_at
+ or task.timezone != expected_timezone
+ or task.updated_at != expected_updated_at
+ ):
+ await self._reconcile_rejected_one_shot_fire(task_id)
+ return
+ try:
+ queued = await self._run_runtime_sync(
+ self.request_store.enqueue_task_run,
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ expected_run_at=expected_run_at,
+ expected_timezone=expected_timezone,
+ expected_updated_at=expected_updated_at,
+ expected_job_id=expected_job_id,
+ )
+ except Exception as exc:
+ if expected_run_at is None or expected_job_id is None:
+ raise
+ error = self._t(
+ "harness.task.schedulerCallbackFailed", detail=str(exc)
+ )
+ recovered = await self._run_runtime_sync(
+ self._recover_failed_one_shot_fire,
+ task.id,
+ expected_run_at=expected_run_at,
+ expected_timezone=str(expected_timezone),
+ expected_updated_at=str(expected_updated_at),
+ expected_job_id=expected_job_id,
+ error=error,
+ )
+ if recovered:
+ _publish_task_definitions_updated()
+ return
+ raise
if queued is not None:
+ if expected_run_at is not None:
+ # The SQLite enqueue atomically retired the definition with this
+ # Run. Reload the process mirror and wake open Workbench pages.
+ await self._run_runtime_sync(self.store.load)
+ _publish_task_definitions_updated()
self._wake_runtime_work(RuntimeWorkLane.REQUESTS)
+ elif expected_run_at is not None:
+ await self._reconcile_rejected_one_shot_fire(task_id)
def _request_partition_key(self, request: TaskExecutionRequest) -> str:
lock_key = self._execution_lock_key(request)
@@ -6991,15 +7361,9 @@ class ScheduledTaskService:
"""The lifecycle state the badge shows for this task — asked of the badge.
The authoritative answer is ``definition_lifecycle_state``, the same SQL CASE
- every list and count surface evaluates, so the notice copy and the badge share
- one clock and one parse of ``run_at`` — and one priority order: an in-flight
- execution outranks the ended predicate, so the caller sees ``running`` rather
- than a boolean that flattened it into "not finished". The Python inference
- below it is a FALLBACK for the file backend and for a row the read cannot
- reach: there is no SQL badge in those worlds to disagree with, and the
- inference asks the same question the projection encodes
- (``compute_next_run_at`` returns ``None`` exactly when the named instant is
- behind us, with ``enabled=True`` so the switch cannot mask the clock).
+ every list and count surface evaluates. An in-flight execution outranks the
+ persisted terminal marker, so the caller sees ``running`` while a consumed Run
+ is active. The Python fallback for the file backend follows the same facts.
"""
if definition_id:
@@ -7016,13 +7380,7 @@ class ScheduledTaskService:
state = None
if state is not None:
return state
- if task.schedule_type == "at" and not compute_next_run_at(
- enabled=True,
- schedule_type=task.schedule_type,
- cron=task.cron,
- run_at=task.run_at,
- timezone_name=task.timezone,
- ):
+ if task.schedule_type == "at" and task.retired_at is not None:
return "finished"
return "paused"
@@ -7824,19 +8182,38 @@ class ScheduledTaskService:
exit_code: Optional[int] = None
stdout: Optional[str] = None
stderr: Optional[str] = None
+ timed_out: Optional[bool] = None
#: The already-durable escalation turn a failed ``--on-failure agent`` command
#: fire queued, or ``None``. Recorded on THIS run's metadata by ``complete()``,
#: which is what stops the same failure being reported twice.
escalation_run_id: Optional[str] = None
try:
if request.request_type in {"task_run", "scheduled"}:
- self.store.maybe_reload()
+ # A scheduled one-shot is retired in the same SQLite transaction
+ # that created this Run. Only that transaction stamps the Run as
+ # its owner; cron fires keep the invalidation-aware fast path.
+ consumed_generation = task_schedule_generation(request.metadata)
+ consumed_one_shot = consumed_generation is not None
+ if consumed_one_shot:
+ self.store.load()
+ else:
+ self.store.maybe_reload()
task = self.store.get_task(request.task_id or "")
if task is None:
raise ValueError(f"task '{request.task_id}' not found")
task_id = task.id
session_key = task.session_key
session_id = task.session_id
+ if consumed_generation is not None and (
+ task.schedule_type != "at"
+ or task.enabled
+ or task.run_at != consumed_generation["run_at"]
+ or task.timezone != consumed_generation["timezone"]
+ or task.retired_at != consumed_generation["retired_at"]
+ or task.retirement_reason != TASK_RETIREMENT_SCHEDULE_CONSUMED
+ or task.last_run_id != request.id
+ ):
+ raise ValueError(self._t("harness.task.scheduleReplaced"))
task_agent_id = (
request.agent_id
if task.agent_name and task.agent_name == request.agent_name
@@ -7847,6 +8224,7 @@ class ScheduledTaskService:
execution_id=request.id,
disable_one_shot=request.source_kind == "scheduler",
agent_id=task_agent_id,
+ schedule_generation=consumed_generation,
)
error = result.error
session_key = result.session_key
@@ -7857,6 +8235,7 @@ class ScheduledTaskService:
exit_code = result.exit_code
stdout = result.stdout
stderr = result.stderr
+ timed_out = result.timed_out
escalation_run_id = result.escalation_run_id
elif request.request_type in {
"hook_send",
@@ -8028,6 +8407,7 @@ class ScheduledTaskService:
exit_code=exit_code,
stdout=stdout,
stderr=stderr,
+ timed_out=timed_out,
escalation_run_id=escalation_run_id,
)
# A STOP THAT NEVER BECAME A ``CancelledError``. ``cancel_run`` can
@@ -8174,7 +8554,12 @@ class ScheduledTaskService:
return str(row.get("workdir") or "").strip() or None
async def _execute_command_task(
- self, task: ScheduledTask, *, execution_id: str, disable_one_shot: bool
+ self,
+ task: ScheduledTask,
+ *,
+ execution_id: str,
+ disable_one_shot: bool,
+ schedule_generation: Optional[dict[str, str]] = None,
) -> TaskExecutionResult:
"""Run one command definition's fire and record its outcome.
@@ -8212,6 +8597,13 @@ class ScheduledTaskService:
# BEFORE anything can fail, and before the spawn: the enqueue predicted this
# command from the definition as it stood then, and the executor re-read the
# definition after claiming. This is the copy that will actually run.
+ non_owner_retired_expectation = (
+ self.store._read_state(task)
+ if schedule_generation is None
+ and task.schedule_type == "at"
+ and task.retired_at is not None
+ else None
+ )
self._record_executed_command(execution_id, task)
spawn_cwd = (
@@ -8397,6 +8789,11 @@ class ScheduledTaskService:
if escalation_request is not None
else None
),
+ expected_schedule_generation=schedule_generation,
+ expected_terminal_run_id=(
+ execution_id if schedule_generation is not None else None
+ ),
+ expected_non_owner_retired_one_shot=non_owner_retired_expectation,
)
# ONLY when the stamp landed. A refusal rolled the escalation row back with it,
# so claiming an escalation id here would suppress the failure notice in favour
@@ -8426,6 +8823,7 @@ class ScheduledTaskService:
exit_code=exit_code,
stdout=stdout_value,
stderr=stderr_value,
+ timed_out=timed_out,
escalation_run_id=escalation_run_id,
)
@@ -8491,6 +8889,7 @@ class ScheduledTaskService:
execution_id: str,
disable_one_shot: bool,
agent_id: Optional[str] = None,
+ schedule_generation: Optional[dict[str, str]] = None,
) -> TaskExecutionResult:
error: Optional[str] = None
complete_on_return = True
@@ -8512,7 +8911,10 @@ class ScheduledTaskService:
# there, in the same transaction as its result stamp -- it does not dispatch
# one from here.
return await self._execute_command_task(
- task, execution_id=execution_id, disable_one_shot=disable_one_shot
+ task,
+ execution_id=execution_id,
+ disable_one_shot=disable_one_shot,
+ schedule_generation=schedule_generation,
)
try:
if task.session_policy == "create_per_run":
@@ -8594,7 +8996,15 @@ class ScheduledTaskService:
except Exception as exc:
error = str(exc)
logger.error("Scheduled task %s failed: %s", task.id, exc, exc_info=True)
- if not self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot):
+ if not self.store.mark_task_result(
+ task.id,
+ error=error,
+ disable_one_shot=disable_one_shot,
+ expected_schedule_generation=schedule_generation,
+ expected_terminal_run_id=(
+ execution_id if schedule_generation is not None else None
+ ),
+ ):
# The TERMINAL STAMP was refused (HFR-261): the definition was reclaimed,
# repointed, soft-deleted or removed while this fire was running, so
# ``last_run_at`` / ``last_error`` / the one-shot disable are NOT stored.
@@ -9154,9 +9564,29 @@ class ScheduledTaskService:
definition_id,
)
return
+ metadata = run.get("metadata")
+ schedule_generation = task_schedule_generation(metadata)
+ legacy_consumed_marker = bool(
+ isinstance(metadata, dict)
+ and metadata.get(TASK_SCHEDULE_CONSUMED_METADATA_KEY)
+ and schedule_generation is None
+ )
+ if legacy_consumed_marker:
+ logger.warning(
+ "Run %s has no exact one-shot generation; skipping definition %s projection",
+ execution_id,
+ definition_id,
+ )
+ return
retire_one_shot = (
str(run.get("source_kind") or "") == "scheduler"
- and task.schedule_type == "at"
+ and (
+ schedule_generation is not None
+ or (
+ self.store.sqlite_backend is None
+ and task.schedule_type == "at"
+ )
+ )
)
# A COMMAND fire that ends here ended without reaching its own result stamp --
# cancelled, or interrupted by shutdown -- so this projection IS that fire's
@@ -9182,6 +9612,10 @@ class ScheduledTaskService:
task.session_key,
task.schedule_type,
),
+ expected_schedule_generation=schedule_generation,
+ expected_terminal_run_id=(
+ execution_id if schedule_generation is not None else None
+ ),
)
except Exception:
logger.exception(
@@ -9199,8 +9633,10 @@ class ScheduledTaskService:
return
if retire_one_shot:
try:
- if self.scheduler.get_job(task.id) is not None:
- self.scheduler.remove_job(task.id)
+ job_id = self._job_ids.pop(task.id, task.id)
+ if self.scheduler.get_job(job_id) is not None:
+ self.scheduler.remove_job(job_id)
+ self._one_shot_job_identities.pop(job_id, None)
self._job_signatures.pop(task.id, None)
except Exception:
logger.exception(
diff --git a/core/watches.py b/core/watches.py
index d627de229..169fb3ecc 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -789,7 +789,8 @@ class ManagedWatchStore:
return False
expect = self._read_state(watch)
watch.last_started_at = _utc_now_iso()
- watch.last_error = None
+ if watch.retired_at is None:
+ watch.last_error = None
watch.updated_at = _utc_now_iso()
# A runtime stamp: a lost write is reported by the return value, not by an
# exception through the supervisor loop.
@@ -832,8 +833,12 @@ class ManagedWatchStore:
if was_enabled:
watch.last_finished_at = now if disable or pause else None
watch.retired_at = now if disable else None
- watch.last_exit_code = exit_code
- watch.last_error = error
+ # Once retirement commits, these fields describe that terminal outcome.
+ # A late cycle still owns its individual Run row, but it cannot replace
+ # the definition outcome written by the cycle that retired the Watch.
+ if was_enabled or watch.retired_at is None:
+ watch.last_exit_code = exit_code
+ watch.last_error = error
if event_detected:
watch.last_event_at = now
if metadata_updates or (event_detected and acknowledge_event):
diff --git a/docs/plans/harness-lifecycle-facts.md b/docs/plans/harness-lifecycle-facts.md
new file mode 100644
index 000000000..2c12f7ebf
--- /dev/null
+++ b/docs/plans/harness-lifecycle-facts.md
@@ -0,0 +1,81 @@
+# Harness lifecycle facts
+
+Status: implemented for GitHub issue #1036. Diagnosis began against
+`origin/master` at `da10a846783a0aaa0932050db04a812d9667868d`.
+
+## Goal
+
+Make Task and Watch lifecycle state follow persisted transitions. A definition
+must not become paused or finished because a clock passed, an unrelated edit
+moved `updated_at`, or a later cycle overwrote the transition owner.
+
+## Current-head diagnosis
+
+- Pause time is deliberately absent from every projection. The UI renders the
+ paused state without a timestamp, and existing tests reject `updated_at` as a
+ pause time. No consumer needs `paused_at`, so this change preserves that
+ smaller invariant instead of adding unused state.
+- `run_at` already has one meaning at the two boundaries that interpret it: the
+ scheduler and next-fire projection share `resolve_run_at`, and naive values
+ use the definition's IANA timezone. Lifecycle rows and counts no longer infer
+ an outcome from that clock, so they do not duplicate conversion logic.
+- Before this change, one-shot Tasks became finished from a clock comparison. A manual early
+ run can therefore be mistaken for the scheduled outcome, and a missed fire
+ can look successful.
+- A late Watch cycle preserves retirement timestamps but can still overwrite
+ the exit code and error owned by the cycle that retired the Watch.
+- Definition writers already publish `definitions.updated` after successful
+ commits. New lifecycle writes must use the same notification.
+
+## Model
+
+`retired_at` remains the single definition terminal marker for both Tasks and
+Watches. A nullable `retirement_reason` only distinguishes Task terminal facts
+that cannot be reconstructed from run history:
+
+- `schedule_consumed`: the scheduler atomically consumed an `at` definition and
+ queued its Run;
+- `schedule_missed`: APScheduler emitted a real misfire for the current stored
+ one-shot schedule.
+
+The reason does not form a second state machine. Lifecycle remains
+`running | waiting | paused | finished`, declared once by the storage query.
+An in-flight Run outranks retirement, then `retired_at` determines `finished`.
+
+Manual `vibe task run` never writes either terminal fact. The scheduler enqueue
+transaction writes `schedule_consumed` together with the Run, so a crash cannot
+leave one without the other. Startup recovery relies on APScheduler's misfire
+event, not wall-clock inference; `schedule_missed` is therefore an observed
+scheduler outcome and never a fabricated success.
+
+Run completion does not own Task retirement. This matters when the user replaces
+and resumes a consumed schedule while its Run is still active: that late result
+may update run history, but cannot disable or retire the replacement schedule.
+
+A retired one-shot cannot be resumed in place: its old schedule has no future
+fire to restore. Both CLI and Workbench toggles reject that transition. Updating
+`run_at` or the schedule type first clears the terminal marker and creates the
+new lifecycle; unrelated edits preserve it.
+
+For Watches, once a retirement commits, `last_finished_at`, `last_exit_code`,
+and `last_error` are that terminal outcome. A late cycle cannot modify them.
+The cycle's individual Run remains the place where that cycle's own result is
+retained.
+
+## Migration
+
+Add nullable `run_definitions.retirement_reason` with no backfill. Existing
+`retired_at`, run history, `updated_at`, and wall-clock deadlines are not used to
+invent a reason. Legacy rows therefore remain unknown until a new lifecycle
+transition is observed and committed by its current owner. The one-time JSON
+import preserves terminal fields that are explicitly present, but never derives
+missing ones.
+
+## Evidence
+
+- Lifecycle contract: pause/resume/edit preservation, marker-driven Task rows
+ and counts, early manual run, naive `run_at` timezone agreement.
+- Scheduler scenario: atomic scheduled consumption and explicit missed-fire
+ recovery.
+- Watch concurrency contract: retirement outcome survives a late cycle result.
+- Migration: column addition and null legacy backfill.
diff --git a/docs/plans/harness-watch-task-readability.md b/docs/plans/harness-watch-task-readability.md
index dfcd2964c..78bd95a70 100644
--- a/docs/plans/harness-watch-task-readability.md
+++ b/docs/plans/harness-watch-task-readability.md
@@ -65,13 +65,15 @@ without a backfill; legacy disabled watches remain truthfully `paused`.
| `paused` | `enabled = 0` and it did **not** end on its own | 4 |
| `finished` | `enabled = 0` and it ended on its own | 1,228 |
-`paused` vs `finished`, per type:
+`paused` vs `finished`, per type. Follow-up issue #1036 replaced the Task
+wall-clock inference below with the same persisted `retired_at` fact used by
+Watches; the old measured count remains historical context only:
| Type | Rule for `finished` | Rows |
| --- | --- | ---: |
| watch, `mode = once` | `retired_at IS NOT NULL` | forward writes |
| watch, `mode = forever` | `retired_at IS NOT NULL` | forward writes |
-| scheduled, `schedule_type = at` | no future fire remains | 50 |
+| scheduled, `schedule_type = at` | `retired_at IS NOT NULL` | 50 (historical) |
| watch, `mode = once`, never fired | → `paused` | 2 |
| scheduled, `schedule_type = cron`, disabled | → `paused` | 2 |
@@ -99,12 +101,13 @@ list and detail for **both** `scheduled` and `watch` definitions.
```
lifecycle_state: 'running' | 'waiting' | 'paused' | 'finished'
-lifecycle_detail: 'normal' | 'timeout' | 'error' | null # non-null only when finished
+lifecycle_detail: 'normal' | 'timeout' | 'error' | 'missed' | null # non-null only when finished
next_run_at: string | null # ISO-8601; cron via APScheduler CronTrigger, one-shot = run_at
waiting_since: string | null # last_started_at, when waiting
running_since: string | null # started_at of the in-flight run, when running
process_alive: boolean | null # watches only; from the runtime:<watch_id> row. null = unknown
-retired_at: string | null # watches only; supervisor persisted retirement marker
+retired_at: string | null # persisted terminal transition for Tasks and Watches
+retirement_reason: 'schedule_consumed' | 'schedule_missed' | null # Tasks only
```
`running_since` was added during review, and is the one change to this frozen
@@ -122,10 +125,11 @@ show a real number:
counts: { running, waiting, paused, finished, total }
```
-**Non-goals.** The one nullable retirement marker and its forward-only migration
-are the complete schema change; there is no backfill and no inferred legacy
-retirement. The row **title** is computed client-side by reusing R1's fallback
-helper — it is deliberately not a server field.
+**Migration policy.** Neither retirement field is backfilled from edit times,
+run history, or elapsed wall-clock time. Legacy rows remain unknown. Issue #1036
+added the nullable Task reason because a consumed schedule and a missed schedule
+have different product outcomes that cannot be reconstructed from `retired_at`
+alone. The row **title** remains client-side.
### 3.2 Two write-side corrections review forced (behavior changes)
diff --git a/storage/alembic/versions/20260812_0053_run_definition_retirement_reason.py b/storage/alembic/versions/20260812_0053_run_definition_retirement_reason.py
new file mode 100644
index 000000000..bfadd777b
--- /dev/null
+++ b/storage/alembic/versions/20260812_0053_run_definition_retirement_reason.py
@@ -0,0 +1,41 @@
+"""persist the reason a run definition retired
+
+Revision ID: 20260812_0053
+Revises: 20260811_0052
+Create Date: 2026-08-12
+"""
+
+from __future__ import annotations
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "20260812_0053"
+down_revision = "20260811_0052"
+branch_labels = None
+depends_on = None
+
+
+def _columns() -> set[str]:
+ bind = op.get_bind()
+ return {
+ str(row[1])
+ for row in bind.exec_driver_sql(
+ 'pragma table_info("run_definitions")'
+ ).fetchall()
+ }
+
+
+def upgrade() -> None:
+ if "retirement_reason" not in _columns():
+ op.add_column(
+ "run_definitions",
+ sa.Column("retirement_reason", sa.String(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ if "retirement_reason" in _columns():
+ # SQLite before 3.35 needs the table-rebuild form of DROP COLUMN.
+ with op.batch_alter_table("run_definitions") as batch_op:
+ batch_op.drop_column("retirement_reason")
diff --git a/storage/background.py b/storage/background.py
index 22820e322..04494d9bf 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -64,6 +64,27 @@ logger = logging.getLogger(__name__)
CALLBACK_TERMINAL_TURN_ID_METADATA_KEY = "callback_terminal_turn_id"
RUN_LAST_ACTIVITY_METADATA_KEY = "last_activity_at"
+TASK_RETIREMENT_SCHEDULE_CONSUMED = "schedule_consumed"
+TASK_RETIREMENT_SCHEDULE_MISSED = "schedule_missed"
+TASK_SCHEDULE_CONSUMED_METADATA_KEY = "task_schedule_consumed"
+
+
+def task_schedule_generation(metadata: Any) -> Optional[dict[str, str]]:
+ """Return the exact one-shot generation owned by a scheduler Run.
+
+ Older Runs used a boolean marker. That proves only that some schedule was
+ consumed, not which generation owned the result, so it deliberately remains
+ unknown instead of being reconstructed from mutable definition history.
+ """
+
+ if not isinstance(metadata, dict):
+ return None
+ raw = metadata.get(TASK_SCHEDULE_CONSUMED_METADATA_KEY)
+ if not isinstance(raw, dict):
+ return None
+ fields = ("run_at", "timezone", "updated_at", "job_id", "retired_at")
+ generation = {field: str(raw.get(field) or "").strip() for field in fields}
+ return generation if all(generation.values()) else None
def _json_dumps(value: Any) -> str:
@@ -575,12 +596,29 @@ class TaskResumeBlocked(RuntimeError):
self.owner_session_id = str(owner_session_id)
+class TaskScheduleRetired(RuntimeError):
+ """A consumed or missed one-shot needs a new schedule before re-enabling."""
+
+ code = "task_schedule_retired"
+
+ def __init__(self, definition_id: str) -> None:
+ super().__init__(
+ f"task {definition_id} cannot be resumed because its one-shot schedule "
+ "has already retired"
+ )
+ self.definition_id = str(definition_id)
+
+
def require_task_resumable(
definition_id: str,
*,
metadata: Any,
session_id: Any,
+ schedule_type: Any = None,
+ retired_at: Any = None,
) -> None:
+ if str(schedule_type or "") == "at" and retired_at:
+ raise TaskScheduleRetired(definition_id)
blocked = task_resume_block(metadata, session_id)
if blocked is not None:
raise TaskResumeBlocked(definition_id, blocked["owner_session_id"])
@@ -784,6 +822,106 @@ def definition_state_unchanged(expect: DefinitionWriteExpectation) -> list[Any]:
]
+def definition_binding_authority_unchanged(
+ expect: DefinitionWriteExpectation,
+) -> list[Any]:
+ """Predicates proving a definition still grants the same delivery authority.
+
+ Unlike a full-row write, an outbox-only enqueue does not own the definition's
+ enabled switch. It still must refuse deletion, rebinding, reclaim snapshot
+ replacement, and Agent rename/archive so an old fire cannot start a turn under
+ authority the definition no longer grants.
+ """
+
+ return [
+ unchanged_text(run_definitions.c.session_id, expect.session_id),
+ unchanged_text(run_definitions.c.deleted_at, expect.deleted_at),
+ unchanged_text(_RECLAIM_SNAPSHOT_MARKER_SQL, expect.snapshot_captured_at),
+ unchanged_text(_AGENT_BINDING_REVISION_SQL, expect.agent_binding_revision),
+ ]
+
+
+def task_schedule_owner_unchanged(
+ generation: dict[str, str], run_id: str
+) -> list[Any]:
+ """Predicates proving a result still owns the consumed one-shot row."""
+
+ marker_path = f"$.{TASK_SCHEDULE_CONSUMED_METADATA_KEY}"
+ exact_owner_run = (
+ select(agent_runs.c.id)
+ .where(agent_runs.c.id == run_id)
+ .where(agent_runs.c.definition_id == run_definitions.c.id)
+ .where(agent_runs.c.source_kind == "scheduler")
+ .where(func.json_valid(agent_runs.c.metadata_json) == 1)
+ .where(func.json_type(agent_runs.c.metadata_json, marker_path) == "object")
+ .where(
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.run_at")
+ == generation["run_at"]
+ )
+ .where(
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.timezone")
+ == generation["timezone"]
+ )
+ .where(
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.updated_at")
+ == generation["updated_at"]
+ )
+ .where(
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.job_id")
+ == generation["job_id"]
+ )
+ .where(
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.retired_at")
+ == generation["retired_at"]
+ )
+ .exists()
+ )
+ return [
+ run_definitions.c.definition_type == "scheduled",
+ run_definitions.c.schedule_type == "at",
+ run_definitions.c.enabled == 0,
+ unchanged_text(run_definitions.c.run_at, generation["run_at"]),
+ unchanged_text(run_definitions.c.timezone, generation["timezone"]),
+ unchanged_text(run_definitions.c.retired_at, generation["retired_at"]),
+ run_definitions.c.retirement_reason == TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ run_definitions.c.last_run_id == run_id,
+ exact_owner_run,
+ ]
+
+
+def task_schedule_generation_matches_definition() -> list[Any]:
+ """SQL predicates accepting only a complete owner marker for this row."""
+
+ marker_path = f"$.{TASK_SCHEDULE_CONSUMED_METADATA_KEY}"
+ return [
+ func.json_type(agent_runs.c.metadata_json, marker_path) == "object",
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.run_at")
+ == run_definitions.c.run_at,
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.timezone")
+ == run_definitions.c.timezone,
+ func.json_extract(agent_runs.c.metadata_json, f"{marker_path}.retired_at")
+ == run_definitions.c.retired_at,
+ func.trim(
+ func.coalesce(
+ func.json_extract(
+ agent_runs.c.metadata_json, f"{marker_path}.updated_at"
+ ),
+ "",
+ )
+ )
+ != "",
+ func.trim(
+ func.coalesce(
+ func.json_extract(
+ agent_runs.c.metadata_json, f"{marker_path}.job_id"
+ ),
+ "",
+ )
+ )
+ != "",
+ ]
+
+
def definition_lifecycle_expression(definition_type: str):
"""The single declaration of a task/watch lifecycle state, as SQL.
@@ -800,10 +938,9 @@ def definition_lifecycle_expression(definition_type: str):
without giving it anything left to do, and reading the switch first parked
such a row in the default Active view forever.
- Both ``ended`` branches read a fact written by whatever ends the definition,
- never a proxy for one: a watch retires when its supervisor says so, and a
- one-shot when the clock passes the instant it names. A history column —
- "it has run at least once" — looks like either and is neither.
+ Both ``ended`` branches read ``retired_at``, the fact written by whoever
+ ends the definition. A history column or a deadline whose clock passed can
+ look like retirement, but neither proves that the schedule was consumed.
"""
in_flight = (
@@ -828,27 +965,14 @@ def definition_lifecycle_expression(definition_type: str):
run_definitions.c.retired_at.is_not(None),
)
else:
- # A cron task cannot retire itself, so a disabled one is always someone
- # having paused it. A one-shot is over when the instant it names has
- # passed — not when it last ran. ``vibe task run`` executes an armed
- # task early and records ``last_run_at`` without consuming the schedule,
- # so reading history here retired a task that was still going to fire.
- #
- # This is the same question ``compute_next_run_at`` answers — it returns
- # ``None`` exactly when the instant is behind us — so the state and the
- # time printed beside it cannot contradict each other.
- #
- # SQLite cannot resolve an IANA timezone and treats a naive timestamp as
- # UTC. The connection UDF delegates that resolution to the same stdlib
- # rule the scheduler uses, then compares two epoch values in UTC.
+ # A cron task cannot retire itself, so a disabled one without this marker
+ # is paused. For a one-shot, the scheduler stamps the marker either in the
+ # same transaction that queues its Run or from a real APScheduler misfire
+ # event. A manual early run writes only history and cannot consume the
+ # future schedule; wall-clock passage alone proves no outcome at all.
ended = and_(
run_definitions.c.schedule_type == "at",
- run_definitions.c.run_at.is_not(None),
- func.avibe_run_at_epoch(
- run_definitions.c.run_at,
- run_definitions.c.timezone,
- )
- <= (func.julianday("now") - literal(2440587.5)) * literal(86400.0),
+ run_definitions.c.retired_at.is_not(None),
)
return case(
(in_flight, "running"),
@@ -882,11 +1006,26 @@ def _successful_finished_definition_expression(definition_type: str, lifecycle:
no_error,
)
else:
+ consumed_run_status = (
+ select(agent_runs.c.status)
+ .where(agent_runs.c.id == run_definitions.c.last_run_id)
+ .where(agent_runs.c.definition_id == run_definitions.c.id)
+ .where(agent_runs.c.source_kind == "scheduler")
+ .where(func.json_valid(agent_runs.c.metadata_json) == 1)
+ .where(*task_schedule_generation_matches_definition())
+ .limit(1)
+ .scalar_subquery()
+ )
successful_one_shot = and_(
run_definitions.c.schedule_type == "at",
- run_definitions.c.enabled == 0,
- run_definitions.c.last_run_at.is_not(None),
- no_error,
+ run_definitions.c.retired_at.is_not(None),
+ run_definitions.c.retirement_reason
+ == TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ run_definitions.c.last_run_id.is_not(None),
+ func.coalesce(
+ consumed_run_status.in_(_status_query_values("succeeded")),
+ False,
+ ),
)
return and_(lifecycle == "finished", successful_one_shot)
@@ -895,12 +1034,14 @@ def _successful_finished_definition_expression(definition_type: str, lifecycle:
# went, and what it caught.
DEFINITION_RETIREMENT_COLUMNS = (
"retired_at",
+ "retirement_reason",
"last_finished_at",
"last_exit_code",
"last_error",
)
DEFINITION_CYCLE_COLUMNS = (
"retired_at",
+ "retirement_reason",
"last_started_at",
"last_finished_at",
"last_event_at",
@@ -975,13 +1116,17 @@ def definition_lifecycle_detail(
last_exit_code: Any = None,
last_error: Any = None,
timed_out: Optional[bool] = None,
+ retirement_reason: Optional[str] = None,
+ terminal_run_status: Optional[str] = None,
+ terminal_run_exit_code: Any = None,
+ terminal_run_timed_out: Optional[bool] = None,
) -> Optional[str]:
- """How a finished task/watch ended: ``normal``, ``timeout``, or ``error``.
+ """How a finished task/watch ended.
Non-null only for ``finished``; the other three states are still in play and
have no ending to report yet. Python rather than SQL because it has exactly
one consumer — the row — and never a ``GROUP BY``: the filter groups by
- state, and the row alone says which of the three endings it was.
+ state, and the row alone says how the definition ended.
``timed_out`` is THE ANSWER for scheduled tasks when the row has one. 124 is
the code the runner synthesizes for a limit it enforced itself, but it is also
@@ -995,8 +1140,27 @@ def definition_lifecycle_detail(
if lifecycle_state != "finished":
return None
- if definition_type == "scheduled" and last_run_at is None:
- return None
+ if definition_type == "scheduled":
+ if retirement_reason == TASK_RETIREMENT_SCHEDULE_MISSED:
+ return "missed"
+ if retirement_reason != TASK_RETIREMENT_SCHEDULE_CONSUMED:
+ # A legacy retirement has no owner. Prior manual history cannot prove
+ # what consumed this schedule or how that terminal execution ended.
+ return None
+ status = normalize_run_status(terminal_run_status)
+ if status == "succeeded":
+ return "normal"
+ if status == "canceled":
+ return "canceled"
+ if status != "failed":
+ return None
+ if terminal_run_timed_out:
+ return "timeout"
+ if terminal_run_timed_out is None and terminal_run_exit_code == _TIMEOUT_EXIT_CODE:
+ return "timeout"
+ # The owning Run's terminal status is the outcome even when a damaged or
+ # legacy writer omitted its human-readable error text.
+ return "error"
if timed_out:
return "timeout"
if definition_type != "scheduled" and timed_out is None and last_exit_code == _TIMEOUT_EXIT_CODE:
@@ -2990,6 +3154,7 @@ def upsert_definition_in_connection(
*,
expect: DefinitionWriteExpectation | None,
definition_type: str,
+ extra_predicates: Sequence[Any] = (),
) -> bool:
"""The one full-row ``run_definitions`` write, guarded, in a CALLER'S transaction.
@@ -3013,6 +3178,8 @@ def upsert_definition_in_connection(
# (pysqlite emits no ``BEGIN`` for a bare SELECT), so the lock is first taken
# here.
stmt = stmt.where(*definition_state_unchanged(expect))
+ if extra_predicates:
+ stmt = stmt.where(*extra_predicates)
result = conn.execute(stmt.values(**values))
if result.rowcount:
return True
@@ -3180,6 +3347,8 @@ class SQLiteBackgroundTaskStore:
expect: DefinitionWriteExpectation | None = None,
expected_enabled_agent_id: Optional[str] = None,
expected_reference_agent_id: Optional[str] = None,
+ expected_schedule_generation: Optional[dict[str, str]] = None,
+ expected_terminal_run_id: Optional[str] = None,
) -> bool:
"""Write a whole scheduled-task row. ``False`` means the write was REFUSED.
@@ -3195,6 +3364,14 @@ class SQLiteBackgroundTaskStore:
definition_type="scheduled task",
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ extra_predicates=(
+ task_schedule_owner_unchanged(
+ expected_schedule_generation, expected_terminal_run_id
+ )
+ if expected_schedule_generation is not None
+ and expected_terminal_run_id is not None
+ else ()
+ ),
)
def upsert_scheduled_task_with_binding_notice(
@@ -3258,6 +3435,8 @@ class SQLiteBackgroundTaskStore:
select(
run_definitions.c.definition_type,
run_definitions.c.mode,
+ run_definitions.c.schedule_type,
+ run_definitions.c.retired_at,
run_definitions.c.enabled,
run_definitions.c.session_id,
run_definitions.c.metadata_json,
@@ -3274,6 +3453,8 @@ class SQLiteBackgroundTaskStore:
definition_id,
metadata=_json_loads(current["metadata_json"], {}),
session_id=current["session_id"],
+ schedule_type=current["schedule_type"],
+ retired_at=current["retired_at"],
)
clear_columns = definition_resume_clear_columns(
current["definition_type"], current["mode"]
@@ -3298,6 +3479,59 @@ class SQLiteBackgroundTaskStore:
result = conn.execute(stmt)
return bool(result.rowcount)
+ def retire_missed_one_shot(
+ self,
+ definition_id: str,
+ *,
+ expected_run_at: str,
+ expected_timezone: str,
+ expected_updated_at: str,
+ retired_at: Optional[str] = None,
+ ) -> bool:
+ """Persist one APScheduler-owned missed ``at`` transition.
+
+ The schedule identity is part of the compare-and-set. A stale misfire
+ event from a job that was edited cannot retire the replacement schedule.
+ """
+
+ now = retired_at or _utc_now_iso()
+ metadata_without_result = case(
+ (
+ func.json_valid(run_definitions.c.metadata_json) == 1,
+ func.json_remove(
+ run_definitions.c.metadata_json,
+ f"$.{COMMAND_TIMED_OUT_METADATA_KEY}",
+ f"$.{TASK_LAST_RESULT_STATUS_METADATA_KEY}",
+ ),
+ ),
+ else_=run_definitions.c.metadata_json,
+ )
+ with self.engine.begin() as conn:
+ result = conn.execute(
+ update(run_definitions)
+ .where(run_definitions.c.id == definition_id)
+ .where(run_definitions.c.definition_type == "scheduled")
+ .where(run_definitions.c.schedule_type == "at")
+ .where(run_definitions.c.enabled != 0)
+ .where(run_definitions.c.deleted_at.is_(None))
+ .where(run_definitions.c.retired_at.is_(None))
+ .where(run_definitions.c.run_at == expected_run_at)
+ .where(run_definitions.c.timezone == expected_timezone)
+ .where(run_definitions.c.updated_at == expected_updated_at)
+ .values(
+ enabled=0,
+ retired_at=now,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_MISSED,
+ last_run_at=None,
+ last_run_id=None,
+ last_error=None,
+ last_exit_code=None,
+ metadata_json=metadata_without_result,
+ updated_at=now,
+ )
+ )
+ return bool(result.rowcount)
+
def list_watches(self) -> list[dict[str, Any]]:
stmt = self._definitions_query("watch").order_by(
run_definitions.c.created_at, run_definitions.c.id
@@ -3391,6 +3625,7 @@ class SQLiteBackgroundTaskStore:
definition_type: str,
expected_enabled_agent_id: Optional[str] = None,
expected_reference_agent_id: Optional[str] = None,
+ extra_predicates: Sequence[Any] = (),
) -> bool:
"""The one full-row ``run_definitions`` write, guarded once for both types."""
@@ -3410,7 +3645,11 @@ class SQLiteBackgroundTaskStore:
)
values["agent_name"] = identity["name"]
return upsert_definition_in_connection(
- conn, values, expect=expect, definition_type=definition_type
+ conn,
+ values,
+ expect=expect,
+ definition_type=definition_type,
+ extra_predicates=extra_predicates,
)
def upsert_watch_with_queued_run(
@@ -3481,6 +3720,8 @@ class SQLiteBackgroundTaskStore:
expect: DefinitionWriteExpectation | None,
run_payload: dict[str, Any],
expected_uncanceled_run_id: Optional[str] = None,
+ expected_schedule_generation: Optional[dict[str, str]] = None,
+ expected_terminal_run_id: Optional[str] = None,
) -> bool:
"""A guarded task stamp and the outbox row it authorises, ONE transaction.
@@ -3533,6 +3774,14 @@ class SQLiteBackgroundTaskStore:
values,
expect=expect,
definition_type="scheduled task",
+ extra_predicates=(
+ task_schedule_owner_unchanged(
+ expected_schedule_generation, expected_terminal_run_id
+ )
+ if expected_schedule_generation is not None
+ and expected_terminal_run_id is not None
+ else ()
+ ),
):
return False
_pin_run_to_definition_agent(
@@ -3541,6 +3790,77 @@ class SQLiteBackgroundTaskStore:
enqueue_run_in_connection(conn, run_values)
return True
+ def enqueue_task_escalation_without_definition_write(
+ self,
+ definition_id: str,
+ *,
+ expect: DefinitionWriteExpectation,
+ expected_session_key: str,
+ run_payload: dict[str, Any],
+ expected_uncanceled_run_id: str,
+ ) -> bool:
+ """Atomically enqueue a non-owner failure escalation, never its definition.
+
+ A manual or legacy Run of a retired one-shot owns its Run history and this
+ outbox decision, but owns no definition projection. The write lock makes the
+ authority check and enqueue one decision while allowing a concurrent schedule
+ replacement to survive byte-for-byte.
+ """
+
+ parent_run_id = str(expected_uncanceled_run_id or "").strip()
+ if not parent_run_id:
+ return False
+ run_values = self._run_values(run_payload)
+ with run_update_event_transaction(self.engine) as conn:
+ reserve_write_lock(conn)
+ parent = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.cancel_requested)
+ .where(agent_runs.c.id == parent_run_id)
+ .limit(1)
+ ).mappings().first()
+ if parent is None or bool(parent["cancel_requested"]) or normalize_run_status(
+ parent["status"]
+ ) == "canceled":
+ return False
+ definition = conn.execute(
+ select(run_definitions.c.agent_name)
+ .where(run_definitions.c.id == definition_id)
+ .where(run_definitions.c.definition_type == "scheduled")
+ .where(
+ unchanged_text(
+ run_definitions.c.legacy_session_key,
+ expected_session_key,
+ )
+ )
+ .where(*definition_binding_authority_unchanged(expect))
+ .limit(1)
+ ).mappings().first()
+ if definition is None:
+ return False
+ _pin_run_to_definition_agent(
+ conn,
+ run_values,
+ agent_name=definition["agent_name"],
+ )
+ pinned_agent_id = str(run_values.get("agent_id") or "").strip()
+ current_agent_name = str(definition["agent_name"] or "").strip()
+ if current_agent_name and not pinned_agent_id:
+ return False
+ if pinned_agent_id:
+ try:
+ identity = _require_agent_reference_identity(
+ conn,
+ expected_agent_id=pinned_agent_id,
+ )
+ except ValueError:
+ return False
+ if current_agent_name and identity["name"] != current_agent_name:
+ return False
+ run_values["agent_id"] = identity["id"]
+ run_values["agent_name"] = identity["name"]
+ enqueue_run_in_connection(conn, run_values)
+ return True
+
def enqueue_run(
self,
payload: dict[str, Any],
@@ -3641,38 +3961,32 @@ class SQLiteBackgroundTaskStore:
payload: dict[str, Any],
*,
suppress_scheduler_successor: bool = False,
+ expected_run_at: Optional[str] = None,
+ expected_timezone: Optional[str] = None,
+ expected_updated_at: Optional[str] = None,
+ expected_job_id: Optional[str] = None,
+ terminal_error: Optional[str] = None,
) -> Optional[dict[str, Any]]:
"""Enqueue one internally consistent snapshot of a live definition."""
+ if (expected_run_at is None) != (expected_timezone is None):
+ raise ValueError("expected run_at and timezone must be supplied together")
+ if (expected_run_at is None) != (expected_updated_at is None):
+ raise ValueError(
+ "expected run_at and definition updated_at must be supplied together"
+ )
+ if (expected_run_at is None) != (expected_job_id is None):
+ raise ValueError(
+ "expected run_at and scheduler job id must be supplied together"
+ )
+ if terminal_error is not None and expected_run_at is None:
+ raise ValueError("a terminal enqueue error requires a one-shot identity")
values = self._run_values(payload)
definition_id = str(values.get("definition_id") or "").strip()
if not definition_id:
raise ValueError("definition id is required")
with run_update_event_transaction(self.engine) as conn:
reserve_write_lock(conn)
- if suppress_scheduler_successor:
- unstarted = conn.execute(
- select(agent_runs.c.id)
- .where(agent_runs.c.definition_id == definition_id)
- .where(agent_runs.c.source_kind == "scheduler")
- .where(
- or_(
- agent_runs.c.status.in_(_status_query_values("queued")),
- and_(
- agent_runs.c.status.in_(_status_query_values("running")),
- agent_runs.c.delivery_id.is_(None),
- agent_runs.c.pid.is_(None),
- func.json_extract(
- agent_runs.c.metadata_json,
- f"$.{COMMAND_WORKER_METADATA_KEY}",
- ).is_(None),
- ),
- )
- )
- .limit(1)
- ).scalar_one_or_none()
- if unstarted is not None:
- return None
definition = conn.execute(
select(
run_definitions.c.definition_type,
@@ -3688,6 +4002,11 @@ class SQLiteBackgroundTaskStore:
run_definitions.c.metadata_json,
run_definitions.c.command_json,
run_definitions.c.shell_command,
+ run_definitions.c.schedule_type,
+ run_definitions.c.run_at,
+ run_definitions.c.timezone,
+ run_definitions.c.updated_at,
+ run_definitions.c.retired_at,
run_definitions.c.enabled,
run_definitions.c.deleted_at,
)
@@ -3697,8 +4016,43 @@ class SQLiteBackgroundTaskStore:
if definition is not None:
if definition["deleted_at"] is not None:
raise ValueError(f"definition '{definition_id}' not found")
- if not bool(definition["enabled"]):
+ scheduled_one_shot = bool(
+ values.get("source_kind") == "scheduler"
+ and definition["definition_type"] == "scheduled"
+ and definition["schedule_type"] == "at"
+ )
+ expects_one_shot = expected_run_at is not None
+ if expects_one_shot and not scheduled_one_shot:
+ # The caller is an APScheduler DateTrigger generation. If the
+ # definition now names cron (or another kind), that generation
+ # is stale and owns no enqueue at all.
+ return None
+ if scheduled_one_shot and expected_run_at is None:
+ raise ValueError(
+ "scheduler one-shot enqueue requires its expected run_at and timezone"
+ )
+ if (
+ scheduled_one_shot and definition["retired_at"] is not None
+ ):
+ return None
+ manual_retired_one_shot = bool(
+ values.get("source_kind") in {"cli", "manual"}
+ and definition["definition_type"] == "scheduled"
+ and definition["schedule_type"] == "at"
+ and definition["retired_at"] is not None
+ )
+ if not bool(definition["enabled"]) and not manual_retired_one_shot:
raise ValueError(f"definition '{definition_id}' is disabled")
+ if (
+ scheduled_one_shot
+ and expected_run_at is not None
+ and (
+ definition["run_at"] != expected_run_at
+ or definition["timezone"] != expected_timezone
+ or definition["updated_at"] != expected_updated_at
+ )
+ ):
+ return None
current_name = str(definition["agent_name"] or "").strip() or None
identity = _resolve_agent_identity_by_name(conn, current_name)
@@ -3706,6 +4060,9 @@ class SQLiteBackgroundTaskStore:
metadata = _json_loads(definition["metadata_json"], {})
if not isinstance(metadata, dict):
metadata = {}
+ # Internal Run provenance: a definition's free-form metadata
+ # cannot claim that this enqueue owned the lifecycle transition.
+ metadata.pop(TASK_SCHEDULE_CONSUMED_METADATA_KEY, None)
# A run is an immutable record of one execution, so WHAT it executed
# belongs on it -- the definition it came from is editable and
# deletable, and the failure-notice drain reads long after the fire.
@@ -3732,6 +4089,118 @@ class SQLiteBackgroundTaskStore:
message_payload_json=definition["message_payload_json"],
metadata_json=_json_dumps(metadata),
)
+ if suppress_scheduler_successor:
+ unstarted_stmt = (
+ select(agent_runs.c.id)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(agent_runs.c.source_kind == "scheduler")
+ .where(
+ or_(
+ agent_runs.c.status.in_(_status_query_values("queued")),
+ and_(
+ agent_runs.c.status.in_(_status_query_values("running")),
+ agent_runs.c.delivery_id.is_(None),
+ agent_runs.c.pid.is_(None),
+ func.json_extract(
+ agent_runs.c.metadata_json,
+ f"$.{COMMAND_WORKER_METADATA_KEY}",
+ ).is_(None),
+ ),
+ )
+ )
+ )
+ if expected_run_at is not None:
+ marker_path = f"$.{TASK_SCHEDULE_CONSUMED_METADATA_KEY}"
+ unstarted_stmt = (
+ unstarted_stmt.where(func.json_valid(agent_runs.c.metadata_json) == 1)
+ .where(func.json_type(agent_runs.c.metadata_json, marker_path) == "object")
+ .where(
+ func.json_extract(
+ agent_runs.c.metadata_json, f"{marker_path}.run_at"
+ )
+ == expected_run_at
+ )
+ .where(
+ func.json_extract(
+ agent_runs.c.metadata_json, f"{marker_path}.timezone"
+ )
+ == expected_timezone
+ )
+ .where(
+ func.json_extract(
+ agent_runs.c.metadata_json, f"{marker_path}.updated_at"
+ )
+ == expected_updated_at
+ )
+ .where(
+ func.json_extract(
+ agent_runs.c.metadata_json, f"{marker_path}.job_id"
+ )
+ == expected_job_id
+ )
+ )
+ if conn.execute(unstarted_stmt.limit(1)).scalar_one_or_none() is not None:
+ return None
+ schedule_consumed = bool(
+ definition is not None
+ and scheduled_one_shot
+ and expected_run_at is not None
+ )
+ if schedule_consumed:
+ now = _utc_now_iso()
+ consumed = conn.execute(
+ update(run_definitions)
+ .where(run_definitions.c.id == definition_id)
+ .where(run_definitions.c.enabled != 0)
+ .where(run_definitions.c.definition_type == "scheduled")
+ .where(run_definitions.c.schedule_type == "at")
+ .where(run_definitions.c.deleted_at.is_(None))
+ .where(run_definitions.c.retired_at.is_(None))
+ .where(
+ and_(
+ run_definitions.c.run_at == expected_run_at,
+ run_definitions.c.timezone == expected_timezone,
+ run_definitions.c.updated_at == expected_updated_at,
+ )
+ )
+ .values(
+ enabled=0,
+ retired_at=now,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ last_run_id=values["id"],
+ updated_at=now,
+ )
+ )
+ if not consumed.rowcount:
+ return None
+ run_metadata = _json_loads(values["metadata_json"], {})
+ if not isinstance(run_metadata, dict):
+ run_metadata = {}
+ run_metadata[TASK_SCHEDULE_CONSUMED_METADATA_KEY] = {
+ "run_at": expected_run_at,
+ "timezone": expected_timezone,
+ "updated_at": expected_updated_at,
+ "job_id": expected_job_id,
+ "retired_at": now,
+ }
+ values["metadata_json"] = _json_dumps(run_metadata)
+ if terminal_error is not None:
+ values.update(
+ status="failed",
+ error=terminal_error,
+ completed_at=now,
+ updated_at=now,
+ )
+ _merge_owed_failure_notice(
+ values,
+ conn=conn,
+ run_id=str(values["id"]),
+ status=values["status"],
+ source_kind=values.get("source_kind"),
+ parent_run_id=values.get("parent_run_id"),
+ row_metadata_json=values["metadata_json"],
+ now=now,
+ )
enqueue_run_in_connection(conn, values)
return {
"agent_name": values["agent_name"],
@@ -4274,6 +4743,52 @@ class SQLiteBackgroundTaskStore:
stmt = stmt.where(or_(*(field.like(pattern, escape=_LIKE_ESCAPE) for field in fields)))
return stmt
+ @staticmethod
+ def _schedule_consuming_runs(
+ conn: Any,
+ definition_ids: Iterable[str],
+ ) -> dict[str, dict[str, Any]]:
+ """Exact Run that atomically consumed each one-shot schedule generation."""
+
+ ids = [str(value or "").strip() for value in dict.fromkeys(definition_ids)]
+ ids = [value for value in ids if value]
+ owners: dict[str, dict[str, Any]] = {}
+ for batch in _id_batches(ids):
+ rows = conn.execute(
+ select(
+ agent_runs.c.id,
+ run_definitions.c.id.label("definition_id"),
+ agent_runs.c.status,
+ agent_runs.c.completed_at,
+ agent_runs.c.exit_code,
+ agent_runs.c.error,
+ agent_runs.c.metadata_json,
+ )
+ .select_from(
+ run_definitions.join(
+ agent_runs,
+ agent_runs.c.id == run_definitions.c.last_run_id,
+ )
+ )
+ .where(run_definitions.c.id.in_(batch))
+ .where(agent_runs.c.definition_id == run_definitions.c.id)
+ .where(agent_runs.c.source_kind == "scheduler")
+ .where(func.json_valid(agent_runs.c.metadata_json) == 1)
+ .where(*task_schedule_generation_matches_definition())
+ ).mappings()
+ for row in rows:
+ definition_id = str(row["definition_id"] or "")
+ metadata = _json_loads(row["metadata_json"], {})
+ owners[definition_id] = {
+ "id": row["id"],
+ "status": normalize_run_status(row["status"]),
+ "completed_at": row["completed_at"],
+ "exit_code": row["exit_code"],
+ "error": row["error"],
+ "timed_out": _definition_timed_out(metadata),
+ }
+ return owners
+
def _definition_counts(
self,
definition_type: str,
@@ -8123,7 +8638,8 @@ class SQLiteBackgroundTaskStore:
"updated_at": payload.get("updated_at") or payload.get("created_at"),
"last_started_at": None,
"last_finished_at": None,
- "retired_at": None,
+ "retired_at": payload.get("retired_at"),
+ "retirement_reason": payload.get("retirement_reason"),
"last_event_at": None,
"last_run_at": payload.get("last_run_at"),
"last_run_id": payload.get("last_run_id"),
@@ -8169,6 +8685,7 @@ class SQLiteBackgroundTaskStore:
"last_started_at": payload.get("last_started_at"),
"last_finished_at": payload.get("last_finished_at"),
"retired_at": payload.get("retired_at"),
+ "retirement_reason": None,
"last_event_at": payload.get("last_event_at"),
"last_run_at": None,
"last_run_id": None,
@@ -8259,6 +8776,8 @@ class SQLiteBackgroundTaskStore:
"updated_at": row["updated_at"],
"last_run_at": row["last_run_at"],
"last_run_id": row["last_run_id"],
+ "retired_at": row["retired_at"],
+ "retirement_reason": row["retirement_reason"],
"last_error": row["last_error"],
"metadata": metadata,
"resume_blocked": task_resume_block(metadata, row["session_id"]),
@@ -8293,6 +8812,7 @@ class SQLiteBackgroundTaskStore:
"last_started_at": row["last_started_at"],
"last_finished_at": row["last_finished_at"],
"retired_at": row["retired_at"],
+ "retirement_reason": row["retirement_reason"],
"last_event_at": row["last_event_at"],
"last_error": row["last_error"],
"last_exit_code": row["last_exit_code"],
@@ -8445,6 +8965,20 @@ class SQLiteBackgroundTaskStore:
conn=conn,
),
)
+ consuming_runs: dict[str, dict[str, Any]] = {}
+ if definition_type == "scheduled":
+ consuming_runs = _lookup(
+ "schedule-consuming runs",
+ lambda: self._schedule_consuming_runs(
+ conn,
+ [
+ row.get("id")
+ for row in rows
+ if row.get("retirement_reason")
+ == TASK_RETIREMENT_SCHEDULE_CONSUMED
+ ],
+ ),
+ )
if any(row.get("lifecycle_state") == "running" for row in rows):
started = _lookup(
"in-flight run starts",
@@ -8516,6 +9050,18 @@ class SQLiteBackgroundTaskStore:
row["consecutive_failures"] = row_health["consecutive_failures"]
row["recent_failures"] = row_health["recent_failures"]
state = row.get("lifecycle_state")
+ consuming_run = consuming_runs.get(row.get("id") or "")
+ if (
+ definition_type == "scheduled"
+ and row.get("retirement_reason")
+ == TASK_RETIREMENT_SCHEDULE_CONSUMED
+ ):
+ # Once consumed, this definition's terminal outcome is the exact
+ # Run the enqueue transaction named in last_run_id. Earlier manual
+ # history remains on its own Run rows but cannot describe this ending.
+ row["last_run_at"] = (consuming_run or {}).get("completed_at")
+ row["last_exit_code"] = (consuming_run or {}).get("exit_code")
+ row["last_error"] = (consuming_run or {}).get("error")
row["lifecycle_detail"] = definition_lifecycle_detail(
lifecycle_state=state,
definition_type=definition_type,
@@ -8523,7 +9069,20 @@ class SQLiteBackgroundTaskStore:
last_exit_code=row.get("last_exit_code"),
last_error=row.get("last_error"),
timed_out=_definition_timed_out(row.get("metadata")),
+ retirement_reason=row.get("retirement_reason"),
+ terminal_run_status=(consuming_run or {}).get("status"),
+ terminal_run_exit_code=(consuming_run or {}).get("exit_code"),
+ terminal_run_timed_out=(consuming_run or {}).get("timed_out"),
)
+ if definition_type == "scheduled":
+ if row.get("retirement_reason") == TASK_RETIREMENT_SCHEDULE_CONSUMED:
+ row["lifecycle_finished_at"] = (consuming_run or {}).get(
+ "completed_at"
+ )
+ else:
+ row["lifecycle_finished_at"] = row.get("retired_at")
+ else:
+ row["lifecycle_finished_at"] = row.get("last_finished_at")
row["next_run_at"] = compute_next_run_at(
enabled=bool(row.get("enabled")),
schedule_type=row.get("schedule_type"),
diff --git a/storage/db.py b/storage/db.py
index 6b90c0406..d6fc0525c 100644
--- a/storage/db.py
+++ b/storage/db.py
@@ -7,7 +7,6 @@ from sqlalchemy import Engine, create_engine, event
from sqlalchemy.engine import URL
from config import paths
-from storage.sqlite_semantics import sqlite_run_at_epoch
def escape_sql_like(value: str) -> str:
@@ -37,12 +36,6 @@ def create_sqlite_engine(db_path: Path | None = None) -> Engine:
@event.listens_for(engine, "connect")
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
- dbapi_connection.create_function(
- "avibe_run_at_epoch",
- 2,
- sqlite_run_at_epoch,
- deterministic=True,
- )
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode = WAL")
cursor.execute("PRAGMA foreign_keys = ON")
diff --git a/storage/importer.py b/storage/importer.py
index f597858f7..e1d42f071 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -495,6 +495,8 @@ def _import_scheduled_tasks(conn: Connection, source: Path) -> int:
updated_at=item.get("updated_at") or item.get("created_at") or _utc_now_iso(),
last_started_at=None,
last_finished_at=None,
+ retired_at=item.get("retired_at"),
+ retirement_reason=item.get("retirement_reason"),
last_event_at=None,
last_run_at=item.get("last_run_at"),
last_error=item.get("last_error"),
@@ -546,6 +548,8 @@ def _import_watches(conn: Connection, source: Path) -> int:
updated_at=item.get("updated_at") or item.get("created_at") or _utc_now_iso(),
last_started_at=item.get("last_started_at"),
last_finished_at=item.get("last_finished_at"),
+ retired_at=item.get("retired_at"),
+ retirement_reason=None,
last_event_at=item.get("last_event_at"),
last_run_at=None,
last_error=item.get("last_error"),
diff --git a/storage/migrations.py b/storage/migrations.py
index 7a8e896cf..55c43c26c 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -114,6 +114,8 @@ PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS = {
},
}
HEAD_REQUIRED_COLUMNS = PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS | {
+ "run_definitions": PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS["run_definitions"]
+ | {"retirement_reason"},
"agent_sessions": PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS["agent_sessions"]
| {
"composer_draft_text",
@@ -502,6 +504,7 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->
"message_payload_json": "TEXT",
"last_run_id": "VARCHAR",
"retired_at": "VARCHAR",
+ "retirement_reason": "VARCHAR",
}.items():
if column not in definition_columns:
conn.execute(f'alter table "run_definitions" add column "{column}" {column_type}')
diff --git a/storage/models.py b/storage/models.py
index f4c870b0b..9da23c63f 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -222,6 +222,7 @@ run_definitions = Table(
Column("last_started_at", String, nullable=True),
Column("last_finished_at", String, nullable=True),
Column("retired_at", String, nullable=True),
+ Column("retirement_reason", String, nullable=True),
Column("last_event_at", String, nullable=True),
Column("last_run_at", String, nullable=True),
Column("last_error", Text, nullable=True),
diff --git a/storage/sqlite_semantics.py b/storage/sqlite_semantics.py
index 758308b66..6062643d8 100644
--- a/storage/sqlite_semantics.py
+++ b/storage/sqlite_semantics.py
@@ -10,9 +10,7 @@ with no dependencies of its own. One function, two importers, zero drift.
from __future__ import annotations
import re
-from datetime import datetime
from typing import Any
-from zoneinfo import ZoneInfo
_INT64_MAX = 2**63 - 1
_INT64_MIN = -(2**63)
@@ -63,25 +61,3 @@ def sqlite_cast_integer(raw: Any) -> int:
if match is None or not match.group(2):
return 0
return min(max(int(match.group(1) + match.group(2)), _INT64_MIN), _INT64_MAX)
-
-
-def sqlite_run_at_epoch(run_at: Any, timezone_name: Any) -> float | None:
- """Resolve a one-shot wall clock exactly like the scheduler does.
-
- SQLite's ``datetime()`` treats an offset-free timestamp as UTC and cannot
- resolve IANA timezone names. Scheduled tasks do carry an IANA timezone, so
- lifecycle queries use this connection-local function instead of silently
- reading the same ``run_at`` as a different instant than APScheduler.
-
- ``None`` is the SQL-friendly invalid-input result: it makes the lifecycle
- predicate false and leaves the row visible rather than retiring a schedule
- whose instant cannot be proved.
- """
-
- try:
- zone = ZoneInfo(str(timezone_name or "UTC"))
- instant = datetime.fromisoformat(str(run_at))
- resolved = instant.replace(tzinfo=zone) if instant.tzinfo is None else instant.astimezone(zone)
- return resolved.timestamp()
- except (KeyError, OSError, TypeError, ValueError, OverflowError):
- return None
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index c057d8e42..0bea418d0 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -4285,6 +4285,42 @@ scenarios:
# Turn's sole initial accepted input. Steered or coalesced participants settle
# locally, skip their callback, and leave the shared Session Turn untouched.
test: tests/test_internal_server.py::test_hfr_476_run_cancel_does_not_stop_a_shared_turn
+ - id: HFR-477
+ name: one-shot Task schedule consumption is explicit and atomic
+ status: covered
+ kind: lifecycle
+ layer: contract
+ backend: shared
+ # A manual early run leaves the future schedule armed. The scheduler writes
+ # retired_at and schedule_consumed in the same transaction as its Run; the
+ # definition points at that exact consuming Run for terminal status, time, and
+ # compact-list success. The consuming Run retains the registered run_at,
+ # timezone, definition revision, physical job id, and retirement time. That
+ # exact identity rejects stale enqueue, execution, successor suppression, and
+ # result writes after replacement. A manual rerun of a retired one-shot adds
+ # only CLI Run history, while a callback failure before enqueue atomically
+ # records a failed owner Run and retires the exact schedule generation.
+ test: tests/test_scheduled_tasks.py::test_hfr_477_scheduler_consumes_one_shot_atomically_but_manual_run_does_not
+ - id: HFR-478
+ name: missed one-shot recovery records the exact observed schedule
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # APScheduler's physical job generation retains its registered run_at,
+ # timezone, and definition revision. The misfire records schedule_missed only
+ # while all still match an enabled at schedule; an event from a replacement
+ # that resolves to the same instant still cannot retire it.
+ test: tests/test_scheduled_tasks.py::test_hfr_478_misfire_retires_only_the_schedule_apscheduler_observed
+ - id: HFR-479
+ name: Watch retirement outcome has one cycle owner
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ # A late cycle preserves the already-committed retired_at, finished time,
+ # exit code, and error while retaining its own individual Run history.
+ test: tests/test_watches.py::test_hfr_479_late_cycle_cannot_replace_committed_watch_terminal_outcome
- id: HFR-480
name: persisted Run activity exposes missing live ownership
status: covered
diff --git a/tests/test_cli_definition_read_projection.py b/tests/test_cli_definition_read_projection.py
index 96c5de350..7d1ae8c0c 100644
--- a/tests/test_cli_definition_read_projection.py
+++ b/tests/test_cli_definition_read_projection.py
@@ -5,7 +5,11 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import select, update
-from storage.background import SQLiteBackgroundTaskStore
+from storage.background import (
+ SQLiteBackgroundTaskStore,
+ TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ TASK_SCHEDULE_CONSUMED_METADATA_KEY,
+)
from storage.models import agent_runs, run_definitions
from storage.pagination import PageRequest
from vibe import cli
@@ -17,6 +21,7 @@ PAST = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
CANONICAL_FIELDS = (
"lifecycle_state",
"lifecycle_detail",
+ "lifecycle_finished_at",
"next_run_at",
"waiting_since",
"running_since",
@@ -287,7 +292,7 @@ def test_task_list_pagination_is_stable_across_run_at_boundary(capsys) -> None:
store.close()
-def test_task_list_does_not_hide_an_enabled_one_shot_after_manual_run(capsys) -> None:
+def test_task_list_and_show_keep_unverifiable_retirements_unknown(capsys) -> None:
store = SQLiteBackgroundTaskStore()
try:
_task(
@@ -301,18 +306,84 @@ def test_task_list_does_not_hide_an_enabled_one_shot_after_manual_run(capsys) ->
)
_task(
store,
- "scheduler-completed",
+ "legacy-ownerless",
schedule_type="at",
cron=None,
run_at=PAST,
enabled=False,
last_run_at=NOW,
+ retired_at=NOW,
+ )
+ _task(
+ store,
+ "consumed-owner-missing",
+ schedule_type="at",
+ cron=None,
+ run_at=PAST,
+ enabled=False,
+ last_run_at=NOW,
+ last_run_id="missing-owner",
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ )
+ _task(
+ store,
+ "consumed-owner-success",
+ schedule_type="at",
+ cron=None,
+ run_at=PAST,
+ enabled=False,
+ last_run_id="successful-owner",
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ )
+ store.enqueue_run(
+ {
+ "id": "successful-owner",
+ "definition_id": "consumed-owner-success",
+ "request_type": "scheduled",
+ "source_kind": "scheduler",
+ "status": "succeeded",
+ "created_at": NOW,
+ "updated_at": NOW,
+ "completed_at": NOW,
+ "metadata": {
+ TASK_SCHEDULE_CONSUMED_METADATA_KEY: {
+ "run_at": PAST,
+ "timezone": "UTC",
+ "updated_at": "registered-generation",
+ "job_id": "successful-job",
+ "retired_at": NOW,
+ }
+ },
+ }
)
- assert cli.cmd_task_list(page_request=PageRequest(limit=20)) == 0
+ assert cli.cmd_task_list(
+ include_finished=True,
+ page_request=PageRequest(limit=20),
+ ) == 0
rows = json.loads(capsys.readouterr().out)["definitions"]
- assert [row["id"] for row in rows] == ["manual-run"]
- assert rows[0]["lifecycle_state"] == "finished"
+ by_id = {row["id"]: row for row in rows}
+ assert set(by_id) == {
+ "manual-run",
+ "legacy-ownerless",
+ "consumed-owner-missing",
+ "consumed-owner-success",
+ }
+ assert by_id["manual-run"]["lifecycle_state"] == "waiting"
+ for task_id in ("legacy-ownerless", "consumed-owner-missing"):
+ assert by_id[task_id]["lifecycle_state"] == "finished"
+ assert by_id[task_id]["lifecycle_detail"] is None
+ assert by_id[task_id]["state"] == "unknown"
+ assert cli.cmd_task_show(task_id) == 0
+ shown = json.loads(capsys.readouterr().out)["definition"]
+ assert (shown["lifecycle_detail"], shown["state"]) == (None, "unknown")
+ assert by_id["consumed-owner-success"]["lifecycle_detail"] == "normal"
+ assert by_id["consumed-owner-success"]["state"] == "completed"
+ assert cli.cmd_task_show("consumed-owner-success") == 0
+ shown = json.loads(capsys.readouterr().out)["definition"]
+ assert (shown["lifecycle_detail"], shown["state"]) == ("normal", "completed")
finally:
store.close()
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index afee0182a..728c147a2 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -154,6 +154,43 @@ def test_task_resume_rejects_orphaned_owner_without_execution_target(
assert cli.ScheduledTaskStore().get_task(task.id).enabled is False
+def test_task_resume_rejects_retired_one_shot_until_schedule_changes(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = cli.ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at="2026-08-11T00:00:00+00:00",
+ timezone_name="UTC",
+ )
+ task.enabled = False
+ task.retired_at = "2026-08-11T00:00:01+00:00"
+ task.retirement_reason = "schedule_missed"
+ store.upsert_task(task)
+
+ with patch("vibe.cli._task_store", return_value=store):
+ result, payload = _capture_stderr_json(
+ cli.cmd_task_set_enabled,
+ task.id,
+ True,
+ )
+
+ assert result == 1
+ assert payload["code"] == "task_schedule_retired"
+ assert payload["details"] == {"task_id": task.id}
+ saved = cli.ScheduledTaskStore().get_task(task.id)
+ assert saved is not None
+ assert saved.enabled is False
+ assert saved.retirement_reason == "schedule_missed"
+
+
def test_task_update_preserves_archived_agent_reference(capsys) -> None:
db_path = cli.paths.get_sqlite_state_path()
agent_store = cli.VibeAgentStore(db_path)
@@ -1236,6 +1273,7 @@ def test_task_run_missing_id_returns_guidance(tmp_path: Path) -> None:
def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys) -> None:
store = cli.ScheduledTaskStore()
+ requests = cli.TaskExecutionStore()
store.add_task(
session_key="slack::channel::C123",
prompt="recurring",
@@ -1250,7 +1288,18 @@ def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys)
run_at="2026-03-31T09:00:00+08:00",
timezone_name="Asia/Shanghai",
)
- store.mark_task_result(done.id, error=None)
+ done_run = requests.enqueue_task_run(
+ done.id,
+ source_kind="scheduler",
+ task=done,
+ expected_run_at=done.run_at,
+ expected_timezone=done.timezone,
+ expected_job_id="done-job",
+ )
+ assert done_run is not None
+ claimed_done = requests.claim(done_run.id)
+ assert claimed_done is not None
+ assert requests.complete(claimed_done, ok=True) == "succeeded"
failed = store.add_task(
session_key="slack::channel::C123",
prompt="failed one-shot",
@@ -1258,7 +1307,20 @@ def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys)
run_at="2026-03-31T10:00:00+08:00",
timezone_name="Asia/Shanghai",
)
- store.mark_task_result(failed.id, error="delivery failed")
+ failed_run = requests.enqueue_task_run(
+ failed.id,
+ source_kind="scheduler",
+ task=failed,
+ expected_run_at=failed.run_at,
+ expected_timezone=failed.timezone,
+ expected_job_id="failed-job",
+ )
+ assert failed_run is not None
+ claimed_failed = requests.claim(failed_run.id)
+ assert claimed_failed is not None
+ assert requests.complete(
+ claimed_failed, ok=False, error="delivery failed"
+ ) == "failed"
with patch("vibe.cli._task_store", return_value=store):
result = cli.cmd_task_list()
@@ -1558,6 +1620,48 @@ def test_task_run_enqueues_request(tmp_path: Path, capsys) -> None:
assert (request_root / "pending" / f"{payload['execution_id']}.json").exists()
+def test_task_run_enqueues_manual_rerun_for_retired_one_shot(
+ tmp_path: Path, monkeypatch, capsys
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = cli.ScheduledTaskStore()
+ requests = cli.TaskExecutionStore()
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="hello",
+ schedule_type="at",
+ run_at="2026-03-31T09:00:00+08:00",
+ timezone_name="Asia/Shanghai",
+ )
+ owner = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert owner is not None
+ store.load()
+ retired = store.get_task(task.id)
+ terminal = (retired.retired_at, retired.retirement_reason, retired.last_run_id)
+
+ with (
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli._task_request_store", return_value=requests),
+ ):
+ result = cli.cmd_task_run(task.id)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ manual = requests.get_run(payload["execution_id"])
+ assert manual is not None and manual["source_kind"] == "cli"
+ assert "task_schedule_consumed" not in manual["metadata"]
+ current = cli.ScheduledTaskStore().get_task(task.id)
+ assert current is not None and current.enabled is False
+ assert (current.retired_at, current.retirement_reason, current.last_run_id) == terminal
+
+
def test_task_update_requires_at_least_one_change(tmp_path: Path) -> None:
store_path = tmp_path / "scheduled_tasks.json"
store = cli.ScheduledTaskStore(store_path)
diff --git a/tests/test_harness_definition_lifecycle.py b/tests/test_harness_definition_lifecycle.py
index 24a52d9ae..246ab2927 100644
--- a/tests/test_harness_definition_lifecycle.py
+++ b/tests/test_harness_definition_lifecycle.py
@@ -29,12 +29,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from storage import workbench_sessions_service
from storage.background import (
+ COMMAND_TIMED_OUT_METADATA_KEY,
DEFINITION_CYCLE_COLUMNS,
DEFINITION_RETIREMENT_COLUMNS,
DEFINITION_STATUS_COUNTS,
DEFINITION_STATUS_FILTERS,
NO_EVENT_EXIT_CODE,
SQLiteBackgroundTaskStore,
+ TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ TASK_RETIREMENT_SCHEDULE_MISSED,
+ TASK_LAST_RESULT_STATUS_METADATA_KEY,
+ TaskScheduleRetired,
_id_batches,
compute_next_run_at,
definition_lifecycle_detail,
@@ -48,9 +53,8 @@ from storage.settings_service import upsert_scope
NOW = "2026-07-26T00:00:00+00:00"
-# A one-shot's state is now a question about the clock, so these two are
-# relative to the real one: the SQL compares ``run_at`` against SQLite's
-# ``now``, and a fixed literal would decide the answer by the calendar.
+# Next-fire projection still compares the schedule to the real clock. Lifecycle
+# itself reads persisted retirement and never interprets these timestamps.
FUTURE = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()
PAST = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
@@ -201,14 +205,81 @@ def test_process_alive_tells_a_dead_waiter_from_one_never_seen(store) -> None:
assert died["runtime"]["running"] is False
-def test_a_disabled_cron_task_is_paused_and_a_fired_one_shot_is_finished(store) -> None:
[email protected]("definition_type", ["scheduled", "watch"])
+def test_pause_resume_and_edit_never_publish_an_inferred_pause_time(
+ store,
+ definition_type: str,
+) -> None:
+ """Pause is a state without a timestamp until the product needs that fact."""
+
+ definition_id = f"paused-{definition_type}"
+ if definition_type == "scheduled":
+ _task(store, definition_id, enabled=False, updated_at="2026-07-27T00:00:00+00:00")
+ else:
+ _watch(store, definition_id, enabled=False, updated_at="2026-07-27T00:00:00+00:00")
+ get = store.get_scheduled_task if definition_type == "scheduled" else store.get_watch
+ row = get(definition_id)
+ assert row["lifecycle_state"] == "paused"
+ assert "paused_at" not in row
+
+ assert store.set_definition_enabled(
+ definition_id,
+ True,
+ definition_type=definition_type,
+ )
+ assert store.set_definition_enabled(
+ definition_id,
+ False,
+ definition_type=definition_type,
+ )
+ if definition_type == "scheduled":
+ _task(
+ store,
+ definition_id,
+ name="renamed Friday",
+ enabled=False,
+ updated_at="2026-07-31T00:00:00+00:00",
+ )
+ else:
+ _watch(
+ store,
+ definition_id,
+ name="renamed Friday",
+ enabled=False,
+ updated_at="2026-07-31T00:00:00+00:00",
+ )
+ row = get(definition_id)
+ assert row["lifecycle_state"] == "paused"
+ assert "paused_at" not in row
+
+
+def test_disabled_definitions_need_a_persisted_retirement_fact_to_be_finished(store) -> None:
"""A cron task cannot retire itself, so switching one off is always a pause.
- A one-shot whose scheduled instant is past is done whichever way its switch
- points; the switch cannot create another fire."""
+ A one-shot is finished only after its scheduler owner persisted retirement;
+ a legacy row with no marker remains an honest pause rather than gaining a
+ fabricated outcome from its deadline."""
_task(store, "cron-off", enabled=False)
_task(store, "cron-on")
- _task(store, "one-shot-fired-off", schedule_type="at", run_at=PAST, enabled=False, last_run_at=NOW)
- _task(store, "one-shot-fired-on", schedule_type="at", run_at=PAST, enabled=True, last_run_at=NOW)
+ _task(
+ store,
+ "one-shot-fired-off",
+ schedule_type="at",
+ run_at=PAST,
+ enabled=False,
+ last_run_at=NOW,
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ )
+ _task(
+ store,
+ "one-shot-fired-on",
+ schedule_type="at",
+ run_at=PAST,
+ enabled=True,
+ last_run_at=NOW,
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ )
_task(store, "one-shot-pending", schedule_type="at", run_at="2099-01-01T00:00:00+00:00", enabled=False)
states = {task["id"]: task["lifecycle_state"] for task in store.list_scheduled_tasks()}
@@ -340,7 +411,7 @@ def test_only_a_finished_row_reports_an_ending(state) -> None:
assert definition_lifecycle_detail(lifecycle_state=state, last_exit_code=1, last_error="boom") is None
-def test_a_missed_one_shot_without_run_evidence_claims_no_ending() -> None:
+def test_a_legacy_one_shot_without_owner_evidence_claims_no_ending() -> None:
assert (
definition_lifecycle_detail(
lifecycle_state="finished",
@@ -359,7 +430,59 @@ def test_a_missed_one_shot_without_run_evidence_claims_no_ending() -> None:
last_exit_code=None,
last_error=None,
)
- == "normal"
+ is None
+ )
+
+
+def test_legacy_consumed_one_shot_without_owner_stays_visible_in_compact(store) -> None:
+ """Unknown legacy ownership must not be backfilled into a successful ending."""
+
+ _task(
+ store,
+ "legacy-consumed",
+ schedule_type="at",
+ cron=None,
+ run_at=PAST,
+ enabled=False,
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ last_run_at=NOW,
+ last_run_id=None,
+ )
+
+ row = store.get_scheduled_task("legacy-consumed")
+ assert row["lifecycle_detail"] is None
+ assert row["last_run_at"] is None
+ compact = store.list_scheduled_tasks_page(
+ page_request=PageRequest(limit=20),
+ include_successful_finished=False,
+ )
+ assert {item["id"] for item in compact.items} == {"legacy-consumed"}
+
+
+ ("status", "exit_code", "timed_out", "expected"),
+ [
+ ("succeeded", None, None, "normal"),
+ ("canceled", None, None, "canceled"),
+ ("failed", 1, False, "error"),
+ ("failed", 124, False, "error"),
+ ("failed", 124, True, "timeout"),
+ ],
+)
+def test_consumed_one_shot_ending_comes_from_its_owner_run(
+ status, exit_code, timed_out, expected
+) -> None:
+ assert (
+ definition_lifecycle_detail(
+ lifecycle_state="finished",
+ definition_type="scheduled",
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ terminal_run_status=status,
+ terminal_run_exit_code=exit_code,
+ terminal_run_timed_out=timed_out,
+ )
+ == expected
)
@@ -797,8 +920,8 @@ def test_a_forever_watch_retired_by_its_lifetime_says_it_timed_out(store) -> Non
) == "timeout"
-def test_a_legacy_scheduled_task_exit_124_requires_the_explicit_timeout_fact() -> None:
- """A command may return 124 itself; missing timeout metadata is generic."""
+def test_a_legacy_scheduled_task_exit_124_claims_no_terminal_outcome() -> None:
+ """Neither exit 124 nor old result text proves who consumed the schedule."""
assert (
definition_lifecycle_detail(
lifecycle_state="finished",
@@ -808,11 +931,11 @@ def test_a_legacy_scheduled_task_exit_124_requires_the_explicit_timeout_fact() -
last_error="command returned status 124",
timed_out=None,
)
- == "error"
+ is None
)
-def test_re_enabling_a_fired_one_shot_task_does_not_make_it_waiting_again(store) -> None:
+def test_re_enabling_a_retired_one_shot_task_does_not_make_it_waiting_again(store) -> None:
"""``enabled`` is not a promise of a future fire.
Switching a one-shot back on leaves its ``run_at`` in the past, so
@@ -820,7 +943,16 @@ def test_re_enabling_a_fired_one_shot_task_does_not_make_it_waiting_again(store)
history parked such a task in the default Active view forever, inflating the
badge with a row that will never run.
"""
- _task(store, "fired-then-re-enabled", schedule_type="at", run_at=NOW, enabled=True, last_run_at=NOW)
+ _task(
+ store,
+ "fired-then-re-enabled",
+ schedule_type="at",
+ run_at=NOW,
+ enabled=True,
+ last_run_at=NOW,
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ )
assert store.get_scheduled_task("fired-then-re-enabled")["lifecycle_state"] == "finished"
assert compute_next_run_at(
@@ -845,19 +977,87 @@ def test_running_a_future_one_shot_by_hand_leaves_it_waiting(store) -> None:
) is not None
-def test_a_one_shot_whose_moment_has_passed_is_finished_even_if_it_never_ran(store) -> None:
- """The instant is the fact, not the run history.
-
- A task whose moment went by while the service was down has nothing left to
- do, and saying *waiting* would promise a fire that can never come.
- """
+def test_a_past_one_shot_without_a_recovery_fact_stays_nonterminal(store) -> None:
+ """Wall-clock passage cannot manufacture a successful or missed outcome."""
_task(store, "missed-it", schedule_type="at", run_at=PAST, enabled=True, last_run_at=None)
- assert store.get_scheduled_task("missed-it")["lifecycle_state"] == "finished"
+ row = store.get_scheduled_task("missed-it")
+ assert row["lifecycle_state"] == "waiting"
+ assert row["lifecycle_detail"] is None
assert compute_next_run_at(
enabled=True, schedule_type="at", cron=None, run_at=PAST, timezone_name="UTC"
) is None
+ assert store.retire_missed_one_shot(
+ "missed-it",
+ expected_run_at=PAST,
+ expected_timezone="UTC",
+ expected_updated_at=NOW,
+ retired_at=NOW,
+ )
+ row = store.get_scheduled_task("missed-it")
+ assert row["lifecycle_state"] == "finished"
+ assert row["lifecycle_detail"] == "missed"
+ assert row["last_run_at"] is None
+
+
+def test_schedule_missed_clears_prior_manual_result_mirrors_but_keeps_run_history(
+ store,
+) -> None:
+ """HFR-478 -- a missed schedule cannot borrow an earlier manual failure."""
+
+ _task(
+ store,
+ "missed-after-manual-failure",
+ schedule_type="at",
+ run_at=FUTURE,
+ enabled=True,
+ last_run_at=NOW,
+ last_run_id="manual-failure",
+ last_error="manual run failed",
+ last_exit_code=7,
+ metadata={
+ "keep": "definition policy",
+ COMMAND_TIMED_OUT_METADATA_KEY: False,
+ TASK_LAST_RESULT_STATUS_METADATA_KEY: "failed",
+ },
+ )
+ store.enqueue_run(
+ {
+ "id": "manual-failure",
+ "definition_id": "missed-after-manual-failure",
+ "request_type": "scheduled",
+ "source_kind": "cli",
+ "status": "failed",
+ "created_at": NOW,
+ "updated_at": NOW,
+ "completed_at": NOW,
+ "error": "manual run failed",
+ "exit_code": 7,
+ }
+ )
+
+ assert store.retire_missed_one_shot(
+ "missed-after-manual-failure",
+ expected_run_at=FUTURE,
+ expected_timezone="UTC",
+ expected_updated_at=NOW,
+ retired_at=NOW,
+ )
+
+ row = store.get_scheduled_task("missed-after-manual-failure")
+ assert row["lifecycle_detail"] == "missed"
+ assert (row["last_run_at"], row["last_run_id"]) == (None, None)
+ assert (row["last_error"], row["last_exit_code"]) == (None, None)
+ assert row["metadata"] == {"keep": "definition policy"}
+ historical = store.get_run("manual-failure")
+ assert historical is not None
+ assert (historical["status"], historical["error"], historical["exit_code"]) == (
+ "failed",
+ "manual run failed",
+ 7,
+ )
+
def test_pausing_a_one_shot_before_its_moment_is_a_pause(store) -> None:
"""Switched off with the instant still ahead: the user's doing, and undoable."""
@@ -866,14 +1066,18 @@ def test_pausing_a_one_shot_before_its_moment_is_a_pause(store) -> None:
assert store.get_scheduled_task("held-back")["lifecycle_state"] == "paused"
-def test_one_shot_states_and_counts_agree_on_the_clock(store) -> None:
- """Whatever the clock decides, the chips and the rows decide it together.
-
- Both read ``definition_lifecycle_expression``; this pins that the ``at``
- branch's time comparison survives the trip through ``GROUP BY``.
- """
+def test_one_shot_states_and_counts_agree_on_persisted_retirement(store) -> None:
+ """Rows and counts share the same terminal fact, never the wall clock."""
_task(store, "ahead", schedule_type="at", run_at=FUTURE, enabled=True, last_run_at=NOW)
- _task(store, "behind", schedule_type="at", run_at=PAST, enabled=True)
+ _task(
+ store,
+ "behind",
+ schedule_type="at",
+ run_at=PAST,
+ enabled=False,
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_MISSED,
+ )
_task(store, "paused-ahead", schedule_type="at", run_at=FUTURE, enabled=False)
page = store.list_scheduled_tasks_page(page_request=PageRequest(limit=50))
@@ -884,8 +1088,8 @@ def test_one_shot_states_and_counts_agree_on_the_clock(store) -> None:
assert (counts["waiting"], counts["finished"], counts["paused"]) == (1, 1, 1)
-def test_naive_one_shot_uses_its_task_timezone_in_rows_counts_and_next_fire(store) -> None:
- """Offset-free ``run_at`` has one meaning across SQL and the scheduler."""
+def test_naive_one_shot_uses_its_task_timezone_for_the_next_fire_only(store) -> None:
+ """Offset-free ``run_at`` has one owner; lifecycle never reinterprets it."""
now_utc = datetime.now(timezone.utc)
los_angeles = ZoneInfo("America/Los_Angeles")
@@ -910,12 +1114,40 @@ def test_naive_one_shot_uses_its_task_timezone_in_rows_counts_and_next_fire(stor
rows = {row["id"]: row for row in store.list_scheduled_tasks()}
assert rows["naive-ahead"]["lifecycle_state"] == "waiting"
- assert rows["naive-behind"]["lifecycle_state"] == "finished"
+ assert rows["naive-behind"]["lifecycle_state"] == "waiting"
assert rows["naive-ahead"]["next_run_at"] is not None
assert rows["naive-behind"]["next_run_at"] is None
counts = store.count_scheduled_tasks()
- assert (counts["waiting"], counts["finished"]) == (1, 1)
+ assert (counts["waiting"], counts["finished"]) == (2, 0)
+
+
+def test_retired_one_shot_requires_a_new_schedule_before_resume(store) -> None:
+ """Every toggle doorway preserves the terminal marker and disabled switch."""
+
+ _task(
+ store,
+ "retired",
+ schedule_type="at",
+ run_at=PAST,
+ enabled=False,
+ retired_at=NOW,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_MISSED,
+ )
+
+ with pytest.raises(TaskScheduleRetired):
+ store.set_definition_enabled(
+ "retired",
+ True,
+ definition_type="scheduled",
+ )
+
+ row = store.get_scheduled_task("retired")
+ assert row["enabled"] is False
+ assert (row["retired_at"], row["retirement_reason"]) == (
+ NOW,
+ TASK_RETIREMENT_SCHEDULE_MISSED,
+ )
def test_searching_tasks_looks_at_what_a_command_task_actually_runs(store) -> None:
@@ -1051,12 +1283,29 @@ def test_mark_cycle_result_stamps_a_finish_only_when_it_retires_the_watch(tmp_pa
assert retired.last_finished_at is not None
assert retired.retired_at is not None
assert retired.last_error is None
+ assert retired.last_exit_code == 124
assert retired.enabled is False
# A later non-disabling result cannot erase a genuine retirement.
- before = (retired.last_finished_at, retired.retired_at)
- store.mark_cycle_result(retiring.id, exit_code=0, error=None, event_detected=True, disable=False)
- assert (retired.last_finished_at, retired.retired_at) == before
+ before = (
+ retired.last_finished_at,
+ retired.retired_at,
+ retired.last_exit_code,
+ retired.last_error,
+ )
+ store.mark_cycle_result(
+ retiring.id,
+ exit_code=7,
+ error="late cycle failed",
+ event_detected=True,
+ disable=False,
+ )
+ assert (
+ retired.last_finished_at,
+ retired.retired_at,
+ retired.last_exit_code,
+ retired.last_error,
+ ) == before
continuing = store.add_watch(
name="continuing",
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index d78c95a9d..a317cfee8 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -34,6 +34,7 @@ from storage.background import (
OWED_NOTICE_INDEX,
RUN_INTERRUPTION_REASONS,
SQLiteBackgroundTaskStore,
+ TASK_RETIREMENT_SCHEDULE_CONSUMED,
owed_notice_eligible,
)
@@ -2173,20 +2174,19 @@ def test_circuit_repair_failure_copy_does_not_claim_a_stale_pause_state(
assert "remains paused" not in body
-def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> None:
+def test_a_retired_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> None:
"""The task-side twin of the retired-watch copy fix — FINISHED IS NOT PAUSED.
- A failed ``at`` task is disabled by ``mark_task_result(disable_one_shot=True)``
- before its notice renders, so the generic disabled branch told the user the task
+ A consumed ``at`` task is disabled and retired before its notice renders, so
+ the generic disabled branch told the user the task
was PAUSED and offered ``vibe task resume`` — while the canonical lifecycle
- projection (``definition_lifecycle_expression``) classifies a past one-shot as
+ projection (``definition_lifecycle_expression``) classifies the persisted retirement as
FINISHED and the CLI reads the same combination as a failed one-shot. One
surface's copy contradicted every other surface and named a lifecycle action
that re-arms nothing.
- The distinction is read through the projection's own question —
- ``compute_next_run_at`` returns ``None`` exactly when the named instant is
- behind us — so the copy and the badge cannot disagree. The explicit re-run
+ The distinction is read through the projection's own persisted marker, so
+ the copy and the badge cannot disagree. The explicit re-run
affordance is retained: ``vibe task run`` is real and is the honest next step
for a failed one-shot.
@@ -2200,7 +2200,7 @@ def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> No
from vibe.i18n import t as i18n_t
sqlite, requests = _store(tmp_path)
- # The instant is named and behind us; ``mark_task_result`` left the switch off.
+ # The scheduler consumed this instant and persisted that transition.
_task(
sqlite,
"task-once",
@@ -2209,6 +2209,8 @@ def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> No
cron=None,
run_at="2026-07-20T00:00:00+00:00",
enabled=False,
+ retired_at=_EPOCH,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
)
_task(sqlite, "task-paused", name="paused cron", enabled=False)
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
@@ -2246,10 +2248,8 @@ def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> No
f"a genuinely paused cron task keeps the resume copy: {control!r}"
)
- # A naive ``run_at`` is resolved in the task's own timezone by both the SQL
- # lifecycle projection and ``compute_next_run_at``. This Shanghai wall clock
- # is one hour in the past there but seven hours ahead if misread as UTC, so it
- # consumes the exact disagreement the SQLite connection UDF closes.
+ # A naive ``run_at`` is resolved in the task's own timezone for the next-fire
+ # projection. Lifecycle itself reads only the persisted retirement fact.
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
@@ -2270,6 +2270,8 @@ def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> No
run_at=naive_past_shanghai,
timezone="Asia/Shanghai",
enabled=False,
+ retired_at=_EPOCH,
+ retirement_reason=TASK_RETIREMENT_SCHEDULE_CONSUMED,
)
store.load()
assert sqlite.definition_lifecycle_state("task-tz", definition_type="task") == "finished"
@@ -2291,7 +2293,7 @@ def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> No
{"failure_id": "failure:run-tz", "interrupt_reason": None},
)
assert i18n_t("harness.notice.taskFinished", "en") in tz_body, (
- f"the copy and badge must both read the task-zone instant as FINISHED: {tz_body!r}"
+ f"the copy and badge must both read persisted retirement as FINISHED: {tz_body!r}"
)
assert "vibe task resume task-tz" not in tz_body, f"a finished task must not offer resume: {tz_body!r}"
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 536507e59..6e7c612d0 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -72,6 +72,7 @@ from core.scheduled_tasks import (
ScheduledTaskStore,
SessionBindingChange,
TaskDispatchResult,
+ TaskExecutionResult,
TaskExecutionRequest,
TaskExecutionStore,
_TASK_RESULT_NOT_RECORDED_I18N_KEY,
@@ -92,8 +93,11 @@ from storage.background import (
COMMAND_TIMED_OUT_METADATA_KEY,
DefinitionWriteConflict,
SQLiteBackgroundTaskStore,
+ TASK_SCHEDULE_CONSUMED_METADATA_KEY,
TASK_LAST_RESULT_STATUS_METADATA_KEY,
definition_lifecycle_detail,
+ resolve_run_at,
+ task_schedule_generation,
)
from storage.models import (
agent_events,
@@ -2687,6 +2691,9 @@ def test_service_stop_terminalizes_inflight_run_without_replay(
task.id,
source_kind="scheduler",
task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="test-one-shot",
)
successor = request_store.enqueue_hook_send(
session_key="slack::channel::C123",
@@ -2848,6 +2855,9 @@ def test_service_stop_keeps_claim_cancelled_before_execution_starts_queued(
task.id,
source_kind="scheduler",
task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="test-one-shot",
)
service = ScheduledTaskService(
controller=SimpleNamespace(platform_settings_managers={}),
@@ -2953,7 +2963,11 @@ def test_canceled_task_execution_projects_every_result_and_only_retires_schedule
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
+ has_job = any(
+ job_id == task.id or job_id.startswith(f"{task.id}:at:")
+ for job_id in service.scheduler.jobs
+ )
+ assert has_job is expected_enabled
@pytest.mark.parametrize("cancellation_entrypoint", ["direct", "service_stop", "lease_loss"])
@@ -2979,6 +2993,9 @@ def test_task_definition_projection_follows_the_exact_terminal_cas_winner(
task.id,
source_kind="scheduler",
task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="test-one-shot",
)
started = asyncio.Event()
@@ -3450,6 +3467,21 @@ def test_restart_recovery_terminalizes_started_rows_and_preserves_other_owners(
task.id,
source_kind=source_kind,
task=task,
+ expected_run_at=(
+ task.run_at
+ if source_kind == "scheduler" and task.schedule_type == "at"
+ else None
+ ),
+ expected_timezone=(
+ task.timezone
+ if source_kind == "scheduler" and task.schedule_type == "at"
+ else None
+ ),
+ expected_job_id=(
+ f"test:{task.id}"
+ if source_kind == "scheduler" and task.schedule_type == "at"
+ else None
+ ),
)
assert request_store.claim(request.id) is not None
_force_run_columns(request_store, request.id, pid=4321)
@@ -9876,163 +9908,1512 @@ def test_run_task_request_does_not_disable_one_shot(tmp_path: Path) -> None:
assert updated.last_run_at is not None
-def test_start_keeps_watcher_alive_after_initial_reconcile_failure(tmp_path: Path) -> None:
- store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
- controller = SimpleNamespace(platform_settings_managers={})
- service = ScheduledTaskService(controller=controller, store=store)
- service.scheduler = _StubScheduler()
-
- async def _watch_store():
- await asyncio.Event().wait()
-
- def _fail_once():
- raise ValueError("bad trigger")
+def test_hfr_477_scheduler_consumes_one_shot_atomically_but_manual_run_does_not(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- only the scheduler may consume a one-shot definition."""
- service._watch_store = _watch_store # type: ignore[method-assign]
- service.reconcile_jobs = _fail_once # type: ignore[method-assign]
+ db_path = _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ metadata={TASK_SCHEDULE_CONSUMED_METADATA_KEY: True},
+ )
- async def _exercise():
- service.start()
- assert service._running is True
- assert service._reconcile_task is not None
- service._reconcile_task.cancel()
- try:
- await service._reconcile_task
- except asyncio.CancelledError:
- pass
- await service.stop()
+ manual = requests.enqueue_task_run(task.id, source_kind="cli", task=task)
+ assert manual is not None
+ store.load()
+ armed = store.get_task(task.id)
+ assert armed is not None
+ assert (armed.enabled, armed.retired_at, armed.retirement_reason) == (
+ True,
+ None,
+ None,
+ )
- asyncio.run(_exercise())
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=requests,
+ )
+ service._job_ids[task.id] = "test-one-shot"
+ asyncio.run(
+ service._run_task(
+ task.id,
+ task.run_at,
+ task.timezone,
+ task.updated_at,
+ "test-one-shot",
+ )
+ )
+ stored = requests._sqlite.get_scheduled_task(task.id)
+ assert stored is not None
+ assert stored["enabled"] is False
+ assert stored["retired_at"] is not None
+ assert stored["retirement_reason"] == "schedule_consumed"
+ runs = [
+ row
+ for row in requests._sqlite.list_runs()
+ if row["definition_id"] == task.id
+ ]
+ assert {row["source_kind"] for row in runs} == {"cli", "scheduler"}
+ by_source = {row["source_kind"]: row for row in runs}
+ assert TASK_SCHEDULE_CONSUMED_METADATA_KEY not in by_source["cli"]["metadata"]
+ generation = by_source["scheduler"]["metadata"][
+ TASK_SCHEDULE_CONSUMED_METADATA_KEY
+ ]
+ assert generation["job_id"] == "test-one-shot"
+ assert generation["run_at"] == task.run_at
+ assert stored["last_run_id"] == by_source["scheduler"]["id"]
-def test_watch_store_respawns_after_unexpected_cancellation(tmp_path: Path) -> None:
- """A spurious CancelledError must not silently kill the drain loop."""
- store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
- controller = SimpleNamespace(platform_settings_managers={})
- service = ScheduledTaskService(controller=controller, store=store)
- service.scheduler = _StubScheduler()
- started = asyncio.Event()
+def test_hfr_477_only_a_consumed_one_shot_forces_the_executor_mirror_reload(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- the terminal transition, not scheduler provenance, owns reload."""
- async def _watch_store():
- started.set()
- await asyncio.Event().wait()
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ one_shot = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ cron = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ queued_one_shot = requests.enqueue_task_run(
+ one_shot.id,
+ source_kind="scheduler",
+ task=one_shot,
+ expected_run_at=one_shot.run_at,
+ expected_timezone=one_shot.timezone,
+ expected_job_id="test-one-shot",
+ )
+ queued_cron = requests.enqueue_task_run(
+ cron.id,
+ source_kind="scheduler",
+ task=cron,
+ )
+ assert queued_one_shot is not None and queued_cron is not None
- service._watch_store = _watch_store # type: ignore[method-assign]
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=requests,
+ )
+ reloads: list[str] = []
+ real_load = store.load
+ real_maybe_reload = store.maybe_reload
- async def _exercise():
- service.start()
- first_task = service._reconcile_task
- assert first_task is not None
- await asyncio.wait_for(started.wait(), timeout=1)
+ def _load() -> None:
+ reloads.append("load")
+ real_load()
- started.clear()
- first_task.cancel()
- for _ in range(50):
- await asyncio.sleep(0)
- if service._reconcile_task is not None and service._reconcile_task is not first_task:
- break
- assert service._reconcile_task is not None
- assert service._reconcile_task is not first_task
- assert service._watch_store_restart_count == 1
+ def _maybe_reload() -> bool:
+ reloads.append("maybe_reload")
+ return real_maybe_reload()
- await asyncio.wait_for(started.wait(), timeout=1)
- await service.stop()
+ async def _execute(task, **_kwargs):
+ return TaskExecutionResult(
+ error=None,
+ session_key=task.session_key,
+ session_id=task.session_id,
+ )
- asyncio.run(_exercise())
+ monkeypatch.setattr(store, "load", _load)
+ monkeypatch.setattr(store, "maybe_reload", _maybe_reload)
+ monkeypatch.setattr(service, "_execute_task", _execute)
+ claimed_one_shot = requests.claim(queued_one_shot.id)
+ assert claimed_one_shot is not None
+ asyncio.run(service._execute_claimed_request(claimed_one_shot))
+ assert reloads == ["load"]
-def test_watch_store_respawns_after_unexpected_exception(tmp_path: Path) -> None:
- """If the watch coroutine crashes with a non-Cancelled exception it must respawn."""
- store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
- controller = SimpleNamespace(platform_settings_managers={})
- service = ScheduledTaskService(controller=controller, store=store)
- service.scheduler = _StubScheduler()
+ reloads.clear()
+ claimed_cron = requests.claim(queued_cron.id)
+ assert claimed_cron is not None
+ asyncio.run(service._execute_claimed_request(claimed_cron))
+ assert reloads == ["maybe_reload"]
- invocations: list[int] = []
- async def _watch_store():
- invocations.append(1)
- if len(invocations) == 1:
- raise RuntimeError("boom")
- await asyncio.Event().wait()
+def test_hfr_477_late_consumed_run_cannot_retire_replacement_schedule(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- only the exact scheduler consumption owns retirement."""
- service._watch_store = _watch_store # type: ignore[method-assign]
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ first_run_at = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
+ replacement_run_at = (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=first_run_at,
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=requests,
+ )
+ service._job_ids[task.id] = "test-one-shot"
+ asyncio.run(
+ service._run_task(
+ task.id,
+ first_run_at,
+ "UTC",
+ task.updated_at,
+ "test-one-shot",
+ )
+ )
- async def _exercise():
- service.start()
- for _ in range(50):
- await asyncio.sleep(0)
- if len(invocations) >= 2:
- break
- assert len(invocations) >= 2
- assert service._watch_store_restart_count == 1
- await service.stop()
+ consumed = store.refresh_task(task.id)
+ assert consumed is not None and consumed.retired_at is not None
+ store.update_task(
+ task.id,
+ name=consumed.name,
+ session_key=consumed.session_key,
+ session_id=consumed.session_id,
+ prompt=consumed.prompt,
+ schedule_type="at",
+ post_to=consumed.post_to,
+ deliver_key=consumed.deliver_key,
+ cron=None,
+ run_at=replacement_run_at,
+ timezone_name="UTC",
+ agent_name=consumed.agent_name,
+ session_policy=consumed.session_policy,
+ )
+ store.set_enabled(task.id, True)
- asyncio.run(_exercise())
+ consumed_run = next(
+ row
+ for row in requests._sqlite.list_runs()
+ if row["definition_id"] == task.id and row["source_kind"] == "scheduler"
+ )
+ generation = consumed_run["metadata"][TASK_SCHEDULE_CONSUMED_METADATA_KEY]
+ assert not store.mark_task_result(
+ task.id,
+ error=None,
+ disable_one_shot=True,
+ expected_schedule_generation=generation,
+ expected_terminal_run_id=consumed_run["id"],
+ )
+ replacement = store.refresh_task(task.id)
+ assert replacement is not None
+ assert (replacement.enabled, replacement.run_at) == (True, replacement_run_at)
+ assert (replacement.retired_at, replacement.retirement_reason) == (None, None)
+ assert replacement.last_run_at is None
-def test_watch_store_does_not_respawn_after_stop(tmp_path: Path) -> None:
- """stop() cancels the task and must not trigger a respawn."""
- store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
- controller = SimpleNamespace(platform_settings_managers={})
- service = ScheduledTaskService(controller=controller, store=store)
- service.scheduler = _StubScheduler()
- async def _watch_store():
- await asyncio.Event().wait()
+def test_hfr_477_manual_rerun_of_retired_one_shot_preserves_terminal_owner(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- a manual rerun adds history without reviving the schedule."""
- service._watch_store = _watch_store # type: ignore[method-assign]
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ consumed = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert consumed is not None
+ store.load()
+ retired = store.refresh_task(task.id)
+ assert retired is not None
+ terminal = (retired.retired_at, retired.retirement_reason, retired.last_run_id)
- async def _exercise():
- service.start()
- first_task = service._reconcile_task
- assert first_task is not None
- await service.stop()
- assert service._reconcile_task is None
- assert service._watch_store_restart_count == 0
- assert first_task.cancelled() or first_task.done()
+ manual = requests.enqueue_task_run(task.id, source_kind="cli", task=retired)
- asyncio.run(_exercise())
+ assert manual is not None
+ assert TASK_SCHEDULE_CONSUMED_METADATA_KEY not in manual.metadata
+ current = store.refresh_task(task.id)
+ assert current is not None
+ assert current.enabled is False
+ assert (current.retired_at, current.retirement_reason, current.last_run_id) == terminal
-def test_hfr_164_hfr_165_service_restart_joins_only_its_harness_lane_generations(
[email protected]("retirement_reason", ["schedule_missed", "schedule_consumed"])
+def test_hfr_477_non_owner_manual_failure_preserves_retired_one_shot_projection(
tmp_path: Path,
monkeypatch,
+ retirement_reason: str,
) -> None:
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- class _Supervisor:
- def __init__(self) -> None:
- self.generations: dict[RuntimeWorkLane, int] = {}
- self.current: dict[RuntimeWorkLane, RuntimeWorkRegistrationToken] = {}
- self.unregistered: list[RuntimeWorkLane] = []
+ """HFR-477/HFR-478 -- a manual Run owns history, never retired definition facts."""
- def register(self, lane, _handler): # noqa: ANN001, ANN202
- assert lane not in self.current
- generation = self.generations.get(lane, 0) + 1
- self.generations[lane] = generation
- token = RuntimeWorkRegistrationToken(lane=lane, generation=generation)
- self.current[lane] = token
- return token
+ _command_task_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = _add_command_task(
+ store,
+ shell_command="echo manual failure >&2; exit 7",
+ cwd=str(tmp_path),
+ schedule_type="at",
+ )
+ if retirement_reason == "schedule_consumed":
+ owner = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert owner is not None
+ else:
+ assert store.sqlite_backend is not None
+ assert store.sqlite_backend.retire_missed_one_shot(
+ task.id,
+ expected_run_at=str(task.run_at),
+ expected_timezone=task.timezone,
+ expected_updated_at=task.updated_at,
+ retired_at="2026-07-28T09:00:01+00:00",
+ )
+ store.load()
+ retired = store.get_task(task.id)
+ assert retired is not None
+ assert retired.retirement_reason == retirement_reason
+ definition_before = _stored_definition_row(task.id)
- def begin_unregister(self, token): # noqa: ANN001, ANN202
- assert self.current.get(token.lane) == token
- self.current.pop(token.lane)
- self.unregistered.append(token.lane)
+ manual = requests.enqueue_task_run(task.id, source_kind="cli", task=retired)
+ assert manual is not None
+ claimed = requests.claim(manual.id)
+ assert claimed is not None
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+ asyncio.run(service._execute_claimed_request(claimed))
- async def _joined() -> None:
- return None
+ definition_after = _stored_definition_row(task.id)
+ assert definition_after == definition_before
+ run = requests.get_run(manual.id)
+ assert run is not None
+ assert (run["status"], run["exit_code"]) == ("failed", 7)
+ assert "manual failure" in str(run["error"])
+ assert TASK_SCHEDULE_CONSUMED_METADATA_KEY not in (run["metadata"] or {})
+ notice = requests.sqlite_backend.owed_failure_notice(manual.id)
+ assert notice is not None and notice["state"] == "pending"
- return asyncio.create_task(_joined())
- def notify(self, *_lanes) -> None: # noqa: ANN002
- return None
[email protected]("replacement_schedule", ["at", "cron"])
+def test_hfr_477_retired_manual_escalation_preserves_replacement_schedule(
+ tmp_path: Path,
+ monkeypatch,
+ replacement_schedule: str,
+) -> None:
+ """HFR-477 -- an old manual Run may enqueue, but never rewrite its replacement."""
- async def _exercise() -> None:
- supervisor = _Supervisor()
- supervisor.register(RuntimeWorkLane.SESSION_DELIVERIES, object())
- controller = SimpleNamespace(
+ _command_task_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ session_id = _bare_session_row(
+ workdir=tmp_path,
+ anchor=f"avibe_retired_escalation_replacement_{replacement_schedule}",
+ )
+ task = _escalation_command_task(
+ store,
+ tmp_path,
+ shell_command="echo old manual failure >&2; exit 7",
+ schedule_type="at",
+ session_id=session_id,
+ agent_name="codex",
+ )
+ assert store.sqlite_backend is not None
+ assert store.sqlite_backend.retire_missed_one_shot(
+ task.id,
+ expected_run_at=str(task.run_at),
+ expected_timezone=task.timezone,
+ expected_updated_at=task.updated_at,
+ retired_at="2026-07-28T09:00:01+00:00",
+ )
+ store.load()
+ retired = store.get_task(task.id)
+ assert retired is not None and retired.retired_at is not None
+
+ requests = TaskExecutionStore()
+ manual = requests.enqueue_task_run(task.id, source_kind="cli", task=retired)
+ assert manual is not None
+ claimed = requests.claim(manual.id)
+ assert claimed is not None
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+ replacement_row: dict[str, Any] = {}
+ real_runner = scheduled_tasks.run_supervised_command
+
+ async def _replace_while_running(**kwargs):
+ writer = ScheduledTaskStore()
+ current = writer.get_task(task.id)
+ assert current is not None
+ replacement_run_at = (
+ "2026-07-29T10:30:00+00:00"
+ if replacement_schedule == "at"
+ else None
+ )
+ writer.update_task(
+ task.id,
+ name=current.name,
+ session_key=current.session_key,
+ session_id=current.session_id,
+ prompt="replacement definition",
+ schedule_type=replacement_schedule,
+ post_to=current.post_to,
+ deliver_key=current.deliver_key,
+ cron="30 10 * * *" if replacement_schedule == "cron" else None,
+ run_at=replacement_run_at,
+ timezone_name="UTC",
+ agent_name=current.agent_name,
+ session_policy=current.session_policy,
+ )
+ replacement_row.update(_stored_definition_row(task.id))
+ return await real_runner(**kwargs)
+
+ monkeypatch.setattr(
+ scheduled_tasks,
+ "run_supervised_command",
+ _replace_while_running,
+ )
+
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ assert _stored_definition_row(task.id) == replacement_row
+ run = requests.get_run(manual.id)
+ assert run is not None and (run["status"], run["exit_code"]) == ("failed", 7)
+ escalations = _escalation_runs(store)
+ assert len(escalations) == 1
+ assert escalations[0]["parent_run_id"] == manual.id
+ assert escalations[0]["agent_name"] == "codex"
+ assert requests.sqlite_backend.owed_failure_notice(manual.id) is None
+
+
[email protected]("authority_loss", ["deleted", "reclaimed", "canceled"])
+def test_hfr_477_retired_manual_escalation_refuses_lost_authority(
+ tmp_path: Path,
+ monkeypatch,
+ authority_loss: str,
+) -> None:
+ """HFR-477 -- outbox enqueue rechecks deletion, reclaim, and cancellation."""
+
+ from storage.session_reclaim import RECLAIM_PAUSE, reclaim_bound_definitions
+
+ _command_task_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ session_id = _bare_session_row(
+ workdir=tmp_path,
+ anchor=f"avibe_retired_escalation_refusal_{authority_loss}",
+ )
+ task = _escalation_command_task(
+ store,
+ tmp_path,
+ shell_command="echo refused escalation >&2; exit 7",
+ schedule_type="at",
+ session_id=session_id,
+ agent_name="codex",
+ )
+ assert store.sqlite_backend is not None
+ assert store.sqlite_backend.retire_missed_one_shot(
+ task.id,
+ expected_run_at=str(task.run_at),
+ expected_timezone=task.timezone,
+ expected_updated_at=task.updated_at,
+ retired_at="2026-07-28T09:00:01+00:00",
+ )
+ store.load()
+ retired = store.get_task(task.id)
+ assert retired is not None and retired.retired_at is not None
+
+ requests = TaskExecutionStore()
+ manual = requests.enqueue_task_run(task.id, source_kind="cli", task=retired)
+ assert manual is not None
+ claimed = requests.claim(manual.id)
+ assert claimed is not None
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+ original_enqueue = (
+ scheduled_tasks.SQLiteBackgroundTaskStore
+ .enqueue_task_escalation_without_definition_write
+ )
+
+ def _lose_authority_before_transaction(backend, definition_id, **kwargs):
+ if authority_loss == "deleted":
+ assert backend.remove_task(definition_id)
+ elif authority_loss == "reclaimed":
+ with backend.engine.begin() as conn:
+ summary = reclaim_bound_definitions(
+ conn,
+ session_id,
+ mode=RECLAIM_PAUSE,
+ reason="the bound session was replaced",
+ )
+ assert summary["paused"] == 1
+ else:
+ assert backend.cancel_run(manual.id)
+ return original_enqueue(backend, definition_id, **kwargs)
+
+ monkeypatch.setattr(
+ scheduled_tasks.SQLiteBackgroundTaskStore,
+ "enqueue_task_escalation_without_definition_write",
+ _lose_authority_before_transaction,
+ )
+
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ run = requests.get_run(manual.id)
+ assert run is not None
+ assert _escalation_runs(store) == []
+ assert run["metadata"].get("escalation_run_id") is None
+ if authority_loss == "canceled":
+ assert run["status"] == "canceled"
+ else:
+ assert run["status"] == "failed"
+ notice = requests.sqlite_backend.owed_failure_notice(manual.id)
+ assert notice is not None and notice["state"] == "pending"
+
+
+def test_hfr_477_old_queued_run_does_not_suppress_replacement_generation(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- successor suppression is scoped to one exact DateTrigger."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="generation A",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ first = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ suppress_scheduler_successor=True,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert first is not None
+ store.load()
+ retired = store.refresh_task(task.id)
+ replacement_run_at = (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat()
+ replacement = store.update_task(
+ task.id,
+ name=retired.name,
+ session_key=retired.session_key,
+ session_id=retired.session_id,
+ prompt="generation B",
+ schedule_type="at",
+ post_to=retired.post_to,
+ deliver_key=retired.deliver_key,
+ cron=None,
+ run_at=replacement_run_at,
+ timezone_name="UTC",
+ agent_name=retired.agent_name,
+ session_policy=retired.session_policy,
+ )
+ store.set_enabled(task.id, True)
+ replacement = store.refresh_task(task.id)
+ second = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=replacement,
+ suppress_scheduler_successor=True,
+ expected_run_at=replacement.run_at,
+ expected_timezone=replacement.timezone,
+ expected_job_id="generation-b",
+ )
+
+ assert second is not None
+ assert second.id != first.id
+ assert requests.get_run(first.id)["status"] == "queued"
+ current = store.refresh_task(task.id)
+ assert current is not None and current.last_run_id == second.id
+
+
+def test_hfr_477_old_queued_run_cannot_execute_replacement_definition(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- a claimed old fire keeps its history but cannot run generation B."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="generation A",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ queued = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert queued is not None
+ store.load()
+ retired = store.get_task(task.id)
+ store.update_task(
+ task.id,
+ name=retired.name,
+ session_key=retired.session_key,
+ session_id=retired.session_id,
+ prompt="generation B",
+ schedule_type="cron",
+ post_to=retired.post_to,
+ deliver_key=retired.deliver_key,
+ cron="0 * * * *",
+ run_at=None,
+ timezone_name="UTC",
+ agent_name=retired.agent_name,
+ session_policy=retired.session_policy,
+ )
+ store.set_enabled(task.id, True)
+ dispatched: list[str] = []
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=requests,
+ )
+
+ async def _execute_request(**kwargs):
+ dispatched.append(kwargs["prompt"])
+ return None
+
+ service._execute_request = _execute_request
+ claimed = requests.claim(queued.id)
+ assert claimed is not None
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ assert dispatched == []
+ old_run = requests.get_run(queued.id)
+ assert old_run is not None and old_run["status"] == "failed"
+ replacement = store.refresh_task(task.id)
+ assert replacement is not None
+ assert (replacement.enabled, replacement.schedule_type, replacement.prompt) == (
+ True,
+ "cron",
+ "generation B",
+ )
+ assert replacement.last_run_at is None
+
+
+def test_hfr_477_result_cas_rejects_replacement_after_mirror_read(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- replacement in the result read/write window wins atomically."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="generation A",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ queued = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert queued is not None
+ generation = task_schedule_generation(queued.metadata)
+ assert generation is not None
+ store.load()
+ real_upsert = store.sqlite_backend.upsert_scheduled_task
+
+ def _replace_then_write(payload, **kwargs):
+ writer = ScheduledTaskStore()
+ current = writer.get_task(task.id)
+ writer.update_task(
+ task.id,
+ name=current.name,
+ session_key=current.session_key,
+ session_id=current.session_id,
+ prompt="generation B",
+ schedule_type="cron",
+ post_to=current.post_to,
+ deliver_key=current.deliver_key,
+ cron="0 * * * *",
+ run_at=None,
+ timezone_name="UTC",
+ agent_name=current.agent_name,
+ session_policy=current.session_policy,
+ )
+ writer.set_enabled(task.id, True)
+ return real_upsert(payload, **kwargs)
+
+ monkeypatch.setattr(store.sqlite_backend, "upsert_scheduled_task", _replace_then_write)
+ landed = store.mark_task_result(
+ task.id,
+ error=None,
+ expected_schedule_generation=generation,
+ expected_terminal_run_id=queued.id,
+ )
+
+ assert landed is False
+ replacement = store.refresh_task(task.id)
+ assert replacement is not None
+ assert (replacement.enabled, replacement.schedule_type, replacement.prompt) == (
+ True,
+ "cron",
+ "generation B",
+ )
+ assert replacement.last_run_at is None
+
+
+def test_hfr_477_consumed_result_survives_unrelated_definition_edit(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- mutable copy edits do not replace the consumed generation."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ name="generation A",
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="existing",
+ )
+ queued = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="generation-a",
+ )
+ assert queued is not None
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=requests,
+ )
+ assert store.maybe_reload() is False
+
+ async def _edit_while_running(**_kwargs):
+ writer = ScheduledTaskStore()
+ current = writer.get_task(task.id)
+ assert current is not None
+ writer.update_task(
+ task.id,
+ name="renamed while running",
+ session_key=current.session_key,
+ session_id=current.session_id,
+ prompt="edited prompt",
+ schedule_type=current.schedule_type,
+ post_to=current.post_to,
+ deliver_key=current.deliver_key,
+ cron=current.cron,
+ run_at=current.run_at,
+ timezone_name=current.timezone,
+ agent_name=current.agent_name,
+ session_policy=current.session_policy,
+ )
+ return TaskDispatchResult(error=None)
+
+ service._execute_request = _edit_while_running
+ claimed = requests.claim(queued.id)
+ assert claimed is not None
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ settled = requests.get_run(queued.id)
+ assert settled is not None and settled["status"] == "succeeded"
+ current = store.refresh_task(task.id)
+ assert current is not None
+ assert (current.name, current.prompt) == ("renamed while running", "edited prompt")
+ assert current.last_run_id == queued.id
+ assert current.retired_at == task_schedule_generation(queued.metadata)["retired_at"]
+ assert current.last_run_at is not None
+ assert current.last_error is None
+
+
+def test_hfr_477_enqueue_exception_records_failed_terminal_owner(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- a DateTrigger callback cannot disappear before enqueue."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=requests,
+ )
+ service._job_ids[task.id] = "generation-a"
+ real_enqueue = requests._sqlite.enqueue_definition_run
+
+ def _fail_enqueue(payload, **kwargs):
+ if kwargs.get("terminal_error") is None:
+ raise RuntimeError("queue unavailable")
+ return real_enqueue(payload, **kwargs)
+
+ monkeypatch.setattr(requests._sqlite, "enqueue_definition_run", _fail_enqueue)
+ asyncio.run(
+ service._run_task(
+ task.id,
+ task.run_at,
+ task.timezone,
+ task.updated_at,
+ "generation-a",
+ )
+ )
+
+ current = requests._sqlite.get_scheduled_task(task.id)
+ assert current is not None
+ assert current["lifecycle_state"] == "finished"
+ assert current["lifecycle_detail"] == "error"
+ owner = requests.get_run(current["last_run_id"])
+ assert owner is not None and owner["status"] == "failed"
+ assert "queue unavailable" in owner["error"]
+ assert task_schedule_generation(owner["metadata"])["job_id"] == "generation-a"
+ notice = requests._sqlite.owed_failure_notice(owner["id"])
+ assert notice is not None and notice["state"] == "pending"
+ assert [row["id"] for row in requests._sqlite.list_owed_failure_notices()] == [
+ owner["id"]
+ ]
+ compact = requests._sqlite.list_scheduled_tasks_page(
+ page_request=PageRequest(limit=20),
+ include_successful_finished=False,
+ )
+ assert task.id in {item["id"] for item in compact.items}
+
+ emitted: list[str] = []
+
+ async def _emit(run, _notice, evidence):
+ emitted.append(run["id"])
+ evidence.delivered_id = "notice-1"
+ evidence.persisted_row = {"id": "notice-1"}
+ evidence.send_returned = True
+ return True
+
+ service._emit_failure_notice = _emit
+ service._owns_service_instance = lambda: True
+ asyncio.run(service._drain_failure_notices())
+
+ assert emitted == [owner["id"]]
+ sent = requests._sqlite.owed_failure_notice(owner["id"])
+ assert sent is not None and sent["state"] == "sent"
+
+
+def test_hfr_477_job_error_event_recovers_only_registered_generation(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- EVENT_JOB_ERROR carries the same exact DateTrigger owner."""
+
+ from apscheduler.events import EVENT_JOB_ERROR, JobExecutionEvent
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=TaskExecutionStore(),
+ )
+ service.scheduler = _StubScheduler()
+ service.reconcile_jobs()
+ job_id = service._job_ids[task.id]
+ event = JobExecutionEvent(
+ EVENT_JOB_ERROR,
+ job_id,
+ "default",
+ resolve_run_at(task.run_at, task.timezone),
+ exception=RuntimeError("callback failed"),
+ )
+
+ service._on_scheduler_event(event)
+
+ current = service.request_store._sqlite.get_scheduled_task(task.id)
+ assert current is not None and current["lifecycle_detail"] == "error"
+ owner = service.request_store.get_run(current["last_run_id"])
+ assert owner is not None and owner["status"] == "failed"
+ generation = task_schedule_generation(owner["metadata"])
+ assert generation is not None and generation["job_id"] == job_id
+
+
+def test_hfr_478_misfire_retires_only_the_schedule_apscheduler_observed(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-478 -- missed recovery records evidence and rejects stale events."""
+
+ from apscheduler.events import EVENT_JOB_MISSED, JobExecutionEvent
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ original_instant = (datetime.now(timezone.utc) - timedelta(hours=2)).replace(
+ microsecond=0
+ )
+ original_run_at = original_instant.isoformat()
+ replacement_run_at = original_instant.astimezone(
+ timezone(timedelta(hours=8))
+ ).isoformat()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=original_run_at,
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=TaskExecutionStore(),
+ )
+ service.scheduler = _StubScheduler()
+ service.reconcile_jobs()
+ original_job_id = service._job_ids[task.id]
+ stale_event = JobExecutionEvent(
+ EVENT_JOB_MISSED,
+ original_job_id,
+ "default",
+ resolve_run_at(original_run_at, "UTC"),
+ )
+
+ store.update_task(
+ task.id,
+ name=task.name,
+ session_key=task.session_key,
+ session_id=task.session_id,
+ prompt=task.prompt,
+ schedule_type="at",
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ cron=None,
+ run_at=replacement_run_at,
+ timezone_name="Asia/Shanghai",
+ agent_name=task.agent_name,
+ session_policy=task.session_policy,
+ )
+ service.reconcile_jobs()
+ replacement_job_id = service._job_ids[task.id]
+ assert replacement_job_id != original_job_id
+ service._on_scheduler_event(stale_event)
+ current = store.refresh_task(task.id)
+ assert current is not None
+ assert (current.enabled, current.retired_at, current.retirement_reason) == (
+ True,
+ None,
+ None,
+ )
+
+ missed_event = JobExecutionEvent(
+ EVENT_JOB_MISSED,
+ replacement_job_id,
+ "default",
+ resolve_run_at(replacement_run_at, "Asia/Shanghai"),
+ )
+ service.scheduler.remove_job(replacement_job_id)
+ service._on_scheduler_event(missed_event)
+ missed = store.refresh_task(task.id)
+ assert missed is not None
+ assert missed.enabled is False
+ assert missed.retired_at is not None
+ assert missed.retirement_reason == "schedule_missed"
+ assert service.scheduler.get_jobs() == []
+ assert task.id not in service._job_ids
+ assert [
+ row
+ for row in service.request_store._sqlite.list_runs()
+ if row["definition_id"] == task.id
+ ] == []
+
+
[email protected]("replacement_schedule", ["cron", "at"])
[email protected]("event_code", ["missed", "error"])
+def test_hfr_478_stale_event_reconciles_the_current_replacement_schedule(
+ tmp_path: Path,
+ monkeypatch,
+ replacement_schedule: str,
+ event_code: str,
+) -> None:
+ """HFR-478 -- rejecting a removed DateTrigger restores current intent."""
+
+ from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_MISSED, JobExecutionEvent
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ original_run_at = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
+ task = store.add_task(
+ session_key="",
+ prompt="original",
+ schedule_type="at",
+ run_at=original_run_at,
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=TaskExecutionStore(),
+ )
+ service.scheduler = _StubScheduler()
+ service.reconcile_jobs()
+ original_job_id = service._job_ids[task.id]
+ original_identity = service._one_shot_job_identities[original_job_id]
+ assert store.maybe_reload() is False
+
+ writer = ScheduledTaskStore()
+ current = writer.get_task(task.id)
+ assert current is not None
+ replacement_run_at = (
+ (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat()
+ if replacement_schedule == "at"
+ else None
+ )
+ replacement = writer.update_task(
+ task.id,
+ name=current.name,
+ session_key=current.session_key,
+ session_id=current.session_id,
+ prompt="replacement",
+ schedule_type=replacement_schedule,
+ post_to=current.post_to,
+ deliver_key=current.deliver_key,
+ cron="0 * * * *" if replacement_schedule == "cron" else None,
+ run_at=replacement_run_at,
+ timezone_name="UTC",
+ agent_name=current.agent_name,
+ session_policy=current.session_policy,
+ )
+
+ # APScheduler removes a DateTrigger before publishing its terminal event.
+ service.scheduler.remove_job(original_job_id)
+ code = EVENT_JOB_ERROR if event_code == "error" else EVENT_JOB_MISSED
+ event = JobExecutionEvent(
+ code,
+ original_job_id,
+ "default",
+ resolve_run_at(original_identity[1], original_identity[2]),
+ exception=RuntimeError("stale callback") if event_code == "error" else None,
+ )
+ service._on_scheduler_event(event)
+
+ refreshed = store.refresh_task(task.id)
+ assert refreshed is not None
+ assert (refreshed.enabled, refreshed.retired_at, refreshed.schedule_type) == (
+ True,
+ None,
+ replacement_schedule,
+ )
+ assert refreshed.updated_at == replacement.updated_at
+ assert len(service.scheduler.get_jobs()) == 1
+ replacement_job_id = service._job_ids[task.id]
+ replacement_job = service.scheduler.get_job(replacement_job_id)
+ assert replacement_job is not None
+ assert replacement_job.args[0] == task.id
+ if replacement_schedule == "at":
+ assert replacement_job_id != original_job_id
+ assert tuple(replacement_job.args[1:4]) == (
+ replacement_run_at,
+ "UTC",
+ replacement.updated_at,
+ )
+ else:
+ assert replacement_job_id == task.id
+ assert tuple(replacement_job.args[1:4]) == (None, None, None)
+ assert original_job_id not in service._one_shot_job_identities
+
+
[email protected]("replacement_schedule", ["cron", "at"])
+def test_hfr_477_normal_stale_callback_reconciles_the_current_replacement_schedule(
+ tmp_path: Path,
+ monkeypatch,
+ replacement_schedule: str,
+) -> None:
+ """HFR-477 -- a rejected normal DateTrigger returns current intent to its owner."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ prompt="original",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=TaskExecutionStore(),
+ )
+ service.scheduler = _StubScheduler()
+ service.reconcile_jobs()
+ original_job_id = service._job_ids[task.id]
+ original_identity = service._one_shot_job_identities[original_job_id]
+
+ writer = ScheduledTaskStore()
+ current = writer.get_task(task.id)
+ assert current is not None
+ replacement_run_at = (
+ (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat()
+ if replacement_schedule == "at"
+ else None
+ )
+ replacement = writer.update_task(
+ task.id,
+ name=current.name,
+ session_key=current.session_key,
+ session_id=current.session_id,
+ prompt="replacement",
+ schedule_type=replacement_schedule,
+ post_to=current.post_to,
+ deliver_key=current.deliver_key,
+ cron="0 * * * *" if replacement_schedule == "cron" else None,
+ run_at=replacement_run_at,
+ timezone_name="UTC",
+ agent_name=current.agent_name,
+ session_policy=current.session_policy,
+ )
+ service.scheduler.remove_job(original_job_id)
+
+ asyncio.run(service._run_task(task.id, *original_identity[1:], original_job_id))
+
+ assert service.request_store.list_pending() == []
+ jobs = service.scheduler.get_jobs()
+ assert len(jobs) == 1
+ replacement_job = jobs[0]
+ assert replacement_job.args[0] == task.id
+ assert service._job_ids[task.id] == replacement_job.id
+ if replacement_schedule == "at":
+ assert replacement_job.id != original_job_id
+ assert tuple(replacement_job.args[1:4]) == (
+ replacement_run_at,
+ "UTC",
+ replacement.updated_at,
+ )
+ else:
+ assert replacement_job.id == task.id
+ assert tuple(replacement_job.args[1:4]) == (None, None, None)
+
+
+def test_hfr_477_enqueue_race_reconciles_the_current_replacement_schedule(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- losing the atomic enqueue CAS still restores current intent."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ prompt="original",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=store,
+ request_store=TaskExecutionStore(),
+ )
+ service.scheduler = _StubScheduler()
+ service.reconcile_jobs()
+ original_job_id = service._job_ids[task.id]
+ original_identity = service._one_shot_job_identities[original_job_id]
+ replacement_run_at = (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat()
+
+ def _replace_before_atomic_enqueue(*_args, **_kwargs):
+ writer = ScheduledTaskStore()
+ current = writer.get_task(task.id)
+ assert current is not None
+ writer.update_task(
+ task.id,
+ name=current.name,
+ session_key=current.session_key,
+ session_id=current.session_id,
+ prompt="replacement",
+ schedule_type="at",
+ post_to=current.post_to,
+ deliver_key=current.deliver_key,
+ cron=None,
+ run_at=replacement_run_at,
+ timezone_name="UTC",
+ agent_name=current.agent_name,
+ session_policy=current.session_policy,
+ )
+ return None
+
+ monkeypatch.setattr(
+ service.request_store,
+ "enqueue_task_run",
+ _replace_before_atomic_enqueue,
+ )
+ service.scheduler.remove_job(original_job_id)
+
+ asyncio.run(service._run_task(task.id, *original_identity[1:], original_job_id))
+
+ replacement = store.refresh_task(task.id)
+ assert replacement is not None and replacement.run_at == replacement_run_at
+ jobs = service.scheduler.get_jobs()
+ assert len(jobs) == 1
+ replacement_job = jobs[0]
+ assert replacement_job.id != original_job_id
+ assert tuple(replacement_job.args[1:4]) == (
+ replacement_run_at,
+ "UTC",
+ replacement.updated_at,
+ )
+
+
+def test_hfr_477_stale_scheduler_enqueue_cannot_consume_a_replacement_generation(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- the storage CAS rejects stale and non-``at`` callbacks."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ run_at = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
+ task = store.add_task(
+ session_key="",
+ prompt="original",
+ schedule_type="at",
+ run_at=run_at,
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ original_updated_at = task.updated_at
+
+ replacement = store.update_task(
+ task.id,
+ name=task.name,
+ session_key=task.session_key,
+ session_id=task.session_id,
+ prompt="replacement",
+ schedule_type="at",
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ cron=None,
+ run_at=run_at,
+ timezone_name="UTC",
+ agent_name=task.agent_name,
+ session_policy=task.session_policy,
+ )
+ stale = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=run_at,
+ expected_timezone="UTC",
+ expected_updated_at=original_updated_at,
+ expected_job_id="stale-job",
+ )
+ assert stale is None
+ assert store.refresh_task(task.id).enabled is True
+
+ cron = store.update_task(
+ task.id,
+ name=replacement.name,
+ session_key=replacement.session_key,
+ session_id=replacement.session_id,
+ prompt=replacement.prompt,
+ schedule_type="cron",
+ post_to=replacement.post_to,
+ deliver_key=replacement.deliver_key,
+ cron="0 * * * *",
+ run_at=None,
+ timezone_name="UTC",
+ agent_name=replacement.agent_name,
+ session_policy=replacement.session_policy,
+ )
+ stale_after_cron = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=cron,
+ expected_run_at=run_at,
+ expected_timezone="UTC",
+ expected_updated_at=replacement.updated_at,
+ expected_job_id="stale-job",
+ )
+ assert stale_after_cron is None
+ assert store.refresh_task(task.id).schedule_type == "cron"
+
+
+def test_hfr_477_consumed_terminal_outcome_belongs_to_the_consuming_run(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-477 -- prior manual history cannot hide a canceled consumed fire."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ requests = TaskExecutionStore()
+ task = store.add_task(
+ session_key="",
+ prompt="send digest",
+ schedule_type="at",
+ run_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
+ timezone_name="UTC",
+ session_policy="create_per_run",
+ )
+ manual = requests.enqueue_task_run(task.id, source_kind="cli", task=task)
+ assert manual is not None
+ claimed = requests.claim(manual.id)
+ assert claimed is not None
+ assert requests.complete(claimed, ok=True) == "succeeded"
+ manual_finished_at = requests.get_run(manual.id)["completed_at"]
+
+ consumed = requests.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="test-one-shot",
+ )
+ assert consumed is not None
+ assert requests.cancel_run(consumed.id)
+
+ row = requests._sqlite.get_scheduled_task(task.id)
+ terminal_run = requests.get_run(consumed.id)
+ assert row is not None and terminal_run is not None
+ assert row["last_run_id"] == consumed.id
+ assert row["lifecycle_state"] == "finished"
+ assert row["lifecycle_detail"] == "canceled"
+ assert row["lifecycle_finished_at"] == terminal_run["completed_at"]
+ assert row["last_run_at"] == terminal_run["completed_at"]
+ assert row["last_run_at"] != manual_finished_at
+ compact = requests._sqlite.list_scheduled_tasks_page(
+ page_request=PageRequest(limit=20),
+ include_successful_finished=False,
+ )
+ assert task.id in {item["id"] for item in compact.items}
+
+
+def test_start_keeps_watcher_alive_after_initial_reconcile_failure(tmp_path: Path) -> None:
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(controller=controller, store=store)
+ service.scheduler = _StubScheduler()
+
+ async def _watch_store():
+ await asyncio.Event().wait()
+
+ def _fail_once():
+ raise ValueError("bad trigger")
+
+ service._watch_store = _watch_store # type: ignore[method-assign]
+ service.reconcile_jobs = _fail_once # type: ignore[method-assign]
+
+ async def _exercise():
+ service.start()
+ assert service._running is True
+ assert service._reconcile_task is not None
+ service._reconcile_task.cancel()
+ try:
+ await service._reconcile_task
+ except asyncio.CancelledError:
+ pass
+ await service.stop()
+
+ asyncio.run(_exercise())
+
+
+def test_watch_store_respawns_after_unexpected_cancellation(tmp_path: Path) -> None:
+ """A spurious CancelledError must not silently kill the drain loop."""
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(controller=controller, store=store)
+ service.scheduler = _StubScheduler()
+
+ started = asyncio.Event()
+
+ async def _watch_store():
+ started.set()
+ await asyncio.Event().wait()
+
+ service._watch_store = _watch_store # type: ignore[method-assign]
+
+ async def _exercise():
+ service.start()
+ first_task = service._reconcile_task
+ assert first_task is not None
+ await asyncio.wait_for(started.wait(), timeout=1)
+
+ started.clear()
+ first_task.cancel()
+ for _ in range(50):
+ await asyncio.sleep(0)
+ if service._reconcile_task is not None and service._reconcile_task is not first_task:
+ break
+ assert service._reconcile_task is not None
+ assert service._reconcile_task is not first_task
+ assert service._watch_store_restart_count == 1
+
+ await asyncio.wait_for(started.wait(), timeout=1)
+ await service.stop()
+
+ asyncio.run(_exercise())
+
+
+def test_watch_store_respawns_after_unexpected_exception(tmp_path: Path) -> None:
+ """If the watch coroutine crashes with a non-Cancelled exception it must respawn."""
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(controller=controller, store=store)
+ service.scheduler = _StubScheduler()
+
+ invocations: list[int] = []
+
+ async def _watch_store():
+ invocations.append(1)
+ if len(invocations) == 1:
+ raise RuntimeError("boom")
+ await asyncio.Event().wait()
+
+ service._watch_store = _watch_store # type: ignore[method-assign]
+
+ async def _exercise():
+ service.start()
+ for _ in range(50):
+ await asyncio.sleep(0)
+ if len(invocations) >= 2:
+ break
+ assert len(invocations) >= 2
+ assert service._watch_store_restart_count == 1
+ await service.stop()
+
+ asyncio.run(_exercise())
+
+
+def test_watch_store_does_not_respawn_after_stop(tmp_path: Path) -> None:
+ """stop() cancels the task and must not trigger a respawn."""
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(controller=controller, store=store)
+ service.scheduler = _StubScheduler()
+
+ async def _watch_store():
+ await asyncio.Event().wait()
+
+ service._watch_store = _watch_store # type: ignore[method-assign]
+
+ async def _exercise():
+ service.start()
+ first_task = service._reconcile_task
+ assert first_task is not None
+ await service.stop()
+ assert service._reconcile_task is None
+ assert service._watch_store_restart_count == 0
+ assert first_task.cancelled() or first_task.done()
+
+ asyncio.run(_exercise())
+
+
+def test_hfr_164_hfr_165_service_restart_joins_only_its_harness_lane_generations(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ class _Supervisor:
+ def __init__(self) -> None:
+ self.generations: dict[RuntimeWorkLane, int] = {}
+ self.current: dict[RuntimeWorkLane, RuntimeWorkRegistrationToken] = {}
+ self.unregistered: list[RuntimeWorkLane] = []
+
+ def register(self, lane, _handler): # noqa: ANN001, ANN202
+ assert lane not in self.current
+ generation = self.generations.get(lane, 0) + 1
+ self.generations[lane] = generation
+ token = RuntimeWorkRegistrationToken(lane=lane, generation=generation)
+ self.current[lane] = token
+ return token
+
+ def begin_unregister(self, token): # noqa: ANN001, ANN202
+ assert self.current.get(token.lane) == token
+ self.current.pop(token.lane)
+ self.unregistered.append(token.lane)
+
+ async def _joined() -> None:
+ return None
+
+ return asyncio.create_task(_joined())
+
+ def notify(self, *_lanes) -> None: # noqa: ANN002
+ return None
+
+ async def _exercise() -> None:
+ supervisor = _Supervisor()
+ supervisor.register(RuntimeWorkLane.SESSION_DELIVERIES, object())
+ controller = SimpleNamespace(
platform_settings_managers={},
runtime_work_supervisor=supervisor,
)
@@ -13147,7 +14528,14 @@ def test_a_refused_result_stamp_cannot_complete_the_run_ok(tmp_path: Path, monke
calls: list = []
service = _scheduled_service_with_ledger(tmp_path, store, calls)
- queued = service.request_store.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ queued = service.request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="test-one-shot",
+ )
claimed = service.request_store.claim(queued.id)
assert claimed is not None
@@ -13225,6 +14613,9 @@ def test_refused_task_stamp_fails_durable_run_and_reconciles_its_delivery(
task.id,
source_kind="scheduler",
task=task,
+ expected_run_at=task.run_at,
+ expected_timezone=task.timezone,
+ expected_job_id="test-one-shot",
)
claimed = service.request_store.claim(queued.id)
assert claimed is not None
@@ -14850,7 +16241,12 @@ def _fire_command_task(
"""Fire one definition through the REAL claimed-request path; return its run row."""
queued = service.request_store.enqueue_task_run(
- task.id, source_kind="scheduler", task=task
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ expected_run_at=task.run_at if task.schedule_type == "at" else None,
+ expected_timezone=task.timezone if task.schedule_type == "at" else None,
+ expected_job_id=(f"test:{task.id}" if task.schedule_type == "at" else None),
)
claimed = service.request_store.claim(queued.id)
assert claimed is not None
@@ -15047,7 +16443,6 @@ def test_command_task_timeout_fails_the_run_with_the_timeout_exit_code(
assert (
definition_lifecycle_detail(
lifecycle_state="finished",
- definition_type="scheduled",
last_run_at=settled.last_run_at,
last_exit_code=settled.last_exit_code,
last_error=settled.last_error,
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 2e6acfc98..4f9598bee 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -6645,7 +6645,8 @@ def test_new_teardown_keeps_a_session_superseded_inside_its_window(tmp_path: Pat
_DEFINITION_RESUME_SELECT = (
- "SELECT run_definitions.definition_type, run_definitions.mode, run_definitions.enabled, "
+ "SELECT run_definitions.definition_type, run_definitions.mode, "
+ "run_definitions.schedule_type, run_definitions.retired_at, run_definitions.enabled, "
"run_definitions.session_id, run_definitions.metadata_json FROM run_definitions "
"WHERE run_definitions.id = ? AND run_definitions.deleted_at IS NULL"
)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 9f9002060..d0146f593 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20260811_0052"
+HEAD_REVISION = "20260812_0053"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
"session_id is not null and type in "
@@ -1967,6 +1967,52 @@ def test_retirement_marker_migration_is_forward_only(tmp_path: Path) -> None:
assert version == (HEAD_REVISION,)
+def test_retirement_reason_migration_preserves_legacy_unknowns(tmp_path: Path) -> None:
+ """0053 adds no inferred reason from clocks, edits, or run history."""
+
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260811_0052")
+ with sqlite3.connect(db_path) as conn:
+ conn.executemany(
+ """
+ insert into run_definitions (
+ id, definition_type, schedule_type, run_at, enabled,
+ last_run_at, retired_at, created_at, updated_at, metadata_json
+ ) values (?, 'scheduled', 'at', ?, 0, ?, ?, ?, ?, '{}')
+ """,
+ (
+ (
+ "legacy-ran",
+ "2026-07-26T09:00:00+00:00",
+ "2026-07-26T09:01:00+00:00",
+ "2026-07-26T09:01:00+00:00",
+ "2026-07-25T00:00:00+00:00",
+ "2026-07-31T00:00:00+00:00",
+ ),
+ (
+ "legacy-missed",
+ "2026-07-26T10:00:00+00:00",
+ None,
+ "2026-07-26T10:00:01+00:00",
+ "2026-07-25T00:00:00+00:00",
+ "2026-07-31T00:00:00+00:00",
+ ),
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ rows = conn.execute(
+ "select id, retirement_reason from run_definitions order by id"
+ ).fetchall()
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert rows == [("legacy-missed", None), ("legacy-ran", None)]
+ assert version == (HEAD_REVISION,)
+
+
def test_orphaned_owner_task_migration_marks_unbound_definitions(tmp_path: Path) -> None:
"""0052 blocks every resumable orphan and stops the ones still enabled."""
db_path = tmp_path / "vibe.sqlite"
@@ -5072,10 +5118,12 @@ def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:
"session_id": "sesk8m4q2p7x",
"session_key": "slack::channel::C123",
"prompt": "hello",
- "schedule_type": "cron",
- "cron": "0 * * * *",
+ "schedule_type": "at",
+ "run_at": "2026-05-15T01:00:00+00:00",
"timezone": "UTC",
- "enabled": True,
+ "enabled": False,
+ "retired_at": "2026-05-15T01:00:00+00:00",
+ "retirement_reason": "schedule_consumed",
"created_at": "2026-05-15T00:00:00+00:00",
"updated_at": "2026-05-15T00:00:00+00:00",
}
@@ -5099,7 +5147,8 @@ def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:
"lifetime_timeout_seconds": 3600,
"retry_exit_codes": [75],
"retry_delay_seconds": 30,
- "enabled": True,
+ "enabled": False,
+ "retired_at": "2026-05-15T02:00:00+00:00",
"created_at": "2026-05-15T00:00:00+00:00",
"updated_at": "2026-05-15T00:00:00+00:00",
}
@@ -5149,12 +5198,25 @@ def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:
assert report.counts["background_runs_imported"] == 2
with sqlite3.connect(db_path) as conn:
tasks = conn.execute(
- "select definition_type, session_id, legacy_session_key from run_definitions order by id"
+ "select definition_type, session_id, legacy_session_key, retired_at, retirement_reason "
+ "from run_definitions order by id"
).fetchall()
runs = conn.execute("select id, run_type, status, session_id, error from agent_runs order by id").fetchall()
assert tasks == [
- ("scheduled", "sesk8m4q2p7x", "slack::channel::C123"),
- ("watch", "sesk8m4q2p7x", "slack::channel::C123"),
+ (
+ "scheduled",
+ "sesk8m4q2p7x",
+ "slack::channel::C123",
+ "2026-05-15T01:00:00+00:00",
+ "schedule_consumed",
+ ),
+ (
+ "watch",
+ "sesk8m4q2p7x",
+ "slack::channel::C123",
+ "2026-05-15T02:00:00+00:00",
+ None,
+ ),
]
assert runs == [
("hook-1", "hook_send", "queued", "sesk8m4q2p7x", None),
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 996cbcd42..0458c9356 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1462,6 +1462,52 @@ def test_harness_task_resume_rejects_orphaned_owner_without_target(
}
+def test_harness_task_resume_rejects_retired_one_shot(monkeypatch, tmp_path):
+ from storage.background import SQLiteBackgroundTaskStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = SQLiteBackgroundTaskStore()
+ try:
+ store.upsert_scheduled_task(
+ {
+ "id": "retired-task",
+ "name": "Retired task",
+ "prompt": "run it",
+ "schedule_type": "at",
+ "run_at": "2026-08-11T00:00:00+00:00",
+ "timezone": "UTC",
+ "enabled": False,
+ "retired_at": "2026-08-11T00:00:01+00:00",
+ "retirement_reason": "schedule_missed",
+ "created_at": "2026-08-11T00:00:00+00:00",
+ "updated_at": "2026-08-11T00:00:01+00:00",
+ }
+ )
+ finally:
+ store.close()
+
+ client = app.test_client()
+ response = client.patch(
+ "/api/harness/tasks/retired-task",
+ json={"enabled": True},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 409
+ body = response.get_json()
+ assert body["code"] == "task_schedule_retired"
+ assert body["details"] == {"task_id": "retired-task"}
+ store = SQLiteBackgroundTaskStore()
+ try:
+ saved = store.get_scheduled_task("retired-task")
+ finally:
+ store.close()
+ assert saved is not None
+ assert saved["enabled"] is False
+ assert saved["retirement_reason"] == "schedule_missed"
+
+
def test_harness_bootstrap_returns_counts_and_selected_page(monkeypatch, tmp_path):
from storage.background import SQLiteBackgroundTaskStore
diff --git a/tests/test_watches.py b/tests/test_watches.py
index 4fb8310c3..a9b360827 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -548,6 +548,67 @@ def test_managed_watch_store_uses_sqlite_when_path_is_default(tmp_path: Path, mo
assert sqlite.get_watch(watch.id)["command"] == ["python3", "wait.py"]
+def test_hfr_479_late_cycle_cannot_replace_committed_watch_terminal_outcome(
+ tmp_path: Path,
+) -> None:
+ """HFR-479 -- the retiring cycle owns definition terminal fields forever."""
+
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ winner = ManagedWatchStore(tmp_path / "winner.json")
+ winner._sqlite = sqlite
+ late = ManagedWatchStore(tmp_path / "late.json")
+ late._sqlite = sqlite
+ watch = winner.add_watch(
+ name="ordered retirement",
+ session_key="",
+ command=[],
+ shell_command="true",
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ late.load()
+ late.maybe_reload() # establish the invalidation baseline before retirement
+ requests = TaskExecutionStore(tmp_path / "requests")
+ requests._sqlite = sqlite
+
+ assert winner.mark_cycle_result(
+ watch.id,
+ exit_code=7,
+ error="terminal cycle failed",
+ disable=True,
+ )
+ late_run = requests.build_hook_send(
+ session_key="",
+ prompt="late cycle evidence",
+ run_type="watch",
+ definition_id=watch.id,
+ source_kind="watch",
+ )
+ assert late.mark_cycle_result(
+ watch.id,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ disable=False,
+ queued_run=late_run.to_dict(),
+ )
+
+ stored = sqlite.get_watch(watch.id)
+ assert stored is not None
+ assert stored["retired_at"] is not None
+ assert stored["last_finished_at"] == stored["retired_at"]
+ assert stored["last_exit_code"] == 7
+ assert stored["last_error"] == "terminal cycle failed"
+ assert sqlite.get_run(late_run.id) is not None
+
+
def test_sqlite_remove_watch_soft_deletes_watch_but_keeps_runtime(tmp_path: Path) -> None:
sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
store = ManagedWatchStore(tmp_path / "watches.json")
diff --git a/ui/src/components/workbench/harnessLifecycle.test.ts b/ui/src/components/workbench/harnessLifecycle.test.ts
index e8e7c43f4..2eaa1cec8 100644
--- a/ui/src/components/workbench/harnessLifecycle.test.ts
+++ b/ui/src/components/workbench/harnessLifecycle.test.ts
@@ -79,7 +79,8 @@ describe('lifecycleLabel', () => {
['timeout', 'harness.lifecycle.timeout'],
['error', 'harness.lifecycle.error'],
[null, 'harness.lifecycle.finished'],
- ['missed', 'harness.lifecycle.finished'],
+ ['missed', 'harness.lifecycle.missed'],
+ ['canceled', 'harness.lifecycle.canceled'],
] as const;
it.each(outcomes)('maps finished detail %s to %s', (detail, expected) => {
@@ -112,6 +113,8 @@ describe('lifecycleLabel', () => {
'normal',
'timeout',
'error',
+ 'missed',
+ 'canceled',
'unknown',
]);
});
@@ -854,13 +857,19 @@ describe('definitionRowLine', () => {
it.each([
[
'an executed one-shot',
- { schedule_type: 'at', run_at: at(-2 * DAY), last_run_at: at(-DAY), updated_at: at(-3 * DAY) },
+ {
+ schedule_type: 'at',
+ run_at: at(-2 * DAY),
+ lifecycle_finished_at: at(-DAY),
+ last_run_at: at(-3 * DAY),
+ updated_at: at(-3 * DAY),
+ },
at(-DAY),
],
[
- 'a one-shot with no recorded run or finish',
- { schedule_type: 'at', run_at: at(-DAY), updated_at: at(-3 * DAY) },
- at(-DAY),
+ 'a missed one-shot with a retirement transition',
+ { schedule_type: 'at', run_at: at(-DAY), retired_at: at(-HOUR), updated_at: at(-3 * DAY) },
+ null,
],
['a retired watch', { mode: 'once', last_finished_at: at(-DAY), updated_at: at(-3 * DAY) }, at(-DAY)],
['a cron task', { cron: '0 * * * *', last_run_at: at(-HOUR), updated_at: at(-3 * DAY) }, at(-HOUR)],
@@ -868,6 +877,44 @@ describe('definitionRowLine', () => {
expect(definitionStateSince(row, 'finished')).toBe(expected);
});
+ it('does not borrow an old manual run time for an ownerless consumed one-shot', () => {
+ expect(
+ definitionStateSince(
+ {
+ schedule_type: 'at',
+ lifecycle_detail: null,
+ last_run_at: at(-3 * DAY),
+ retired_at: at(-HOUR),
+ updated_at: at(-MINUTE),
+ },
+ 'finished',
+ ),
+ ).toBeNull();
+ });
+
+ it('dates a missed one-shot only from its retirement transition', () => {
+ const retiredAt = at(-HOUR);
+ expect(
+ definitionStateSince(
+ {
+ lifecycle_detail: 'missed',
+ retired_at: retiredAt,
+ last_finished_at: at(-2 * DAY),
+ last_run_at: at(-3 * DAY),
+ run_at: at(-4 * DAY),
+ updated_at: at(-MINUTE),
+ },
+ 'finished',
+ ),
+ ).toBe(retiredAt);
+ expect(
+ definitionStateSince(
+ { lifecycle_detail: 'missed', last_run_at: at(-3 * DAY), updated_at: at(-MINUTE) },
+ 'finished',
+ ),
+ ).toBeNull();
+ });
+
it('does not report an intentionally retired waiter as dead', () => {
// A one-shot watch that just fired: the same call that recorded the catch
// stopped its waiter, and the agent run it spawned is still queued, so the
diff --git a/ui/src/components/workbench/harnessLifecycle.ts b/ui/src/components/workbench/harnessLifecycle.ts
index 562a342d9..80807f6f1 100644
--- a/ui/src/components/workbench/harnessLifecycle.ts
+++ b/ui/src/components/workbench/harnessLifecycle.ts
@@ -10,7 +10,7 @@ import { formatElapsed } from '../../lib/agentGraph';
// ---------------------------------------------------------------------------
export type HarnessLifecycleState = 'running' | 'waiting' | 'paused' | 'finished';
-export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error';
+export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error' | 'missed' | 'canceled';
// The filter chips, and the lifecycle states each one selects.
//
@@ -107,7 +107,7 @@ export function lifecycleLabel(
}
const STATES = new Set<string>(['running', 'waiting', 'paused', 'finished']);
-export const LIFECYCLE_DETAILS = ['normal', 'timeout', 'error'] as const;
+export const LIFECYCLE_DETAILS = ['normal', 'timeout', 'error', 'missed', 'canceled'] as const;
const DETAILS = new Set<string>(LIFECYCLE_DETAILS);
// ---------------------------------------------------------------------------
@@ -323,6 +323,7 @@ export type HarnessDefinitionFacts = {
last_started_at?: string | null;
last_finished_at?: string | null;
retired_at?: string | null;
+ lifecycle_finished_at?: string | null;
last_error?: string | null;
updated_at?: string | null;
// Derived server-side from the definition's own run history, because
@@ -629,12 +630,18 @@ export function definitionStateSince(
// can prove when the pause began.
case 'paused':
return null;
- // Prefer the most specific recorded event. A one-shot deadline is only the
- // fallback when neither a stored finish nor an actual run exists.
+ // A missed one-shot may carry results from an earlier manual run. Its
+ // retirement transition is the only clock that owns the Missed state.
case 'finished':
+ if (row.lifecycle_detail === 'missed') return row.lifecycle_finished_at ?? row.retired_at ?? null;
+ if (row.schedule_type === 'at') {
+ return row.lifecycle_finished_at ?? null;
+ }
return (
+ row.lifecycle_finished_at ??
row.last_finished_at ??
row.last_run_at ??
+ row.retired_at ??
(row.schedule_type === 'at' ? (row.run_at ?? null) : null) ??
definitionActivityAt(row)
);
@@ -740,7 +747,7 @@ export function definitionRowLine(
return {
primary: lifecycleLabel('finished', detail, t),
secondary: humanizeTime(since, t, now),
- alert: detail === 'error' || detail === 'timeout' ? detail : unhealthy,
+ alert: detail === 'error' || detail === 'timeout' ? detail : detail === 'missed' ? 'error' : unhealthy,
};
}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index af145edcc..bb79830a5 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1348,7 +1348,7 @@ export type HarnessSessionSummary = {
// one-shot that finished on its own indistinguishable from one the user paused.
// ``lifecycle_detail`` is set only on ``finished`` rows and says how they ended.
export type HarnessLifecycleState = 'running' | 'waiting' | 'paused' | 'finished';
-export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error';
+export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error' | 'missed' | 'canceled';
export type HarnessDefinitionHealth = 'failing' | 'degraded' | 'healthy' | 'unknown';
// The fields every task/watch row reads to describe its state.
@@ -1365,6 +1365,8 @@ export type HarnessDefinitionState = {
// "how long has this been running" must come from the run that is running,
// not from whenever the row last did anything.
running_since: string | null;
+ retired_at?: string | null;
+ lifecycle_finished_at?: string | null;
// Derived from this definition's own settled run outcomes, never from
// ``last_run_at``/``last_error``: those are overwritten on every fire, so one
// success used to erase days of failure and a daily-failing cron rendered
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index bc0f5b856..caf59fe3f 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3314,6 +3314,8 @@
"normal": "Finished",
"timeout": "Timed out",
"error": "Failed",
+ "missed": "Missed",
+ "canceled": "Canceled",
"unknown": "Unknown"
},
"failure": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 0ac9a4f9d..a9726e834 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3314,6 +3314,8 @@
"normal": "正常结束",
"timeout": "已超时",
"error": "出错结束",
+ "missed": "已错过",
+ "canceled": "已取消",
"unknown": "未知"
},
"failure": {
diff --git a/vibe/cli.py b/vibe/cli.py
index 2cf9bd1cd..31b7c033e 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -75,7 +75,9 @@ from storage.db import create_sqlite_engine
from storage.background import (
DefinitionWriteConflict,
SQLiteBackgroundTaskStore,
+ TASK_RETIREMENT_SCHEDULE_MISSED,
TaskResumeBlocked,
+ TaskScheduleRetired,
compute_next_run_at,
normalize_run_status,
)
@@ -1908,12 +1910,12 @@ def _task_display_name(task) -> str:
def _task_state(task) -> str:
- if task.enabled:
- return "active"
if _is_failed_one_shot(task):
return "failed"
if _is_completed_one_shot(task):
return "completed"
+ if task.enabled:
+ return "active"
return "paused"
@@ -2017,6 +2019,7 @@ def _task_payload(task, *, brief: bool = False):
_CANONICAL_DEFINITION_FIELDS = (
"lifecycle_state",
"lifecycle_detail",
+ "lifecycle_finished_at",
"next_run_at",
"waiting_since",
"running_since",
@@ -2063,7 +2066,14 @@ def _task_projection_state(task: Mapping[str, object]) -> str:
if lifecycle_state in {"waiting", "running"}:
return "active"
if lifecycle_state == "finished":
- return "failed" if task.get("lifecycle_detail") in {"timeout", "error"} else "completed"
+ lifecycle_detail = task.get("lifecycle_detail")
+ if lifecycle_detail == "canceled":
+ return "canceled"
+ if lifecycle_detail in {"timeout", "error", "missed"}:
+ return "failed"
+ if lifecycle_detail == "normal":
+ return "completed"
+ return "unknown"
if lifecycle_state == "paused":
return "paused"
return "unknown"
@@ -2226,18 +2236,21 @@ def _supported_task_platforms() -> set[str]:
def _is_completed_one_shot(task) -> bool:
return (
task.schedule_type == "at"
- and not task.enabled
+ and bool(task.retired_at)
and bool(task.last_run_at)
and not task.last_error
+ and task.retirement_reason != TASK_RETIREMENT_SCHEDULE_MISSED
)
def _is_failed_one_shot(task) -> bool:
return (
task.schedule_type == "at"
- and not task.enabled
- and bool(task.last_run_at)
- and bool(task.last_error)
+ and bool(task.retired_at)
+ and (
+ task.retirement_reason == TASK_RETIREMENT_SCHEDULE_MISSED
+ or (bool(task.last_run_at) and bool(task.last_error))
+ )
)
@@ -3865,6 +3878,18 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):
)
)
return 1
+ except TaskScheduleRetired as exc:
+ lang = _memory_cli_language()
+ _print_task_error(
+ TaskCliError(
+ i18n_t("error.taskScheduleRetired.message", lang),
+ code=exc.code,
+ hint=i18n_t("error.taskScheduleRetired.hint", lang, id=task_id),
+ help_command=f"vibe task update {task_id} --help",
+ details={"task_id": task_id},
+ )
+ )
+ return 1
except DefinitionWriteConflict as exc:
# Pause/resume is also a full-row write, so it is refused when a teardown
# changed the definition first. Reporting the switch as flipped would be a lie
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 6c1e94f63..18b76793e 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -80,7 +80,9 @@
"exitedWithDetail": "Command exited with status {code}: {detail}"
},
"task": {
- "resultNotRecorded": "The result of this run could not be recorded: the task was reclaimed, repointed or removed while it was running, so its stored state is unchanged."
+ "resultNotRecorded": "The result of this run could not be recorded: the task was reclaimed, repointed or removed while it was running, so its stored state is unchanged.",
+ "schedulerCallbackFailed": "The scheduled fire failed before it could be queued: {detail}",
+ "scheduleReplaced": "This scheduled fire belongs to an earlier task schedule and was not executed."
},
"queueCoalesced": {
"summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",
@@ -247,6 +249,10 @@
"message": "This Task's managing Session is no longer available.",
"hint": "Create a replacement Task from an available Agent Session, then remove this orphaned definition with `vibe task remove {id}`."
},
+ "taskScheduleRetired": {
+ "message": "This one-shot Task's schedule has already ended.",
+ "hint": "Set a new future time with `vibe task update {id} --at <time>`, then resume it."
+ },
"sessionFork": {
"agentUnavailable": {
"message": "The source session's Agent is no longer available for a new fork.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 4bf40d393..1cdf217ec 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -80,7 +80,9 @@
"exitedWithDetail": "\u547d\u4ee4\u9000\u51fa\uff0c\u72b6\u6001\u7801 {code}\uff1a{detail}"
},
"task": {
- "resultNotRecorded": "\u65e0\u6cd5\u8bb0\u5f55\u672c\u6b21\u8fd0\u884c\u7684\u7ed3\u679c\uff1a\u4efb\u52a1\u5728\u8fd0\u884c\u671f\u95f4\u88ab\u56de\u6536\u3001\u6539\u7ed1\u6216\u5220\u9664\uff0c\u5176\u5b58\u50a8\u72b6\u6001\u672a\u53d1\u751f\u53d8\u5316\u3002"
+ "resultNotRecorded": "\u65e0\u6cd5\u8bb0\u5f55\u672c\u6b21\u8fd0\u884c\u7684\u7ed3\u679c\uff1a\u4efb\u52a1\u5728\u8fd0\u884c\u671f\u95f4\u88ab\u56de\u6536\u3001\u6539\u7ed1\u6216\u5220\u9664\uff0c\u5176\u5b58\u50a8\u72b6\u6001\u672a\u53d1\u751f\u53d8\u5316\u3002",
+ "schedulerCallbackFailed": "\u8ba1\u5212\u89e6\u53d1\u5728\u5165\u961f\u524d\u5931\u8d25\uff1a{detail}",
+ "scheduleReplaced": "\u672c\u6b21\u8ba1\u5212\u89e6\u53d1\u5c5e\u4e8e\u4efb\u52a1\u7684\u65e7\u8c03\u5ea6\u7248\u672c\uff0c\u56e0\u6b64\u672a\u6267\u884c\u3002"
},
"queueCoalesced": {
"summary": "[Avibe Harness] 同一个 watch/task callback 在滚动 {window} 秒窗口内触发了 {count} 次。已将这些排队 callback 合并为一次 Agent turn。",
@@ -247,6 +249,10 @@
"message": "这个 Task 的管理 Session 已不可用。",
"hint": "请从可用的 Agent Session 创建替代 Task,再用 `vibe task remove {id}` 删除这条失去管理者的定义。"
},
+ "taskScheduleRetired": {
+ "message": "这个一次性 Task 的计划已经结束。",
+ "hint": "请先用 `vibe task update {id} --at <time>` 设置新的未来时间,再恢复它。"
+ },
"sessionFork": {
"agentUnavailable": {
"message": "源会话的 Agent 已无法用于创建新的复刻会话。",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8355d2a12..df5a4c3ca 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4182,6 +4182,19 @@ def _task_resume_blocked_response(exc):
)
+def _task_schedule_retired_response(exc):
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ return _coded_error_response(
+ exc.code,
+ t("error.taskScheduleRetired.message", lang),
+ 409,
+ hint=t("error.taskScheduleRetired.hint", lang, id=exc.definition_id),
+ details={"task_id": exc.definition_id},
+ )
+
+
def _show_page_error_response(exc):
code = getattr(exc, "code", "invalid_show_page_request")
# A conflict (not a malformed request) when the page is in the wrong state or
@@ -9324,7 +9337,7 @@ def harness_task_patch(task_id: str):
if "enabled" not in payload:
return jsonify({"ok": False, "code": "invalid_payload", "message": "missing 'enabled'"}), 400
enabled = bool(payload["enabled"])
- from storage.background import TaskResumeBlocked
+ from storage.background import TaskResumeBlocked, TaskScheduleRetired
with _harness_store() as store:
if not store.get_scheduled_task(task_id):
@@ -9333,6 +9346,8 @@ def harness_task_patch(task_id: str):
store.set_definition_enabled(task_id, enabled, definition_type="scheduled")
except TaskResumeBlocked as exc:
return _task_resume_blocked_response(exc)
+ except TaskScheduleRetired as exc:
+ return _task_schedule_retired_response(exc)
task = store.get_scheduled_task(task_id)
from core.inbox_events import publish_definitions_updated