From 50f128c04c4ed153619a15c32a00c58e64d610aa Mon Sep 17 00:00:00 2001 From: ahmed Date: Fri, 30 Oct 2026 15:03:52 -0400 Subject: [PATCH 1/2] Count attempts when a job is picked up so killed runs can't loop forever A run that never reaches set_error_unlock (the process is SIGKILLed, e.g. by the OOM killer) left attempts unchanged and failed_at unset. Because the worker name (hostname + pid) is the same after a container restart and get_job also matches locked_by = self.name, the restarted worker reclaimed the same job immediately and was killed again, forever. - get_job increments attempts in the existing lock UPDATE (no extra query) and returns attempts - 1, so job.attempts still means attempts before this run and set_error_unlock, backoff and reporting are unchanged. - handle_job fails a job that already used max_attempts instead of running it, through the normal error path (error/failure hooks, failed_at, reporting). Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +++ pyworker/worker.py | 14 +++++++++-- tests/test_worker.py | 56 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c8966e9..c7ac1d1 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,9 @@ configuration options: w.sleep_delay = 3 # maximum attempts before marking the job as permanently failing (default 3) +# an attempt is counted when a job is picked up, so runs that never finish +# (e.g. the worker is OOM-killed) also count; a job that already used all +# its attempts is marked as failed instead of being run again w.max_attempts = 5 # sets a cap on how long a worker should wait between retry attempts. diff --git a/pyworker/worker.py b/pyworker/worker.py index 5a3e05c..da5c741 100644 --- a/pyworker/worker.py +++ b/pyworker/worker.py @@ -10,6 +10,7 @@ class TimeoutException(Exception): pass class TerminatedException(Exception): pass +class AttemptsExhaustedException(Exception): pass class Worker(object): def __init__(self, dbstring, logger=None, @@ -126,12 +127,15 @@ def get_job_row(): now, expired = str(now), str(expired) queues = self.queue_names.split(',') queues = ', '.join(["'%s'" % q for q in queues]) - fields = ['id', 'attempts', 'run_at', 'queue', 'handler'] + # attempts is counted when the job is locked (see the UPDATE below), so a run + # that never reaches set_error_unlock (e.g. the process is OOM-killed) still + # uses an attempt; return the attempts made before this run + fields = ['id', 'attempts - 1', 'run_at', 'queue', 'handler'] if self.extra_delayed_job_fields: fields += self.extra_delayed_job_fields fields = ', '.join(fields) query = ''' - UPDATE delayed_jobs SET locked_at = '%s', locked_by = '%s' + UPDATE delayed_jobs SET locked_at = '%s', locked_by = '%s', attempts = attempts + 1 WHERE id IN (SELECT delayed_jobs.id FROM delayed_jobs WHERE ((run_at <= '%s' AND (locked_at IS NULL OR locked_at < '%s') @@ -162,6 +166,12 @@ def handle_job(self, job): error = failed = False caught_exc_info = None try: + if job.attempts >= self.max_attempts: + # every previous run was counted but never finished, e.g. the + # worker was killed, so fail it instead of running it again + raise AttemptsExhaustedException(('Job %d was not run: it already used ' \ + + 'all %d attempts without finishing, the worker was likely killed ' \ + + '(e.g. out of memory)') % (job.job_id, self.max_attempts)) if job.abstract: raise ValueError(('Unsupported Job: %s, please import it ' \ + 'before you can handle it') % job.class_name) diff --git a/tests/test_worker.py b/tests/test_worker.py index 3b99a60..ddd2ac9 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -1,7 +1,7 @@ import datetime from unittest import TestCase from unittest.mock import patch, MagicMock -from pyworker.worker import Worker, TerminatedException +from pyworker.worker import Worker, TerminatedException, AttemptsExhaustedException class TestWorker(TestCase): @patch('pyworker.worker.DBConnector') @@ -105,8 +105,62 @@ def test_worker_run_when_job_found_handles_job(self, mock_get_job, mock_handle_j mock_get_job.assert_called_once_with() mock_handle_job.assert_called_once_with(mock_get_job.return_value) + #********** .get_job tests **********# + + def test_worker_get_job_counts_the_attempt_when_locking_the_job(self): + self.worker._cursor = MagicMock() + self.worker._cursor.fetchone.return_value = None + + self.worker.get_job() + + query = self.worker._cursor.execute.call_args[0][0] + self.assertIn('attempts = attempts + 1', query) + # the job still sees the attempts made before this run + self.assertIn('RETURNING\n id, attempts - 1, run_at', query) + #********** .handle_job tests **********# + def test_worker_handle_job_when_attempts_exhausted_does_not_run_job(self): + # all previous runs were counted but never finished, e.g. the worker was OOM-killed + job = self.mock_job + job.attempts = self.worker.max_attempts + + self.worker.handle_job(job) + + job.before.assert_not_called() + job.run.assert_not_called() + job.remove.assert_not_called() + job.set_error_unlock.assert_called_once() + error = job.set_error_unlock.call_args[0][0] + assert 'AttemptsExhaustedException' in error + assert 'already used all 3 attempts' in error + + @patch('pyworker.worker.get_current_time') + def test_worker_handle_job_when_attempts_exhausted_reports_failure(self, get_current_time): + get_current_time.return_value = self.mocked_now + job = self.mock_job + job.attempts = self.worker.max_attempts + job.set_error_unlock.return_value = True + reporter = MagicMock() + self.worker.reporter = reporter + + self.worker.handle_job(job) + + reporter.record_exception.assert_called_once() + reporter.report.assert_any_call(job_failure=True) + reporter.report_raw.assert_any_call(error=True) + + def test_worker_handle_job_when_attempts_left_runs_job(self): + job = self.mock_job + job.attempts = self.worker.max_attempts - 1 + + self.worker.handle_job(job) + + job.run.assert_called_once() + job.remove.assert_called_once() + job.set_error_unlock.assert_not_called() + + def assert_instrument_context_reports_custom_attributes(self, job, reporter): reporter.recorder.assert_called_once() reporter.report.assert_any_call( From 8482c39409b431bbb17a5f66b1c46bbc0bcca3c9 Mon Sep 17 00:00:00 2001 From: ahmed Date: Wed, 11 Nov 2026 13:44:27 -0500 Subject: [PATCH 2/2] Commit the job lock and attempt before running the job The lock UPDATE in get_job ran in an open transaction that was only committed by a later query on the same connection (set_error_unlock, remove, or a job's own hook). A process killed during run() rolled back attempts + 1 together with the lock, so a job killed every time still had attempts = 0 and was picked up again forever. Commit right after the UPDATE returns. Checked against Postgres 16: a job SIGKILLed on each of 4 pickups ends with attempts = 0 before this change, and with attempts = 4 and failed_at set after it (max_attempts = 3). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PqPDJ4ACaD8D7s3VMSFmfY --- pyworker/worker.py | 6 +++++- tests/test_worker.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/pyworker/worker.py b/pyworker/worker.py index da5c741..c0264b4 100644 --- a/pyworker/worker.py +++ b/pyworker/worker.py @@ -146,7 +146,11 @@ def get_job_row(): ''' % (now, self.name, now, expired, self.name, queues, fields) self.logger.debug('query: %s' % query) self._cursor.execute(query) - return self._cursor.fetchone() + row = self._cursor.fetchone() + # commit the lock and the attempt now: if the process is killed while the + # job runs, an uncommitted UPDATE would be rolled back with it + self.database.commit() + return row job_row = get_job_row() if job_row: diff --git a/tests/test_worker.py b/tests/test_worker.py index ddd2ac9..78546b0 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -118,6 +118,18 @@ def test_worker_get_job_counts_the_attempt_when_locking_the_job(self): # the job still sees the attempts made before this run self.assertIn('RETURNING\n id, attempts - 1, run_at', query) + def test_worker_get_job_commits_the_lock_and_attempt_before_running(self): + # an uncommitted UPDATE would be rolled back if the process is killed during run() + self.worker._cursor = MagicMock() + self.worker._cursor.fetchone.return_value = None + calls = MagicMock() + calls.attach_mock(self.worker._cursor.fetchone, 'fetchone') + calls.attach_mock(self.worker.database.commit, 'commit') + + self.worker.get_job() + + self.assertEqual([c[0] for c in calls.mock_calls], ['fetchone', 'commit']) + #********** .handle_job tests **********# def test_worker_handle_job_when_attempts_exhausted_does_not_run_job(self):