Skip to content

Background Task Features - #12913

Merged
SchrodingersGat merged 11 commits into
inventree:masterfrom
SchrodingersGat:single-shot-task
Sep 26, 2026
Merged

SchrodingersGat merged 11 commits into
inventree:masterfrom
SchrodingersGat:single-shot-task

Conversation

@SchrodingersGat

@SchrodingersGat SchrodingersGat commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

This PR introduces two new features for background tasks:

Optional Single-Shot Mode

offload_task can now be called with retry=False to disable retry on failure. This can be used for tasks which should only run once.

Utilizes the ack_failure task attribute from django-q

Per-Task Timeout

Introduces per-task timeout configuration. Utilizes the timeout task attribute from django-q


Once this is merged, we could apply this to label and report generation - potentially closing #11650

@SchrodingersGat SchrodingersGat added the enhancement This is an suggested enhancement or new feature label Sep 22, 2026
@netlify

netlify Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for inventree-web-pui-preview canceled.

Name Link
🔨 Latest commit fa4d350
🔍 Latest deploy log https://app.netlify.com/projects/inventree-web-pui-preview/deploys/6ab5ba681b58030008f2d0e9

@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.20635% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.34%. Comparing base (94f1f1e) to head (fa4d350).

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #12913      +/-   ##
==========================================
+ Coverage   87.30%   87.34%   +0.03%     
==========================================
  Files        1506     1506              
  Lines      103092   103334     +242     
  Branches    11582    11582              
==========================================
+ Hits        90008    90252     +244     
+ Misses      13019    13017       -2     
  Partials       65       65              
Flag Coverage Δ
backend 92.07% <99.20%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
Backend Apps 92.69% <ø> (ø)
Backend General 94.95% <ø> (ø)
Frontend 79.60% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ledvinap

ledvinap commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

@SchrodingersGat :
Based on gpt-6 review, edited:

  1. [P2] Per-task timeout can exceed the redelivery interval.

IMO refusing timeout longer than retry interval is OK for InvenTree; long print job is now primary candidate for extended timeout, but few minutes shall be enough.

It is also possible to subclass ORM broker and override timeout() orm.py but that is probably overkill for problem that nobody complained about.

  1. [P2] Deduplication silently ignores the requested options. tasks.py

This is mainly policy choice + check_duplicates doc shall mention it.

  1. [P2] A terminal retry=False failure misses the staff notification.

Moving after_failed_task to post_execute signal and fetching Task using task dict seems reasonable fix:

@receiver(post_execute, sender='django_q', dispatch_uid='failure_post_execute_notification')
def after_failed_task(sender, task, **kwargs):
    """Notify staff when a saved task failure will not be retried."""
    from InvenTree.exceptions import log_error

    if task['success']:          # this execution attempt succeeded
        return

    instance = Task.objects.filter(pk=task['id'], success=False).first()
    if instance is None:        # Task succeeded (in other execution)
        return

    n = instance.attempt_count
    limit_reached = Conf.MAX_ATTEMPTS > 0 and n >= Conf.MAX_ATTEMPTS

    if not (task.get('ack_failure', False) or limit_reached):
        return

    # Create a new Error object associated with this failed task
    # This will, in turn, trigger a notification to staff users via the Error post_save signal
    message = f"Task '{instance.func} ({instance.pk})' failed after {n} attempts"
    logger.error(message)

    log_error(
        'task_failure',
        scope='worker',
        error_name='Task Failure',
        error_info=message,
        error_data=str(instance.result) if instance.result else '',
    )

Note:
django-q2 has no concept of a per-task retry limit: the ORM broker (which
InvenTree always uses) simply leaves a failed task's queue entry in place, so it
gets redelivered indefinitely (governed by the cluster-wide 'retry' timeout)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

(indefinitely -> global cluster limit still applies)

Comment on lines +394 to +403
task_kwargs = dict(kwargs)
if not retry:
# Bandaid for django-q2 having no per-task retry limit: 'ack_failure'
# is its one native per-task option that acknowledges (and so drops)
# a task as soon as it fails, rather than leaving it to be redelivered
task_kwargs['ack_failure'] = True
if timeout is not None:
task_kwargs['timeout'] = timeout

task = AsyncTask(taskname, *args, group=group, **task_kwargs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

(q_options will reduce task argument collision a bit, but offload_task signature / kwargs handling will consume args sooner)

Suggested change
task_kwargs = dict(kwargs)
if not retry:
# Bandaid for django-q2 having no per-task retry limit: 'ack_failure'
# is its one native per-task option that acknowledges (and so drops)
# a task as soon as it fails, rather than leaving it to be redelivered
task_kwargs['ack_failure'] = True
if timeout is not None:
task_kwargs['timeout'] = timeout
task = AsyncTask(taskname, *args, group=group, **task_kwargs)
task_kwargs = dict(kwargs)
q_options = dict(task_kwargs.pop('q_options', {}))
q_options['group'] = group
if not retry:
# Bandaid for django-q2 having no per-task retry limit: 'ack_failure'
# is its one native per-task option that acknowledges (and so drops)
# a task as soon as it fails, rather than leaving it to be redelivered
q_options['ack_failure'] = True
if timeout is not None:
q_options['timeout'] = timeout
task = AsyncTask(taskname, *args, q_options=q_options, **task_kwargs)

task['ack_failure'] = True

if timeout is not None:
task['timeout'] = timeout

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is probably good spot to fail when timeout is longer than configured retry interval.

fails (see note below)
timeout: Optional per-task override (in seconds) of the worker's task timeout
timeout: Optional per-task override (in seconds) of the worker's task timeout.
Clamped down (with a warning) if it would leave less than 120s of headroom

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

(HEADROOM = 30)

@ledvinap

Copy link
Copy Markdown
Contributor

@SchrodingersGat : I updated #12913 (comment); most cases are handed; look at instance = Task.objects.filter(pk=task['id'], success=False).first(), it may be slightly more consistent

@SchrodingersGat
SchrodingersGat merged commit 862c934 into inventree:master Sep 26, 2026
48 checks passed
@SchrodingersGat
SchrodingersGat deleted the single-shot-task branch September 26, 2026 00:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement This is an suggested enhancement or new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants