Skip to content

[bug] Fix broken build complete transition - #12696

Merged
SchrodingersGat merged 6 commits into
inventree:masterfrom
SchrodingersGat:transition-fix
Aug 24, 2026
Merged

SchrodingersGat merged 6 commits into
inventree:masterfrom
SchrodingersGat:transition-fix

Conversation

@SchrodingersGat

@SchrodingersGat SchrodingersGat commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Bug Description

Recent update to django-fsm2 in #12507 has caused the build_complete transition to fail when running with the django-q2 background worker.

Overview

#12507 transitioned to django-fsm2 which provides decorators for state machine transition functions. For the most part this is a good refactor, however it has introduced a serious bug which causes build order line items to not be properly consumed when a build is completed.

The complete_build method looks like this:

    @inventree_transition(
        field=status,
        source=[BuildStatus.PENDING, BuildStatus.PRODUCTION, BuildStatus.ON_HOLD],
        target=BuildStatus.COMPLETE,
    )
    def complete_build(self, user: User, trim_allocated_stock: bool = False):
        """Transition this Build to COMPLETE status.

        Arguments:
            user: The user who is completing the build
            trim_allocated_stock: If True, trim any allocated stock
        """
        import build.tasks

        if (
            get_global_setting('BUILDORDER_REQUIRE_CLOSED_CHILDS')
            and self.has_open_child_builds
        ):
            raise ValidationError(
                _('Cannot complete build order with open child builds')
            )

        if self.incomplete_count > 0:
            raise ValidationError(
                _('Cannot complete build order with incomplete outputs')
            )

        # Offload background task to complete build allocations
        InvenTree.tasks.offload_task(
            build.tasks.complete_build,
            self.pk,
            user.pk if user else None,
            trim_allocated_stock=trim_allocated_stock,
            group='build',
        )

This does two things, in sequence:

  1. Sets the status of the build to `COMPLETE
  2. offloads the task to the background worker

Later on, the background task then runs:

@tracer.start_as_current_span('complete_build')
def complete_build(build_id: int, user_id: int, trim_allocated_stock: bool = False):
    """Tasks to run after a BuildOrder is completed.

    Arguments:
        build_id: The ID of the BuildOrder which has been completed
        user_id: The ID of the user who completed the BuildOrder
        trim_allocated_stock: If True, trim any allocated stock which was not consumed
    """
    from build.models import Build
    from build.status_codes import BuildStatus

    with transaction.atomic():
        # Lock the build row: concurrent completion tasks (duplicate task
        # delivery, or repeated completion requests while the build is still
        # IN PRODUCTION) are serialized, and the status is re-checked below
        build = Build.objects.select_for_update().get(pk=build_id)

        if build.status == BuildStatus.COMPLETE.value:
            logger.warning(
                'Build order <%s> is already complete - skipping completion task',
                build.pk,
            )
            return

    ...

However, this now exits early as the build status has already been marked as COMPLETE. This is revealed in worker logs, that the complete_build background task exits early.

Final State

The build is marked as complete, however the underlying build line allocations are not completed, and not consumed against the build order. Additionally, the allocated stock item quantity values are not reduced.

Bug Fix

If the completion task is offloaded to the background worker, the status is not changed - this is deferred to the background task instead

Fixing Corrupted Data

Luckily, this bug has not been pushed to stable and was only introduced a few days ago. However, there is a chance that users running on latest have completed build orders and left orphaned build allocations.

To address this, run invoke dev.shell from the InvenTree command line context, and run the following:

from build.models import BuildItem
from build.status_codes import BuildStatus
items = BuildItem.objects.filter(build_line__build__status=BuildStatus.COMPLETE)
for item in items:
    item.complete_allocation()

@netlify

netlify Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for inventree-web-pui-preview ready!

Name Link
🔨 Latest commit b5f0b00
🔍 Latest deploy log https://app.netlify.com/projects/inventree-web-pui-preview/deploys/6a8c3d7c6d359a0008467648
😎 Deploy Preview https://deploy-preview-12696--inventree-web-pui-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 94 (🔴 down 2 from production)
Accessibility: 82 (🟢 up 1 from production)
Best Practices: 92 (🔴 down 8 from production)
SEO: 78 (no change from production)
PWA: -
View the detailed breakdown and full score reports
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@SchrodingersGat SchrodingersGat added bug Identifies a bug which needs to be addressed build Build orders labels Aug 24, 2026
@SchrodingersGat SchrodingersGat added this to the 1.6.0 milestone Aug 24, 2026
@codecov

codecov Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.78049% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 86.81%. Comparing base (e12bdcf) to head (b5f0b00).

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #12696      +/-   ##
==========================================
- Coverage   86.82%   86.81%   -0.01%     
==========================================
  Files        1456     1455       -1     
  Lines       97652    97641      -11     
  Branches    11330    11321       -9     
==========================================
- Hits        84786    84767      -19     
- Misses      12800    12808       +8     
  Partials       66       66              
Flag Coverage Δ
backend 90.88% <98.78%> (+<0.01%) ⬆️

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

Components Coverage Δ
Backend Apps 92.26% <98.78%> (+<0.01%) ⬆️
Backend General 93.78% <94.11%> (-0.01%) ⬇️
Frontend 79.65% <ø> (-0.06%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@SchrodingersGat
SchrodingersGat merged commit 33586f6 into inventree:master Aug 24, 2026
41 of 42 checks passed
@SchrodingersGat
SchrodingersGat deleted the transition-fix branch August 24, 2026 13:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Identifies a bug which needs to be addressed build Build orders

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant