Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): Clean up orphaned schedules without schedule_id (#11927)

Bently65e3f4822a67
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index eecdf1ccb3..85fb566cb2 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -347,26 +347,35 @@ async def _reschedule_one_shot_after_cap(args: "CopilotTurnJobArgs") -> None:
async def _best_effort_unschedule(
- schedule_id: str | None, user_id: str, *, reason: str
+ schedule_id: str | None, graph_id: str | None, user_id: str, *, reason: str
) -> None:
"""Self-delete a schedule whose firing condition is no longer satisfiable
(graph deleted, session deleted, validation failure, etc.).
- Best-effort: failures are logged and swallowed. For recurring schedules
- the next cron tick will re-attempt the cleanup; for one-shot schedules
- APScheduler removes the job after fire anyway, so a missed delete
- here doesn't accumulate orphans indefinitely.
+ ``graph_id`` enables targeted cleanup of legacy jobs that predate
+ ``schedule_id``; copilot-turn schedules have no graph to target and pass
+ ``None``. Best-effort: failures are logged and swallowed. For recurring
+ schedules the next cron tick will re-attempt the cleanup; for one-shot
+ schedules APScheduler removes the job after fire anyway, so a missed
+ delete here doesn't accumulate orphans indefinitely.
"""
- if not schedule_id:
- logger.warning(
- f"Cannot unschedule (reason: {reason}) — no schedule_id "
- f"available; this is an old job, remove manually"
- )
- return
try:
- await get_scheduler_client().delete_schedule(
- schedule_id=schedule_id, user_id=user_id
- )
+ if schedule_id:
+ await get_scheduler_client().delete_schedule(
+ schedule_id=schedule_id, user_id=user_id
+ )
+ elif graph_id is not None:
+ logger.warning(
+ f"Old scheduled job for graph {graph_id} (user {user_id}) "
+ f"has no schedule_id, attempting targeted cleanup"
+ )
+ await _cleanup_old_schedules_without_id(graph_id, user_id=user_id)
+ else:
+ logger.warning(
+ f"Cannot unschedule (reason: {reason}) — no schedule_id "
+ f"available; this is an old job, remove manually"
+ )
+ return
logger.info(f"Unscheduled job {schedule_id} (reason: {reason})")
except Exception:
logger.warning(
@@ -377,8 +386,10 @@ async def _best_effort_unschedule(
async def _self_delete_copilot_turn_schedule(args: "CopilotTurnJobArgs") -> None:
"""Convenience wrapper for copilot-turn schedules whose target session is gone."""
+ # Copilot-turn schedules aren't graph-bound — no graph target for legacy
+ # cleanup, so a schedule_id-less job can only be removed manually.
await _best_effort_unschedule(
- args.schedule_id, args.user_id, reason="session deleted"
+ args.schedule_id, None, args.user_id, reason="session deleted"
)
@@ -388,6 +399,7 @@ async def _handle_graph_validation_error(args: "GraphExecutionJobArgs") -> None:
)
await _best_effort_unschedule(
args.schedule_id,
+ args.graph_id,
args.user_id,
reason=f"graph {args.graph_id} validation failed",
)
@@ -433,6 +445,35 @@ async def _cleanup_orphaned_schedules_for_graph(graph_id: str, user_id: str) ->
)
+async def _cleanup_old_schedules_without_id(graph_id: str, user_id: str) -> None:
+ """Remove only schedules that have no schedule_id in their job args.
+
+ Unlike _cleanup_orphaned_schedules_for_graph (which removes ALL schedules
+ for a graph), this only targets legacy jobs created before schedule_id was
+ added to GraphExecutionJobArgs, preserving any valid newer schedules.
+ """
+ scheduler_client = get_scheduler_client()
+ schedules = await scheduler_client.get_execution_schedules(
+ graph_id=graph_id, user_id=user_id
+ )
+
+ for schedule in schedules:
+ if schedule.schedule_id is not None:
+ continue
+ try:
+ await scheduler_client.delete_schedule(
+ schedule_id=schedule.id, user_id=user_id
+ )
+ logger.info(
+ f"Cleaned up old schedule {schedule.id} (no schedule_id) "
+ f"for graph {graph_id}"
+ )
+ except Exception:
+ logger.exception(
+ f"Failed to delete old schedule {schedule.id} for graph {graph_id}"
+ )
+
+
def cleanup_expired_files():
"""Clean up expired files from cloud storage."""
# Wait for completion
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index 7f8b419155..31858d1a99 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -19,7 +19,9 @@ from backend.executor.scheduler import (
GraphExecutionJobArgs,
GraphExecutionJobInfo,
Scheduler,
+ _best_effort_unschedule,
_build_trigger,
+ _cleanup_old_schedules_without_id,
_execute_copilot_turn,
_job_to_info,
_next_run_time_iso,
@@ -349,6 +351,56 @@ async def test_self_delete_copilot_turn_swallows_errors():
await _self_delete_copilot_turn_schedule(args)
+# ---------------------------------------------------------------------------
+# _best_effort_unschedule / _cleanup_old_schedules_without_id
+# ---------------------------------------------------------------------------
+
+
+def _schedule_info(schedule_id: str | None, job_id: str) -> MagicMock:
+ info = MagicMock()
+ info.schedule_id = schedule_id
+ info.id = job_id
+ return info
+
+
+async def test_unschedule_without_id_runs_targeted_graph_cleanup():
+ mock_client = AsyncMock()
+ mock_client.get_execution_schedules.return_value = [
+ _schedule_info(None, "legacy-job"),
+ _schedule_info("sched-9", "valid-job"),
+ ]
+ with patch(f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=mock_client):
+ await _best_effort_unschedule(None, "graph-1", "user-1", reason="test")
+ # Only the schedule_id-less legacy job is deleted; valid ones survive.
+ mock_client.delete_schedule.assert_awaited_once_with(
+ schedule_id="legacy-job", user_id="user-1"
+ )
+
+
+async def test_unschedule_without_id_or_graph_is_a_no_op():
+ mock_client = AsyncMock()
+ with patch(f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=mock_client):
+ await _best_effort_unschedule(None, None, "user-1", reason="test")
+ mock_client.delete_schedule.assert_not_awaited()
+ mock_client.get_execution_schedules.assert_not_awaited()
+
+
+async def test_cleanup_old_schedules_swallows_per_schedule_delete_errors():
+ mock_client = AsyncMock()
+ mock_client.get_execution_schedules.return_value = [
+ _schedule_info(None, "legacy-1"),
+ _schedule_info(None, "legacy-2"),
+ ]
+ mock_client.delete_schedule.side_effect = [RuntimeError("boom"), None]
+ with patch(f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=mock_client):
+ # Must not raise, and must still attempt the second delete.
+ await _cleanup_old_schedules_without_id("graph-1", user_id="user-1")
+ assert mock_client.delete_schedule.await_count == 2
+
+
# ---------------------------------------------------------------------------
# _reschedule_one_shot_after_cap
# ---------------------------------------------------------------------------