Skip to content

Harden label printing against concurrent delivery and interrupted jobs #12873

Not planned

Description

@ledvinap

Please verify that this bug has NOT been raised before.

  • I checked and didn't find a similar issue

Describe the bug*

Related to the #12872 that preserves label-print failures in DataOutput and skips redelivery of failed jobs. The problem is a bit theoretical and ignoring it as 'too unlikely' is reasonable; it is likely that other issues have higher priority.

The #12872 fixes failure reporting and prevents printing again when a later delivery observes a recorded failure. However, label printing still has concurrency and interruption cases that can produce duplicate labels or misleading status.

Failure scenarios

Scenario Consequence Did it exist with delete-on-error?
Two workers read the same unfinished output before either finishes Both pass the guards and can print the same labels. Yes. Deleting the output did not stop an execution already holding it.
A worker saves a stale output after another worker records failure Progress or completion saves can clear the recorded error and replace it with apparent success. The stale-write race existed. Previously, a stale save could recreate the deleted output; retaining outputs makes overwriting their error another manifestation.
Printing partially succeeds, then the worker times out or terminates The output can remain unfinished, allowing redelivery to print the batch again. Yes. Django-Q’s TimeoutException inherits from SystemExit, bypassing except Exception. Abrupt termination also bypasses deletion.
A plugin marks the output complete before after_printing() fails The frontend can observe success and stop polling before the failure becomes visible. Yes. Previously the later failure deleted the output instead of recording an error.
An output is deleted while a worker still holds it A subsequent model save can recreate the deleted row. Yes, through progress/completion saves, but not through the delete-on-error handler. The related PR extends this risk to failure recording via mark_failure().

How overlapping execution can occur

InvenTree supports multiple worker processes: the default is four, restricted to one per cluster for SQLite or without a global cache. Queue leasing normally prevents duplicate delivery, but its timer starts at dequeue, before waiting in the local worker queue.

For example:

Time Event
0 s The job is leased and placed in a local worker queue.
280 s Worker A starts printing.
300 s The queue lease expires.
305 s Worker B receives the same job and starts executing it while A is still printing.

Worker A’s 90-second execution timeout has not expired. If neither execution has recorded completion or failure, both can pass the unfinished-output guard.

This is a reachable risk, not a reproduced queue-level incident. It was tested by forced overlapping execution. One worker in one cluster prevents this overlap, but does not prevent sequential reprinting after an unrecorded timeout or crash.

Possible fixes

  • Claim jobs atomically before printing. Persist execution state and permit only one delivery to transition an unstarted job into execution.
  • Treat interrupted printing as uncertain. Record explicit worker timeouts and re-raise them. Preserve the claim across termination or failure to save the result, so recovery does not automatically repeat potentially completed physical printing.
  • Restrict status updates. Use conditional, field-specific updates so stale progress writes cannot clear errors, overwrite terminal results, or recreate deleted outputs.
  • Publish completion after the full lifecycle succeeds. Include after_printing(). For plugins that delegate work, distinguish successful dispatch from confirmed printing.
  • Preserve the original exception. Failure to update a deleted output should not replace the printing error.

Additional state checks or database transactions alone cannot guarantee exactly-once physical printing. That requires printer-side idempotency or reconciliation of uncertain outcomes.

Validation

Four deterministic probes using actual Django task/model code, isolated SQLite, and mocked printing reproduced stale-error loss, timeout redelivery, premature completion, and deleted-row recreation. These were not live multi-worker or hardware tests.

Steps to Reproduce

Overloaded server:

Time Event
0 s The job is leased and placed in a local worker queue.
280 s Worker A finished previous work and starts printing.
300 s The queue lease expires.
305 s Worker B receives the same job and starts executing it while A is still printing.

Timeout case:

  1. Submit a label job that prints some labels, then stalls or continues beyond the worker’s execution timeout—90 seconds by default.
  2. Django-Q raises TimeoutException, which inherits from SystemExit and bypasses the print handler’s except Exception.
  3. The output remains unfinished, with no recorded failure; delete-on-error never runs.
  4. When the queue retries the job, it passes the unfinished-output guard and starts printing again, potentially duplicating labels already printed.

Expected behaviour

Print job is started only once; partial print is not restarted automatically

Deployment Method

None

Version Information

Both master and #12872 are affected

Try to reproduce on the demo site

I did not try to reproduce

Is the bug reproducible on the demo site?

Not reproducible

Relevant log output

I have reviewed this report for correctness and filled out all sections.

  • I have checked this report. I acknowledge that filing bugs via AI agents without review might lead to being blocked.

Activity

  1. added
    bug
    on Sep 17, 2026
  2. added theissue type on Sep 17, 2026
  3. added
    question
    triage:not-checked
    on Sep 17, 2026
  4. matmair commented on Sep 17, 2026

    @matmair
    Member

    I find this highly theoretical. Is this an actual error or a theoretical AI finding?

  5. ledvinap commented on Sep 17, 2026

    @ledvinap
    ContributorAuthor

    I find this highly theoretical. Is this an actual error or a theoretical AI finding?

    More the second, but described 90s stall during print is possible (driver error, too long job, ...). And it can have quite expensive consequences - printing again and again every 5 minutes.

    It is possible to trigger it, the scenario isn't too exotic:

    Confirmed with the upstream delete-on-error code: timeout causes reprinting.

    The simulation used Django-Q’s real timeout handler, ORM broker, worker loop, and result monitor:

    1. Requested two labels; the mocked printer printed label 1, then stalled.
    2. A real one-second timeout interrupted it.
    3. The output remained present: complete=False, errors=None, progress=1.
    4. After advancing the broker lease, the same job was redelivered.
    5. It printed labels 1 and 2 and completed successfully.

    Result: two requested labels produced three simulated prints.

    Only the printer was mocked and lease expiry accelerated; no hardware was used.

  6. matmair commented on Sep 17, 2026

    @matmair
    Member

    Have you personally been able to reproduce this with an actual, correctly production-configured InvenTree instance as per docs and a published production printer driver? Not in a simulated environment. You can mock any behavior you want, especially when constructing from a failure scenario

  7. ledvinap commented on Sep 17, 2026

    @ledvinap
    ContributorAuthor

    Have you personally been able to reproduce this with an actual, correctly production-configured InvenTree instance as per docs and a published production printer driver? Not in a simulated environment. You can mock any behavior you want, especially when constructing from a failure scenario

    No, and that is not how I verify programs, with or without AI.

    Print job that takes over 90s will trigger it in default config (as demonstrated in #12873 (comment)).

  8. matmair commented on Sep 17, 2026

    @matmair
    Member

    I believe the scenario of 90s for a print to be a constructed one and per Threat Model $4 we trust all plugins to be done correctly. Imo this is a waste of time brought up by either an AI explicitly searching for issues or by a wrongly implemented plugin being tested on a instance without debug enabled, then leading some AI loop trying to get itself out of the corener. Which would also explain #12874 and #12872 instead of just turning on label/report debug.

    Which still leaves the question why your are flooding the repo with all of these individually (7 small PRs in the last 10hrs, at least 3 of them fixing non-prod issues).

  9. ledvinap commented on Sep 18, 2026

    @ledvinap
    ContributorAuthor

    I believe the scenario of 90s for a print to be a constructed one and per Threat Model $4 we trust all plugins to be done correctly.

    AI: PT-P750W + 100 × 30 mm labels is a valid supported configuration whose theoretical minimum printer time is 100 seconds. No printer fault, plugin bug, artificial sleep, or overload is required. The real InvenTree task is longer still because it also renders and rasterizes each label and performs cutting / I/O.

    Imo this is a waste of time brought up by either an AI explicitly searching for issues or by a wrongly implemented plugin being tested on a instance without debug enabled, then leading some AI loop trying to get itself out of the corener.

    It started as 'existing, but low priority' issue. 90s job-timeout made it a real-world problem.

    It was pointed out in unrelated AI review, but it is a real issue.

    It takes much more complex problem to get current AI tools cornered.

    Which would also explain #12874 and #12872 instead of just turning on label/report debug.
    Which still leaves the question why your are flooding the repo with all of these individually (7 small PRs in the last 10hrs, at least 3 of them fixing non-prod issues).

    It is result of using InvenTree. Simple changes first, complex one later.

    Can you suggest what PRs can be merged, please?

    #12874, #12872 isn't too visible in current IT (missing QRcode data is one possible exmple). With additional template validation added, it becomes more annoying - the problem can be in Stock item (missing serial, missing version, firmvare version installed) and not in template. User need feedback in that case.

    work in my InvenTree, AI:

    Proposed improvement Size Description
    Explicit link to generated output Small Add an “Open output” link to completion notifications so generated files remain accessible when automatic opening is blocked or missed.
    Preserve completed printer results Small Avoid marking an already-completed machine print job complete again, which can overwrite its output file or progress.
    Correct label-sheet geometry Small–medium Size and position label grids consistently with label dimensions, page margins, and pagination.
    Expandable stock-test notes Small–medium Show a compact, wrapped preview of test-result notes with inline expansion for longer content.
    Template-controlled label rejection Small–medium Allow label templates to reject invalid input with an explicit validation message, including consistent handling by the sheet printer.
    Independent refresh and reset of dependent fields Medium Allow dependent form fields to refresh their available options without necessarily clearing entered values, and apply updated defaults when a reset is required.
    Template-aware printer options Medium Make the selected label template available to printer discovery and driver-option generation, refreshing the printing dialog when the template changes.
    Aligned stock-test history columns Medium Keep expanded test-history rows aligned with the parent table’s column order, visibility, and widths.
    Successful output with warnings Medium Distinguish non-fatal warnings from failed jobs and display warnings alongside successful output without preventing downloads.
    Opt-in label preflight Medium–large Validate all selected labels before queuing a print job, then revalidate in the worker before invoking printer hooks, reducing partial batches caused by validation failures.
    Build-component label selection and result counts Large Resolve label targets from components allocated to build outputs, handle ambiguous or missing matches, and report matched and skipped counts.
    BeepQuay scanner integration Large Support a local scanner service with active-dialog and background scanning, scan-driven navigation, connection status, and session-scoped pause controls.

    work in related projects, AI:

    inventree-brother-plugin — printer integration and accurate label rendering

    The main improvement connects InvenTree’s physical label dimensions to the printer’s actual raster geometry. This matters particularly for small labels, where scaling, rounding, or cropping can noticeably affect text and barcodes.

    Area Fixes and new features Benefit for InvenTree users
    Printer configuration A single printer URI selects TCP, USB, or Linux device-file transport. URI options also configure SNMP and diagnostic behavior. Keeps connection settings together and supports different deployment arrangements through the same driver.
    Media selection Selects media from label-template metadata and, where status is available, validates it against the loaded tape. Reduces repeated operator configuration and catches wrong-tape jobs.
    Accurate rasterization Uses shared printer render profiles and PyMuPDF viewport rendering to map PDF artwork onto the printer pixel grid. Handles orientation, feed direction, and printable-window cropping. Preserves intended physical dimensions and improves predictability for small labels and barcodes.
    Printable-area validation Detects content outside the printable window and reports a warning or error according to template policy. Uncommitted follow-up changes use the actual printer threshold or dithering behavior for this check. Catches clipping while avoiding false overflow reports from faint pixels that would not print.
    Batch printing Combines selected labels and copies into one printer job, with supported controls for grouped full cuts, half cuts, and chain printing. Supports production runs with fewer separate jobs and better control over label release.
    Status and preflight Checks supported printer status and media conditions before rendering. Handles transitional status responses and exposes printer information through the machine integration. Gives operators earlier feedback about conditions such as incorrect tape or an open cover.
    Debug PDF output Generates diagnostic PDFs showing source artwork, the pixel grid, printable crop, and rendering metadata. Uncommitted improvements distinguish pixels above and below the printing threshold. Makes rendering and clipping problems inspectable without consuming labels.
    Diagnostic helpers Adds template-upload and debug-render scripts, raster-accuracy templates, and an optional short tape-priming job. Provides repeatable ways to investigate rendering behavior and check printer setup.

    Two-color 62red printing remains experimental. Accurate two-color debug visualization is not implemented.

    brother_ql-inventree — printer geometry, transport, and diagnostics

    This library provides the lower-level functionality used by the Brother plugin. The additions can also serve other applications generating Brother raster jobs.

    Area Fixes and new features Benefit for integrations
    P-touch support Extends model capabilities and tape definitions, including narrow tape sizes. Adds P900W/P950NW geometry handling and explicit normal, high-quality, and high-resolution modes. Allows callers to use model-specific geometry and options.
    Raster correctness Corrects print-head placement, margins, minimum raster length, and final-page flags. Validates media compatibility and expected image dimensions. Reduces misplaced artwork and unintended resizing, with explicit errors for incompatible input.
    Shared render-profile API Exposes physical media size, printable dimensions, resolution, crop information, and conversion options. Lets the InvenTree plugin render directly for the selected printer without duplicating geometry rules.
    Multi-label jobs Supports copies, grouped cuts, half cuts, chain printing, and special-tape options according to model capabilities. Supplies the command-level foundation for production batch printing.
    Connection and status handling Normalizes printer URIs, adds network SNMP media/status reporting, and improves stale and transitional response handling. Gives higher-level applications a more consistent connection and status interface.
    Offline diagnostics Captures exact outgoing job data, supports capture without printing, and includes tools to analyze commands and render captured raster pages as previews. Helps distinguish rendering problems from encoding or printer behavior and provides reproducible artifacts for bug reports.

    inventree-adv-sheet-label — physical placement and configurable layouts

    This work targets office printers and adhesive label sheets. It models the physical sheet, label artwork, and printer margins separately.

    Area Fixes and new features Benefit for InvenTree users
    Sheet-size preservation Prevents label templates with their own page/body sizing rules from collapsing the generated sheet to individual-label dimensions. Makes standalone label templates more reliable when arranged on full sheets.
    Physical placement Supports smaller artwork within a physical label, configurable horizontal/vertical alignment, and metadata describing empty borders. Allows templates to be positioned appropriately on different suitable label stock.
    Printer margins Adds runtime printer margins and checks whether content fits. Basic placement errors are validated before queuing the background job. Accounts for printer-specific unprintable edges without embedding them in the sheet catalogue.
    Remembered options Stores submitted print-dialog options per user and restores them as defaults. Reduces repetitive setup for recurring printing tasks.
    Debug overlays Displays physical label boundaries, unused sheet areas, content boxes, and printer margins. Makes alignment and layout problems easier to diagnose.
    YAML layout catalogue Moves bundled sheet definitions into packaged YAML and supports overrides uploaded as InvenTree ReportAssets. Lets administrators add or adjust sheet layouts without editing installed Python code.

    Potentially useful standalone contributions include the sheet-size fix, configurable sheet layouts, printable-area validation, and the shared printer render-profile API. Brother-specific batch and cutting controls provide additional value for production printing.

  10. SchrodingersGat commented on Sep 22, 2026

    @SchrodingersGat
    Member

    @ledvinap please reduce the verbosity of these AI generated posts - they are way too cumbersome to read.

    Refer to this PR - #12913 - which introduces the ability to single-shot tasks, which might be helpful here

  11. ledvinap commented on Sep 22, 2026

    @ledvinap
    ContributorAuthor

    please reduce the verbosity of these AI generated posts - they are way too cumbersome to read.

    Sorry, it is just to show why I'm flooding the repo with all of these individually. Would you mind than I edit them to replace them with few sentences?

  12. github-actions commented on Nov 21, 2026

    @github-actions
    Contributor

    This issue seems stale. Please react to show this is still important.

  13. added
    inactive
    on Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buginactivequestiontriage:not-checkedwarn:slop

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions