Explorar el Código

Closes #23737: Support per-job retention periods (#23836)

Allow job runners to define a default lifetime, which can be overridden
or disabled when enqueueing a job. Calculate expiration upon completion,
independently of the global JOB_RETENTION setting.

Introduce an hourly system job to delete expired jobs and their
notifications in locked, bounded batches to limit memory consumption
and prevent race conditions with concurrent retries.

Set a default lifetime of 24 hours for background REST API jobs.
Jeremy Stretch hace 1 día
padre
commit
67b664c8e0

+ 2 - 0
docs/configuration/miscellaneous.md

@@ -167,6 +167,8 @@ Default: `90`
 
 The number of days to retain job results (scripts and reports). Set this to `0` to retain job results in the database indefinitely.
 
+Jobs which have a [lifetime](../features/background-jobs.md#job-lifetime) (such as those for background REST API bulk operations) are deleted once their lifetime runs out, even if that is sooner than the retention period, or if this is set to `0`.
+
 !!! warning
     If enabling indefinite job results retention, it is recommended to periodically delete old entries. Otherwise, the database may eventually exceed capacity.
 

+ 8 - 0
docs/features/background-jobs.md

@@ -18,6 +18,14 @@ Each job has an access class, which determines who may access it in addition to
 
 Superusers can access all jobs regardless of access class. The access class applies to every action, so only superusers can view or delete another user's requester jobs, even if permitted to delete jobs. (Housekeeping still purges all jobs under [`JOB_RETENTION`](../configuration/miscellaneous.md#job_retention).)
 
+## Job Lifetime
+
+!!! info "This feature was introduced in NetBox v4.8."
+
+A job runner may declare a lifetime for the jobs it creates. Once such a job has finished (whether completed, failed, or errored), it expires when its lifetime runs out, and is deleted by a system job which runs hourly. Pending, scheduled, and running jobs never expire. For example, the jobs for background REST API bulk operations have a lifetime of 24 hours.
+
+A job's lifetime applies regardless of the [`JOB_RETENTION`](../configuration/miscellaneous.md#job_retention) setting, which remains an upper limit: a job is deleted when it expires or when it exceeds the retention period, whichever comes first. Jobs without a lifetime are subject only to `JOB_RETENTION`.
+
 ## Scheduled Jobs
 
 Background jobs can be configured to run immediately, or at a set time in the future. Scheduled jobs can also be configured to repeat at a set interval.

+ 1 - 1
docs/integrations/rest-api.md

@@ -795,7 +795,7 @@ Poll the job's URL to track its progress. When the job reaches a terminal status
 
 A failed job records the equivalent error response, for instance `{"status_code": 400, "data": {"slug": ["This field may not be blank."]}}`, with a short summary also placed in the job's `error` field.
 
-A `202` response indicates that the request was accepted and queued, not that it succeeded: validation (including malformed or invalid payloads) and the database write all occur when the job runs. A rejected payload is therefore reported as a failed job rather than a synchronous error response. Always inspect the job's final status to confirm the outcome. The job is accessible only to the user who submitted the request (who must also be permitted to view jobs, `core.view_job`) and to superusers. Jobs created before NetBox v4.8 are not restricted in this way and remain accessible to any user permitted to view jobs until they are purged under [`JOB_RETENTION`](../configuration/miscellaneous.md#job_retention).
+A `202` response indicates that the request was accepted and queued, not that it succeeded: validation (including malformed or invalid payloads) and the database write all occur when the job runs. A rejected payload is therefore reported as a failed job rather than a synchronous error response. Always inspect the job's final status to confirm the outcome. The job expires 24 hours after it finishes and is deleted shortly afterward, so its result must be retrieved within this window. The job is accessible only to the user who submitted the request (who must also be permitted to view jobs, `core.view_job`) and to superusers. Jobs created before NetBox v4.8 are not restricted in this way and remain accessible to any user permitted to view jobs until they are purged under [`JOB_RETENTION`](../configuration/miscellaneous.md#job_retention).
 
 Background processing applies only to bulk operations (a JSON list) on a model's list endpoint. For a single-object write the `background` parameter is ignored and the request is processed synchronously. It cannot be combined with an [`If-Match`](#if-match) precondition (which cannot be evaluated reliably once execution is deferred); such a request is rejected with an `HTTP 400` response. If no background worker is running to service the queue, the request is rejected with an `HTTP 503` response rather than enqueuing a job that would never run.
 

+ 12 - 0
docs/models/core/job.md

@@ -59,6 +59,18 @@ The job's access class, which determines which users may access the job in addit
 | Object | Only users permitted to view the job's assigned object |
 | Shared | Any user permitted to view jobs |
 
+### Lifetime
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The amount of time (in minutes) for which the job is retained after it has finished. It is set by the job runner when the job is created. A job without a lifetime is retained until it is purged under [`JOB_RETENTION`](../../configuration/miscellaneous.md#job_retention).
+
+### Expires
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The date and time at which the job expires, calculated from its completion time and lifetime. An expired job is removed by the next hourly cleanup run. This is populated only once a job with a lifetime has finished.
+
 ### Data
 
 Any data associated with the execution of the job, such as log output.

+ 15 - 1
docs/plugins/development/background-jobs.md

@@ -52,7 +52,7 @@ The default [access class](../../models/core/job.md#access) for jobs created by
 A job with the `object` access class must be assigned to an object: calling `enqueue()` without an `instance` raises a `ValueError`. The default may be overridden for an individual job by passing `access` to `enqueue()`.
 
 !!! warning
-    A subclass of a job runner which declares its own `Meta` class does not inherit the parent's `access`, and falls back to `shared`. Either subclass the parent's `Meta` (e.g. `class Meta(ScriptJob.Meta)`) or declare `access` again.
+    A subclass of a job runner which declares its own `Meta` class does not inherit the parent's `access` or `lifetime`: they fall back to `shared` and no lifetime, respectively. Either subclass the parent's `Meta` (e.g. `class Meta(ScriptJob.Meta)`) or declare them again.
 
 ```python
 from core.choices import JobAccessChoices
@@ -64,6 +64,20 @@ class MyTestJob(JobRunner):
         access = JobAccessChoices.ACCESS_OBJECT
 ```
 
+#### `lifetime`
+
+The default [lifetime](../../features/background-jobs.md#job-lifetime) for jobs created by this runner, in minutes. Once a job has finished, it is deleted automatically when its lifetime runs out, regardless of [`JOB_RETENTION`](../../configuration/miscellaneous.md#job_retention). If omitted, jobs are subject only to `JOB_RETENTION`. The default may be overridden for an individual job by passing `lifetime` to `enqueue()`, or disabled by passing `lifetime=None`.
+
+```python
+from core.choices import JobIntervalChoices
+from netbox.jobs import JobRunner
+
+class MyTestJob(JobRunner):
+    class Meta:
+        name = "My Test Job"
+        lifetime = JobIntervalChoices.INTERVAL_DAILY
+```
+
 ### Logging
 
 A Python logger is instantiated by the runner for each job. It can be utilized within a job's `run()` method as needed:

+ 1 - 1
netbox/core/api/serializers_/jobs.py

@@ -47,6 +47,6 @@ class JobSerializer(BaseModelSerializer):
         fields = [
             'id', 'url', 'display_url', 'display', 'object_type', 'object_id', 'object', 'name', 'status', 'created',
             'scheduled', 'interval', 'started', 'completed', 'execution_time', 'user', 'data', 'error', 'job_id',
-            'queue_name', 'notifications', 'access', 'parent', 'child_count', 'log_entries',
+            'queue_name', 'notifications', 'access', 'lifetime', 'expires', 'parent', 'child_count', 'log_entries',
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'created', 'completed', 'user', 'status')

+ 10 - 1
netbox/core/filtersets.py

@@ -131,6 +131,15 @@ class JobFilterSet(BaseFilterSet):
         field_name='completed',
         lookup_expr='gte'
     )
+    expires = django_filters.DateTimeFilter()
+    expires__before = django_filters.DateTimeFilter(
+        field_name='expires',
+        lookup_expr='lte'
+    )
+    expires__after = django_filters.DateTimeFilter(
+        field_name='expires',
+        lookup_expr='gte'
+    )
     execution_time = django_filters.DurationFilter(
         label=_('Execution time')
     )
@@ -189,7 +198,7 @@ class JobFilterSet(BaseFilterSet):
         model = Job
         fields = (
             'id', 'object_type', 'object_type_id', 'object_id', 'name', 'interval', 'status', 'user', 'job_id',
-            'queue_name', 'execution_time',
+            'queue_name', 'execution_time', 'lifetime',
         )
 
     def search(self, queryset, name, value):

+ 12 - 1
netbox/core/forms/filtersets.py

@@ -80,7 +80,8 @@ class JobFilterForm(SavedFiltersMixin, FilterForm):
         FieldSet('parent_id', 'has_parent', name=_('Hierarchy')),
         FieldSet(
             'created__before', 'created__after', 'scheduled__before', 'scheduled__after', 'started__before',
-            'started__after', 'completed__before', 'completed__after', name=_('Scheduling')
+            'started__after', 'completed__before', 'completed__after', 'expires__before', 'expires__after',
+            name=_('Scheduling')
         ),
         FieldSet('execution_time__gte', 'execution_time__lte', name=_('Execution')),
     )
@@ -143,6 +144,16 @@ class JobFilterForm(SavedFiltersMixin, FilterForm):
         required=False,
         widget=DateTimePicker()
     )
+    expires__after = forms.DateTimeField(
+        label=_('Expires after'),
+        required=False,
+        widget=DateTimePicker()
+    )
+    expires__before = forms.DateTimeField(
+        label=_('Expires before'),
+        required=False,
+        widget=DateTimePicker()
+    )
     user_id = DynamicModelMultipleChoiceField(
         queryset=User.objects.all(),
         required=False,

+ 42 - 1
netbox/core/jobs.py

@@ -5,12 +5,15 @@ from importlib import import_module
 import requests
 from django.conf import settings
 from django.core.cache import cache
+from django.db import router, transaction
 from django.db.models import Exists, OuterRef, Subquery
 from django.utils import timezone
 from packaging import version
 
-from core.models import Job, ObjectChange
+from core.models import Job, ObjectChange, ObjectType
+from extras.models import Notification
 from netbox.config import Config
+from netbox.constants import JOB_DELETE_BATCH_SIZE
 from netbox.jobs import JobRunner, system_job
 from netbox.search.backends import search_backend
 from utilities.proxy import resolve_proxies
@@ -59,6 +62,44 @@ class SyncDataSourceJob(JobRunner):
         self.logger.info("Syncing completed successfully")
 
 
+@system_job(interval=JobIntervalChoices.INTERVAL_HOURLY)
+class HourlyCleanupJob(JobRunner):
+    """
+    Perform hourly cleanup tasks.
+    """
+    class Meta:
+        name = 'Hourly Cleanup'
+        lifetime = JobIntervalChoices.INTERVAL_DAILY
+
+    def run(self, *args, **kwargs):
+        self.delete_expired_jobs()
+
+    def delete_expired_jobs(self):
+        """
+        Delete finished jobs whose lifetime has expired, along with their notifications.
+        """
+        using = router.db_for_write(Job)
+        job_type = ObjectType.objects.get_for_model(Job)
+        expired_pks = (
+            Job.objects.using(using)
+            .filter(expires__lte=timezone.now())
+            .order_by('pk')
+            .select_for_update(skip_locked=True)
+            .values_list('pk', flat=True)
+        )
+        count = 0
+        while True:
+            # Lock each batch, so a concurrent retry can't reset a job between its selection and deletion
+            with transaction.atomic(using=using):
+                if not (pks := list(expired_pks[:JOB_DELETE_BATCH_SIZE])):
+                    break
+                Notification.objects.using(using).filter(object_type=job_type, object_id__in=pks).delete()
+                # only('pk') keeps each job's data and log entries out of memory during deletion
+                Job.objects.using(using).filter(pk__in=pks).only('pk').delete()
+            count += len(pks)
+        self.logger.info(f"Deleted {count} expired jobs")
+
+
 @system_job(interval=JobIntervalChoices.INTERVAL_DAILY)
 class SystemHousekeepingJob(JobRunner):
     """

+ 31 - 0
netbox/core/migrations/0030_job_lifetime.py

@@ -0,0 +1,31 @@
+import django.core.validators
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('contenttypes', '0002_remove_content_type_name'),
+        ('core', '0029_job_parent'),
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='job',
+            name='expires',
+            field=models.DateTimeField(blank=True, editable=False, null=True),
+        ),
+        migrations.AddField(
+            model_name='job',
+            name='lifetime',
+            field=models.PositiveIntegerField(
+                blank=True, null=True, validators=[django.core.validators.MinValueValidator(1)]
+            ),
+        ),
+        migrations.AddIndex(
+            model_name='job',
+            index=models.Index(fields=['expires'], name='core_job_expires_a2dcaf_idx'),
+        ),
+    ]

+ 28 - 0
netbox/core/models/jobs.py

@@ -1,6 +1,7 @@
 import logging
 import uuid
 from dataclasses import asdict
+from datetime import timedelta
 from functools import cached_property, partial
 
 import django_rq
@@ -147,6 +148,21 @@ class Job(models.Model):
         default=JobAccessChoices.ACCESS_SHARED,
         help_text=_('Determines which users may access the job, in addition to the permissions assigned for jobs')
     )
+    lifetime = models.PositiveIntegerField(
+        verbose_name=_('lifetime'),
+        blank=True,
+        null=True,
+        validators=(
+            MinValueValidator(1),
+        ),
+        help_text=_('Time to retain the job after it finishes (in minutes)')
+    )
+    expires = models.DateTimeField(
+        verbose_name=_('expires'),
+        null=True,
+        blank=True,
+        editable=False
+    )
     log_entries = ArrayField(
         verbose_name=_('log entries'),
         base_field=models.JSONField(
@@ -164,6 +180,7 @@ class Job(models.Model):
         indexes = (
             models.Index(fields=('-created',)),  # Default ordering
             models.Index(fields=('object_type', 'object_id')),
+            models.Index(fields=('expires',)),
         )
         verbose_name = _('job')
         verbose_name_plural = _('jobs')
@@ -208,6 +225,12 @@ class Job(models.Model):
             ]
         super().save(*args, **kwargs)
 
+    @property
+    def lifetime_duration(self):
+        if self.lifetime is None:
+            return None
+        return timedelta(minutes=self.lifetime)
+
     @property
     def duration(self):
         if not self.completed:
@@ -296,6 +319,8 @@ class Job(models.Model):
         self.completed = timezone.now()
         if self.started:
             self.execution_time = self.completed - self.started
+        if self.lifetime:
+            self.expires = self.completed + timedelta(minutes=self.lifetime)
         self.save()
 
         if dispatch:
@@ -347,6 +372,7 @@ class Job(models.Model):
             queue_name=None,
             notifications=None,
             access=None,
+            lifetime=None,
             parent=None,
             **kwargs
     ):
@@ -364,6 +390,7 @@ class Job(models.Model):
                 management commands only.
             notifications: Notification behavior on job completion (always, on_failure, or never)
             access: The job's access class (requester, object, or shared; defaults to shared)
+            lifetime: Time to retain the job after it finishes (in minutes; optional)
             parent: The Job which is enqueuing this job (optional)
         """
         if schedule_at and immediate:
@@ -393,6 +420,7 @@ class Job(models.Model):
             queue_name=rq_queue_name,
             notifications=notifications if notifications is not None else JobNotificationChoices.NOTIFICATION_ALWAYS,
             access=access,
+            lifetime=lifetime,
             # Assigned by ID, so the parent instance isn't pickled into the RQ payload
             parent_id=parent.pk if parent else None,
         )

+ 8 - 1
netbox/core/tables/jobs.py

@@ -54,6 +54,12 @@ class JobTable(NetBoxTable):
     access = columns.ChoiceFieldColumn(
         verbose_name=_('Access'),
     )
+    lifetime = columns.DurationColumn(
+        verbose_name=_('Lifetime'),
+    )
+    expires = columns.DateTimeColumn(
+        verbose_name=_('Expires'),
+    )
     parent = tables.Column(
         verbose_name=_('Parent'),
         linkify=True
@@ -69,7 +75,8 @@ class JobTable(NetBoxTable):
         model = Job
         fields = (
             'pk', 'id', 'object_type', 'object', 'name', 'status', 'created', 'scheduled', 'interval', 'started',
-            'completed', 'execution_time', 'user', 'queue_name', 'access', 'log_entries', 'error', 'job_id', 'parent',
+            'completed', 'execution_time', 'user', 'queue_name', 'access', 'lifetime', 'expires', 'log_entries',
+            'error', 'job_id', 'parent',
         )
         default_columns = (
             'pk', 'id', 'object_type', 'object', 'name', 'status', 'created', 'started', 'completed', 'execution_time',

+ 16 - 0
netbox/core/tests/test_filtersets.py

@@ -283,12 +283,16 @@ class JobTestCase(TestCase, BaseFilterSetTestMixin):
                 notifications=JobNotificationChoices.NOTIFICATION_ALWAYS,
                 execution_time=timedelta(seconds=30),
                 access=JobAccessChoices.ACCESS_REQUESTER,
+                lifetime=60,
+                expires=datetime(2026, 1, 1, tzinfo=UTC),
             ),
             Job(
                 name='Job 2', job_id=uuid.uuid4(), user=users[0],
                 notifications=JobNotificationChoices.NOTIFICATION_ALWAYS,
                 execution_time=timedelta(seconds=60),
                 access=JobAccessChoices.ACCESS_OBJECT,
+                lifetime=1440,
+                expires=datetime(2026, 1, 2, tzinfo=UTC),
             ),
             Job(
                 name='Job 3', job_id=uuid.uuid4(), user=users[1],
@@ -336,6 +340,18 @@ class JobTestCase(TestCase, BaseFilterSetTestMixin):
         params = {'access': [JobAccessChoices.ACCESS_REQUESTER, JobAccessChoices.ACCESS_OBJECT]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
+    def test_lifetime(self):
+        """Filter Jobs by lifetime."""
+        params = {'lifetime': [60, 1440]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_expires(self):
+        """Filter Jobs by expiration time."""
+        params = {'expires__after': '2026-01-02T00:00:00Z'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'expires__before': '2026-01-02T00:00:00Z'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_execution_time(self):
         """Filter Jobs by execution time (exact value and gte/lte range)."""
         params = {'execution_time': timedelta(seconds=60)}

+ 72 - 3
netbox/core/tests/test_jobs.py

@@ -4,13 +4,19 @@ from unittest.mock import MagicMock, patch
 
 import requests
 from django.conf import settings
+from django.db import connection
 from django.test import TestCase, override_settings, tag
+from django.test.utils import CaptureQueriesContext
 from django.utils import timezone
 
-from core.choices import DataSourceStatusChoices, JobStatusChoices
-from core.jobs import SyncDataSourceJob, SystemHousekeepingJob
-from core.models import DataFile, DataSource, Job
+from core.choices import DataSourceStatusChoices, JobIntervalChoices, JobStatusChoices
+from core.events import JOB_COMPLETED
+from core.jobs import HourlyCleanupJob, SyncDataSourceJob, SystemHousekeepingJob
+from core.models import DataFile, DataSource, Job, ObjectType
 from core.signals import job_end
+from extras.models import Notification
+from netbox.registry import registry
+from users.models import User
 
 
 def _make_runner(cls, **job_attrs):
@@ -310,6 +316,69 @@ class DeleteExpiredJobsTestCase(HousekeepingRunnerMixin, TestCase):
         self.assertTrue(Job.objects.filter(pk=recent_job.pk).exists())
 
 
+class HourlyCleanupJobTestCase(TestCase):
+    def test_registered_as_hourly_system_job(self):
+        self.assertEqual(
+            registry['system_jobs'][HourlyCleanupJob]['interval'], JobIntervalChoices.INTERVAL_HOURLY
+        )
+
+    def test_cleanup_jobs_expire(self):
+        self.assertEqual(HourlyCleanupJob.Meta.lifetime, JobIntervalChoices.INTERVAL_DAILY)
+
+    def test_run_executes_all_cleanup_tasks(self):
+        with patch.object(HourlyCleanupJob, 'delete_expired_jobs') as delete_expired_jobs:
+            _make_runner(HourlyCleanupJob).run()
+        delete_expired_jobs.assert_called_once_with()
+
+    def test_delete_expired_jobs_deletes_only_expired_jobs(self):
+        now = timezone.now()
+        Job.objects.bulk_create([
+            Job(name='expired', job_id=uuid.uuid4(), expires=now - timedelta(minutes=1)),
+            Job(name='unexpired', job_id=uuid.uuid4(), expires=now + timedelta(minutes=1)),
+            Job(name='no expiration', job_id=uuid.uuid4()),
+        ])
+        # Jobs without an expiration are left to housekeeping, however old
+        Job.objects.filter(name='no expiration').update(created=now - timedelta(days=365))
+
+        _make_runner(HourlyCleanupJob).delete_expired_jobs()
+
+        self.assertEqual(set(Job.objects.values_list('name', flat=True)), {'unexpired', 'no expiration'})
+
+    def test_delete_expired_jobs_in_batches(self):
+        expires = timezone.now() - timedelta(minutes=1)
+        Job.objects.bulk_create([Job(name=f'expired {i}', job_id=uuid.uuid4(), expires=expires) for i in range(5)])
+
+        runner = _make_runner(HourlyCleanupJob)
+        with patch('core.jobs.JOB_DELETE_BATCH_SIZE', 2), CaptureQueriesContext(connection) as queries:
+            runner.delete_expired_jobs()
+
+        self.assertFalse(Job.objects.exists())
+        job_queries = [q['sql'] for q in queries if '"core_job"' in q['sql']]
+        self.assertEqual(sum(sql.startswith('DELETE FROM "core_job"') for sql in job_queries), 3)
+        # Deletion loads only each job's PK, not its data or log entries
+        self.assertFalse(any('"core_job"."data"' in sql for sql in job_queries))
+        runner.logger.info.assert_called_once_with('Deleted 5 expired jobs')
+
+    def test_delete_expired_jobs_deletes_notifications(self):
+        user = User.objects.create_user(username='job-owner')
+        now = timezone.now()
+        expired, unexpired = Job.objects.bulk_create([
+            Job(name='expired', job_id=uuid.uuid4(), user=user, expires=now - timedelta(minutes=1)),
+            Job(name='unexpired', job_id=uuid.uuid4(), user=user, expires=now + timedelta(minutes=1)),
+        ])
+        job_type = ObjectType.objects.get_for_model(Job)
+        Notification.objects.bulk_create([
+            Notification(
+                user=user, object_type=job_type, object_id=job.pk, object_repr=job.name, event_type=JOB_COMPLETED
+            )
+            for job in (expired, unexpired)
+        ])
+
+        _make_runner(HourlyCleanupJob).delete_expired_jobs()
+
+        self.assertEqual(list(Notification.objects.values_list('object_id', flat=True)), [unexpired.pk])
+
+
 class CheckForNewReleasesTestCase(HousekeepingRunnerMixin, TestCase):
     @override_settings(ISOLATED_DEPLOYMENT=True)
     def test_check_for_new_releases_skips_when_isolated(self):

+ 21 - 0
netbox/core/tests/test_models.py

@@ -779,6 +779,27 @@ class JobTestCase(TestCase):
         with translation.override('nl'):
             self.assertEqual(str(verbose_name), gettext('job'))
 
+    def test_lifetime_duration(self):
+        self.assertEqual(Job(lifetime=90).lifetime_duration, timedelta(minutes=90))
+        self.assertIsNone(Job().lifetime_duration)
+
+    @patch('core.models.jobs.job_end')
+    def test_terminate_sets_expiration(self, mock_job_end):
+        """A finished job with a lifetime expires that long after its completion."""
+        for status in JobStatusChoices.TERMINAL_STATE_CHOICES:
+            with self.subTest(status=status):
+                job = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER, lifetime=60)
+                job.terminate(status=status)
+                job.refresh_from_db()
+                self.assertEqual(job.expires, job.completed + timedelta(minutes=60))
+
+    @patch('core.models.jobs.job_end')
+    def test_terminate_without_lifetime_never_expires(self, mock_job_end):
+        job = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        job.terminate()
+        job.refresh_from_db()
+        self.assertIsNone(job.expires)
+
 
 class JobAccessTestCase(TestCase):
     """

+ 24 - 1
netbox/core/tests/test_views.py

@@ -1,7 +1,7 @@
 import json
 import urllib.parse
 import uuid
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
 from unittest.mock import patch
 
 from django.contrib.contenttypes.models import ContentType
@@ -203,6 +203,8 @@ class JobTestCase(
                     status='completed',
                     queue_name='default',
                     job_id=uuid.uuid4(),
+                    lifetime=1440,
+                    expires=datetime(2026, 1, 1, tzinfo=UTC),
                 ),
             ]
         )
@@ -624,6 +626,27 @@ class BackgroundTaskTestCase(RQQueueTestMixin, TestCase):
                 job.refresh_from_db()
                 self.assertEqual(job.status, JobStatusChoices.STATUS_COMPLETED)
 
+    def test_background_task_enqueue_clears_expiration(self):
+        """A finished Job which is run again doesn't expire while waiting."""
+        with self.captureOnCommitCallbacks(execute=True):
+            job = TestJobRunner.enqueue(lifetime=60)
+        with patch.object(TestJobRunner, 'run', side_effect=Exception('Simulated job error')):
+            self.run_rq_jobs('default')
+        job.refresh_from_db()
+        self.assertIsNotNone(job.expires)
+
+        with self.captureOnCommitCallbacks(execute=True):
+            self.client.get(reverse('core:background_task_enqueue', args=[str(job.job_id)]))
+        job.refresh_from_db()
+        self.assertEqual(job.status, JobStatusChoices.STATUS_PENDING)
+        self.assertIsNone(job.expires)
+
+        # The run sets a new expiration
+        with patch.object(TestJobRunner, 'run'):
+            self.run_rq_jobs('default')
+        job.refresh_from_db()
+        self.assertEqual(job.expires, job.completed + timedelta(minutes=60))
+
     def test_background_task_requeue_reruns_job(self):
         """Requeue runs a Job again after its worker died."""
         queue = get_queue('default')

+ 2 - 0
netbox/core/ui/panels.py

@@ -106,6 +106,8 @@ class JobSchedulingPanel(panels.ObjectAttributesPanel):
     started = attrs.DateTimeAttr('started')
     completed = attrs.DateTimeAttr('completed')
     execution_time = attrs.DurationAttr('execution_time')
+    lifetime = attrs.DurationAttr('lifetime_duration', label=_('Lifetime'))
+    expires = attrs.DateTimeAttr('expires')
     queue = attrs.TextAttr('queue_name', label=_('Queue'))
 
 

+ 1 - 0
netbox/core/utils.py

@@ -127,6 +127,7 @@ def _retry_rq_job(job, queue, ended, push):
                 started=None,
                 completed=None,
                 execution_time=None,
+                expires=None,
                 error='',
                 data=None,
                 log_entries=[],

+ 6 - 2
netbox/netbox/jobs.py

@@ -21,7 +21,7 @@ from django_pg_utils import advisory_lock
 from rest_framework.exceptions import APIException
 from rq.timeouts import JobTimeoutException
 
-from core.choices import JobAccessChoices, JobStatusChoices
+from core.choices import JobAccessChoices, JobIntervalChoices, JobStatusChoices
 from core.exceptions import JobFailed
 from core.models import Job, ObjectType
 from netbox.constants import ADVISORY_LOCK_KEYS
@@ -199,6 +199,7 @@ class JobRunner(ABC):
                 interval=job.interval,
                 notifications=job.notifications,
                 access=job.access,
+                lifetime=job.lifetime,
                 parent=Job.objects.filter(pk=job.parent_id).first() if job.parent_id else None,
                 **kwargs,
             )
@@ -242,7 +243,9 @@ class JobRunner(ABC):
         """
         name = kwargs.pop('name', None) or cls.name
         access = kwargs.pop('access', None) or getattr(cls.Meta, 'access', JobAccessChoices.ACCESS_SHARED)
-        return Job.enqueue(cls.handle, name=name, access=access, *args, **kwargs)
+        # An explicit lifetime of None disables the runner's default
+        lifetime = kwargs.pop('lifetime', getattr(cls.Meta, 'lifetime', None))
+        return Job.enqueue(cls.handle, name=name, access=access, lifetime=lifetime, *args, **kwargs)
 
     @classmethod
     @advisory_lock(ADVISORY_LOCK_KEYS['job-schedules'])
@@ -314,6 +317,7 @@ class AsyncAPIJob(JobRunner):
     class Meta:
         name = 'Async API Request'
         access = JobAccessChoices.ACCESS_REQUESTER
+        lifetime = JobIntervalChoices.INTERVAL_DAILY
 
     @staticmethod
     def _build_request(request_copy, payload, scheme):

+ 48 - 1
netbox/netbox/tests/test_jobs.py

@@ -12,7 +12,7 @@ from django.utils import timezone
 from django_pg_utils import advisory_lock
 from django_rq import get_queue
 
-from core.choices import JobAccessChoices, JobStatusChoices
+from core.choices import JobAccessChoices, JobIntervalChoices, JobStatusChoices
 from core.events import JOB_COMPLETED, JOB_FAILED
 from core.exceptions import JobFailed
 from core.jobs import SyncDataSourceJob, SystemHousekeepingJob
@@ -311,6 +311,22 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
         successor = TestJobRunner.get_jobs(instance).exclude(pk=job.pk).get()
         self.assertEqual(successor.access, JobAccessChoices.ACCESS_REQUESTER)
 
+    def test_handle_sets_expiration(self):
+        """A job with a lifetime expires that long after it finishes."""
+        job = TestJobRunner.enqueue(immediate=True, lifetime=60)
+        self.assertEqual(job.status, JobStatusChoices.STATUS_COMPLETED)
+        self.assertEqual(job.expires, job.completed + timedelta(minutes=60))
+
+    def test_handle_reschedule_keeps_lifetime(self):
+        """A periodic job's successor has the same lifetime, and doesn't expire until it finishes."""
+        instance = DataSource.objects.create(name='Data Source 1', type='local')
+        job = TestJobRunner.enqueue(instance, interval=60, schedule_at=self.get_schedule_at(), lifetime=30)
+        TestJobRunner.handle(job)
+
+        successor = TestJobRunner.get_jobs(instance).exclude(pk=job.pk).get()
+        self.assertEqual(successor.lifetime, 30)
+        self.assertIsNone(successor.expires)
+
     def test_handle_object_job_without_object_is_not_rescheduled(self):
         """A periodic object job whose assigned object is gone completes without being rescheduled."""
         instance = DataSource.objects.create(name='Data Source 1', type='local')
@@ -463,6 +479,37 @@ class EnqueueTestCase(BaseJobRunnerTestCase):
             TestJobRunner.enqueue(schedule_at=self.get_schedule_at(), access=JobAccessChoices.ACCESS_OBJECT)
         self.assertFalse(Job.objects.exists())
 
+    def test_enqueue_lifetime(self):
+        class ShortLivedJobRunner(TestJobRunner):
+            class Meta:
+                lifetime = 60
+
+        # The runner's default lifetime
+        job = TestJobRunner.enqueue(schedule_at=self.get_schedule_at())
+        self.assertIsNone(job.lifetime)
+        job = ShortLivedJobRunner.enqueue(schedule_at=self.get_schedule_at())
+        self.assertEqual(job.lifetime, 60)
+
+        # Overridden for an individual job
+        job = ShortLivedJobRunner.enqueue(schedule_at=self.get_schedule_at(), lifetime=5)
+        self.assertEqual(job.lifetime, 5)
+
+        # Disabled for an individual job
+        job = ShortLivedJobRunner.enqueue(schedule_at=self.get_schedule_at(), lifetime=None)
+        self.assertIsNone(job.lifetime)
+
+        # A waiting job doesn't expire
+        self.assertIsNone(job.expires)
+
+    def test_enqueue_invalid_lifetime(self):
+        with self.assertRaises(ValidationError):
+            TestJobRunner.enqueue(schedule_at=self.get_schedule_at(), lifetime=0)
+        self.assertFalse(Job.objects.exists())
+
+    def test_async_api_job_lifetime(self):
+        job = AsyncAPIJob.enqueue(schedule_at=self.get_schedule_at())
+        self.assertEqual(job.lifetime, JobIntervalChoices.INTERVAL_DAILY)
+
     def test_core_job_runner_access(self):
         expected = {
             AsyncAPIJob: JobAccessChoices.ACCESS_REQUESTER,