-
Notifications
You must be signed in to change notification settings - Fork 13
fix: revoke stale jobs to "revoked" status instead of "pending" #1169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
703400b
fix: revoke stale jobs by default instead of setting PENDING
mihow 281e931
refactor: extract check_stale_jobs() for reuse by periodic task
mihow b69d489
refactor: move jobs tests into tests/ package
mihow 0bf2867
fix: correct stale job handling in check_stale_jobs()
mihow 1a733b9
fix: extend async_api progress guard to FAILURE, add cleanup to termi…
mihow 5bb47e5
fix: use select_for_update to prevent concurrent stale-job processing
mihow 2c2d3f5
fix: catch Celery backend errors in stale-job cleanup loop
mihow File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,38 +1,37 @@ | ||
| from celery import states | ||
| from celery.result import AsyncResult | ||
| from django.core.management.base import BaseCommand | ||
| from django.utils import timezone | ||
|
|
||
| from ami.jobs.models import Job, JobState | ||
| from ami.jobs.models import Job | ||
| from ami.jobs.tasks import check_stale_jobs | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = ( | ||
| "Update the status of all jobs that are not in a final state " "and have not been updated in the last X hours." | ||
| ) | ||
| help = "Revoke stale jobs that have not been updated within the cutoff period." | ||
|
|
||
| # Add argument for the number of hours to consider a job stale | ||
| def add_arguments(self, parser): | ||
| parser.add_argument( | ||
| "--hours", | ||
| type=int, | ||
| default=Job.FAILED_CUTOFF_HOURS, | ||
| help="Number of hours to consider a job stale", | ||
| help="Number of hours to consider a job stale (default: %(default)s)", | ||
| ) | ||
| parser.add_argument( | ||
| "--dry-run", | ||
| action="store_true", | ||
| help="Show what would be done without making changes", | ||
| ) | ||
|
|
||
| def handle(self, *args, **options): | ||
| stale_jobs = Job.objects.filter( | ||
| status__in=JobState.running_states(), | ||
| updated_at__lt=timezone.now() - timezone.timedelta(hours=options["hours"]), | ||
| ) | ||
| results = check_stale_jobs(hours=options["hours"], dry_run=options["dry_run"]) | ||
|
|
||
| if not results: | ||
| self.stdout.write("No stale jobs found.") | ||
| return | ||
|
|
||
| for job in stale_jobs: | ||
| task = AsyncResult(job.task_id) if job.task_id else None | ||
| if task: | ||
| job.update_status(task.state, save=False) | ||
| job.save() | ||
| self.stdout.write(self.style.SUCCESS(f"Updated status of job {job.pk} to {task.state}")) | ||
| prefix = "[dry-run] " if options["dry_run"] else "" | ||
| for r in results: | ||
| if r["action"] == "updated": | ||
| self.stdout.write( | ||
| self.style.SUCCESS(f"{prefix}Job {r['job_id']}: updated to {r['state']} (from Celery)") | ||
| ) | ||
| else: | ||
| self.stdout.write(self.style.WARNING(f"Job {job.pk} has no associated task, setting status to FAILED")) | ||
| job.update_status(states.FAILURE, save=False) | ||
| job.save() | ||
| self.stdout.write(self.style.WARNING(f"{prefix}Job {r['job_id']}: revoked (no known Celery state)")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| from datetime import timedelta | ||
| from unittest.mock import patch | ||
|
|
||
| from django.test import TestCase | ||
| from django.utils import timezone | ||
|
|
||
| from ami.jobs.models import Job, JobDispatchMode, JobState | ||
| from ami.jobs.tasks import check_stale_jobs | ||
| from ami.main.models import Project | ||
|
|
||
|
|
||
| class CheckStaleJobsTest(TestCase): | ||
| def setUp(self): | ||
| self.project = Project.objects.create(name="Stale jobs test project") | ||
|
|
||
| def _create_job(self, status=JobState.STARTED, hours_ago=100, task_id=None): | ||
| job = Job.objects.create( | ||
| project=self.project, | ||
| name=f"Test job {status}", | ||
| status=status, | ||
| ) | ||
| Job.objects.filter(pk=job.pk).update( | ||
| updated_at=timezone.now() - timedelta(hours=hours_ago), | ||
| ) | ||
| if task_id is not None: | ||
| Job.objects.filter(pk=job.pk).update(task_id=task_id) | ||
| job.refresh_from_db() | ||
| return job | ||
|
|
||
| @patch("ami.jobs.tasks.cleanup_async_job_if_needed") | ||
| def test_dry_run(self, mock_cleanup): | ||
| """Dry run returns results without modifying jobs.""" | ||
| job = self._create_job(status=JobState.STARTED) | ||
|
|
||
| results = check_stale_jobs(dry_run=True) | ||
|
|
||
| self.assertEqual(len(results), 1) | ||
| self.assertEqual(results[0]["action"], "revoked") | ||
| job.refresh_from_db() | ||
| self.assertEqual(job.status, JobState.STARTED.value) | ||
| mock_cleanup.assert_not_called() | ||
|
|
||
| @patch("ami.jobs.tasks.cleanup_async_job_if_needed") | ||
| def test_revokes_stale_job(self, mock_cleanup): | ||
| """Stale job without a known Celery state is revoked and cleaned up.""" | ||
| job = self._create_job(status=JobState.STARTED) | ||
|
|
||
| results = check_stale_jobs() | ||
|
|
||
| self.assertEqual(len(results), 1) | ||
| result = results[0] | ||
| self.assertEqual(result["action"], "revoked") | ||
| self.assertEqual(result["previous_status"], JobState.STARTED) | ||
| job.refresh_from_db() | ||
| self.assertEqual(job.status, JobState.REVOKED.value) | ||
| self.assertIsNotNone(job.finished_at) | ||
| mock_cleanup.assert_called_once_with(job) | ||
|
|
||
| @patch("ami.jobs.tasks.cleanup_async_job_if_needed") | ||
|
mihow marked this conversation as resolved.
|
||
| @patch("celery.result.AsyncResult") | ||
| def test_updates_status_from_known_celery_state(self, mock_async_result, mock_cleanup): | ||
| """Stale job with a terminal Celery state is updated (not revoked).""" | ||
| from celery import states | ||
|
|
||
| mock_async_result.return_value.state = states.FAILURE | ||
| job = self._create_job(status=JobState.STARTED, task_id="some-celery-task-id") | ||
|
|
||
| results = check_stale_jobs() | ||
|
|
||
| self.assertEqual(len(results), 1) | ||
| result = results[0] | ||
| self.assertEqual(result["action"], "updated") | ||
| self.assertEqual(result["state"], states.FAILURE) | ||
| job.refresh_from_db() | ||
| self.assertEqual(job.status, JobState.FAILURE.value) | ||
| self.assertIsNotNone(job.finished_at) | ||
| mock_cleanup.assert_called_once_with(job) | ||
|
|
||
| @patch("ami.jobs.tasks.cleanup_async_job_if_needed") | ||
| @patch("celery.result.AsyncResult") | ||
| def test_revokes_success_with_incomplete_progress(self, mock_async_result, mock_cleanup): | ||
| """async_api job where Celery reports SUCCESS but progress is incomplete is revoked.""" | ||
| from celery import states | ||
|
|
||
| mock_async_result.return_value.state = states.SUCCESS | ||
| job = self._create_job(status=JobState.STARTED, task_id="some-celery-task-id") | ||
| Job.objects.filter(pk=job.pk).update(dispatch_mode=JobDispatchMode.ASYNC_API) | ||
| job.refresh_from_db() | ||
| # job.progress.is_complete() returns False by default (no stages completed) | ||
|
|
||
| results = check_stale_jobs() | ||
|
|
||
| self.assertEqual(len(results), 1) | ||
| self.assertEqual(results[0]["action"], "revoked") | ||
| job.refresh_from_db() | ||
| self.assertEqual(job.status, JobState.REVOKED.value) | ||
| mock_cleanup.assert_called_once_with(job) | ||
|
|
||
| @patch("ami.jobs.tasks.cleanup_async_job_if_needed") | ||
| @patch("celery.result.AsyncResult") | ||
| def test_revokes_when_celery_lookup_fails(self, mock_async_result, mock_cleanup): | ||
| """Job is revoked if Celery state lookup raises an exception.""" | ||
| mock_async_result.side_effect = ConnectionError("broker down") | ||
| job = self._create_job(status=JobState.STARTED, task_id="unreachable-task") | ||
|
|
||
| results = check_stale_jobs() | ||
|
|
||
| self.assertEqual(len(results), 1) | ||
| self.assertEqual(results[0]["action"], "revoked") | ||
| job.refresh_from_db() | ||
| self.assertEqual(job.status, JobState.REVOKED.value) | ||
| mock_cleanup.assert_called_once_with(job) | ||
|
|
||
| @patch("ami.jobs.tasks.cleanup_async_job_if_needed") | ||
| def test_skips_recent_and_final_state_jobs(self, mock_cleanup): | ||
| """Recent jobs and jobs in final states are not touched.""" | ||
| self._create_job(status=JobState.STARTED, hours_ago=1) # recent | ||
| self._create_job(status=JobState.SUCCESS, hours_ago=200) # final state | ||
|
|
||
| results = check_stale_jobs() | ||
|
|
||
| self.assertEqual(results, []) | ||
| mock_cleanup.assert_not_called() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.