Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 17 additions & 3 deletions pyworker/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Comment thread
maboelnour marked this conversation as resolved.
Resolved
WHERE id IN (SELECT delayed_jobs.id FROM delayed_jobs
WHERE ((run_at <= '%s'
AND (locked_at IS NULL OR locked_at < '%s')
Expand All @@ -142,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:
Expand All @@ -162,6 +170,12 @@ def handle_job(self, job):
error = failed = False
caught_exc_info = None
try:
if job.attempts >= self.max_attempts:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this replace the comparison done on error?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it complements it. The comparison in set_error_unlock still handles runs that fail with an exception: on the last attempt the job is failed right away and the failure hook runs. The new check only matters for runs that never reached set_error_unlock because the process was killed, so their attempts were counted at pickup but never finished. Dropping the error-path comparison would fail those jobs one pickup later than now (rescheduled with backoff, picked up, then failed), so both are kept.

# 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)
Expand Down
68 changes: 67 additions & 1 deletion tests/test_worker.py
Original file line number Diff line number Diff line change
@@ -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')
Expand Down Expand Up @@ -105,8 +105,74 @@ 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)

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):
# 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(
Expand Down
Loading