Skip to content

fix(print): PrintOptions.copies replicates images for hardware print#115

Merged
strausmann merged 1 commit into
mainfrom
fix/copies-not-replicated
Jun 14, 2026
Merged

fix(print): PrintOptions.copies replicates images for hardware print#115
strausmann merged 1 commit into
mainfrom
fix/copies-not-replicated

Conversation

@strausmann

Copy link
Copy Markdown
Owner

Bug

User-reported via Hangar issue strausmann/hangar#109 (2026-06-14):

"ich habe eben für SMA-022-003 einen druckauftrag gestartet. Ich hatte also Menge 3 eingetippt und dann auf den P750W Druck Button getippt. Es kam aber nur ein einziges Ettiket raus."

DB inspection on production:

SELECT id, state, payload FROM jobs ORDER BY created_at DESC LIMIT 1;
-- payload: { "options": { "copies": 3, ... }, "label_data": { "primary_id": "SMA-022-003", ... } }
-- state: done

Hangar had set options.copies=3 correctly — but only 1 label came off the printer.

Root Cause

PrintService.submit_batch_job builds the print-queue image list as one image per request, not honoring options.copies:

prepared = await asyncio.gather(*[_prepare_one(r) for r in requests])
images = [img for img, _ in prepared]   # ← 1 image per request, ignores copies
...
await self._queue.enqueue_batch(images=images, job_ids=job_ids, ...)

options.copies lands in the DB job payload (for auditing) but is never used to grow the image list passed to print_multi().

Fix

In submit_batch_job, after rendering, expand images and job_ids by req.options.copies per request. The same UUID is appended N times so:

  • enqueue_batch length validation still passes (len(images) == len(job_ids)).
  • self._jobs[uuid] = job overwrites idempotently (dict-set semantics), so DB tracking stays 1 row per Hangar request.
  • The printer receives N copies of the rendered image → N labels per Hangar order.
images: list[Image.Image] = []
expanded_job_ids: list[UUID] = []
for req, (img, _ld), jid in zip(requests, prepared, job_ids, strict=True):
    n = max(1, int(req.options.copies))
    for _ in range(n):
        images.append(img)
        expanded_job_ids.append(jid)

Tests

backend/tests/unit/services/test_print_service.py::TestSubmitBatchJobCopies:

  • test_copies_3_yields_three_images — single request with copies=3 → 3 images, 1 distinct job_id
  • test_copies_1_yields_single_image — regression guard for default path
  • test_mixed_copies_per_requestcopies=2 + copies=1 → 3 images, 2 distinct job_ids
$ uv run pytest tests/unit/services/ tests/unit/test_batch_dispatch.py
========== 227 passed in 50.62s ==========

Verification Path

After merge + deploy, retry the user's job from Hangar:

  1. Hangar /samla/SMA-022-003 → Menge 3 → P750W button
  2. Hub log should show: Batch <id> queued on <printer> with 3 items
  3. Printer should produce 3 labels connected by half-cuts

Refs strausmann/hangar#109

…(#hangar-109)

Bug 2026-06-14 — user-reported via Hangar Issue #109:
Hangar submits a Samla print job with options.copies=3 for SMA-022-003,
but only 1 label comes out of the printer. The 2 expected half-cut companion
labels are missing.

Root cause: PrintService.submit_batch_job builds `images = [img for img, _ in
prepared]` — one image per request — and forwards `options.copies` to the
DB job payload but never to the PrintQueue. enqueue_batch then calls
print_multi() with a single image, producing a single label.

Fix: in submit_batch_job, expand `images` and `job_ids` according to each
request's `options.copies`. The same UUID is appended N times so enqueue_batch
length-validation passes and self._jobs[uuid] is overwritten (dict-set
semantics) — DB still tracks 1 row per Hangar request, but the printer
receives N copies of the rendered image.

Tests:
- test_copies_3_yields_three_images: single request with copies=3 → 3 images
- test_copies_1_yields_single_image: regression guard for default path
- test_mixed_copies_per_request: copies=2 + copies=1 → 3 images, 2 distinct job_ids

Refs strausmann/hangar#109
Copilot AI review requested due to automatic review settings June 14, 2026 10:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a bug where print jobs specifying multiple copies were only producing a single label. The fix involves expanding the image list and corresponding job IDs during the batch submission process, ensuring that the hardware receives the correct number of images while maintaining proper database tracking for each Hangar request.

Highlights

  • Fix Print Job Replication: Updated submit_batch_job to correctly replicate images based on the PrintOptions.copies parameter, ensuring the printer receives the requested number of labels.
  • Regression Testing: Added comprehensive unit tests in TestSubmitBatchJobCopies to verify single-copy, multi-copy, and mixed-copy scenarios.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@strausmann
strausmann merged commit d27bbcc into main Jun 14, 2026
13 checks passed
@strausmann
strausmann deleted the fix/copies-not-replicated branch June 14, 2026 10:37

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request addresses a bug where PrintOptions.copies > 1 was ignored by replicating the generated images and job IDs before enqueuing them, supported by new unit tests. However, a critical integration issue was identified: replicating the same job_id for multiple copies will cause the queue worker (_process_batch) to skip subsequent copies due to InvalidStateTransitionError when attempting to transition an already PRINTING job. To resolve this, the queue worker should be updated to allow duplicate jobs to bypass the state transition and deduplicate them before moving to terminal states.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +200 to +204
for req, (img, _ld), jid in zip(requests, prepared, job_ids, strict=True):
n = max(1, int(req.options.copies))
for _ in range(n):
images.append(img)
expanded_job_ids.append(jid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

Critical Bug: Duplicate job_ids will be skipped by the queue worker

While this change correctly replicates the images and job IDs to pass the length validation in enqueue_batch, it introduces a critical bug during the actual printing process in PrintQueue._process_batch (defined in backend/app/services/print_queue.py).

In _process_batch, the worker iterates over batch.job_ids and attempts to transition each job to the PRINTING state:

for idx, jid in enumerate(batch.job_ids):
    job = self._jobs.get(str(jid))
    ...
    try:
        JobStateMachine.transition(job, JobState.PRINTING)
        ...
        active_indices.append(idx)
    except InvalidStateTransitionError:
        logger.warning("Batch %s: job %s skipped — state already %s", ...)

Because expanded_job_ids contains duplicate UUIDs for copies, self._jobs.get(str(jid)) retrieves the exact same in-memory Job instance for all copies of a request.

  1. On the first copy (idx = 0), the job transitions from QUEUED to PRINTING successfully, and 0 is added to active_indices.
  2. On subsequent copies (idx > 0), the job is already in the PRINTING state. Calling JobStateMachine.transition(job, JobState.PRINTING) raises an InvalidStateTransitionError.
  3. These subsequent copies are caught by the except block and skipped, meaning their indices are never added to active_indices.

As a result, active_payloads will only contain the first copy's image, and the printer will still only print one single label instead of $N$ copies.

Why did the tests pass?

The unit tests in test_print_service.py mock queue.enqueue_batch and only assert that the arguments passed to it are correct. They do not run the actual queue worker loop (_process_batch), which is why this integration bug went unnoticed.

Recommended Solution

To fix this, we need to update _process_batch in backend/app/services/print_queue.py to allow processing duplicate job IDs without raising state transition errors, and deduplicate them during final state transitions (like COMPLETED or FAILED).

  1. In backend/app/services/print_queue.py (_process_batch):
    Allow duplicate jobs to bypass the transition if they are already PRINTING:

    for idx, jid in enumerate(batch.job_ids):
        job = self._jobs.get(str(jid))
        if job is None:
            continue
        try:
            if job.state != JobState.PRINTING:
                JobStateMachine.transition(job, JobState.PRINTING)
                self._notify_state_change(job, JobState.QUEUED, JobState.PRINTING, ...)
                await self._store.mark_printing(UUID(job.id))
            active_jobs.append(job)
            active_indices.append(idx)
        except InvalidStateTransitionError:
            ...
  2. Deduplicate transitions to terminal states (COMPLETED / FAILED):

    # Success: transition unique active jobs to COMPLETED
    unique_active_jobs = []
    seen = set()
    for job in active_jobs:
        if job.id not in seen:
            unique_active_jobs.append(job)
            seen.add(job.id)
    
    for job in unique_active_jobs:
        # Transition to COMPLETED

@codecov

codecov Bot commented Jun 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.22%. Comparing base (e459fd7) to head (ef5d86d).
⚠️ Report is 2 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #115      +/-   ##
==========================================
- Coverage   89.28%   89.22%   -0.06%     
==========================================
  Files          91       91              
  Lines        4246     4251       +5     
  Branches      366      368       +2     
==========================================
+ Hits         3791     3793       +2     
- Misses        356      360       +4     
+ Partials       99       98       -1     
Components Coverage Δ
Printer Backends (transport) 86.87% <ø> (ø)
Printer Models (drivers) 88.20% <ø> (ø)
Services 91.20% <100.00%> (-0.04%) ⬇️
REST API 84.97% <ø> (ø)
Pydantic Schemas 100.00% <ø> (ø)
Integration Plugins 100.00% <ø> (ø)
Files with missing lines Coverage Δ
backend/app/services/print_service.py 89.70% <100.00%> (+0.81%) ⬆️

... and 3 files with indirect coverage changes

Flag Coverage Δ
backend 89.22% <100.00%> (-0.06%) ⬇️

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


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 922cc2f...ef5d86d. Read the comment docs.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

strausmann added a commit that referenced this pull request Jun 14, 2026
…r-109) (#120)

User-Bericht 2026-06-14 nach PR #115: SMA-022-003 mit Menge 3 druckt
weiterhin nur 1 Etikett. Live-Logs zeigen:

  Batch 7d8470f4: job 711db9bc skipped — state already printing (cancelled?)

Root Cause: PR #115 hat das Image N-mal mit DERSELBEN job_id eingereiht.
Der BatchWorker macht für jeden batch.job_ids einen
`JobStateMachine.transition(job, PRINTING)` — der zweite Aufruf scheitert
mit InvalidStateTransitionError (Job ist bereits PRINTING), das Replikat
wird übersprungen. Resultat: nur 1 active_payload an print_multi → 1
Etikett trotz copies=3.

Fix: pro Request UND pro Copy eine eigene UUID erzeugen, jeder Copy
landet als separater DB-Job. BatchWorker kann sie unabhängig transitionen.

API-Vertrag bleibt für Hangar erhalten:
- `submit_batch_job` gibt weiterhin 1 master_id pro Request zurück (1:1
  mit Hangar-Bestellung), nicht 1:N.
- Intern werden N Hub-Job-Records mit copy_index/copy_total/copy_master_id
  Payload-Metadata persistiert (für Audit + zukünftige UI).

Tests:
- TestSubmitBatchJobCopies wurde korrigiert — der vorherige Assert
  "same job_id replicated 3x" war FALSCH (er hatte den Bug bestätigt
  statt verhindert). Neu: `len(set(kwargs["job_ids"])) == 3`.
- master_ids bleibt 1 pro Request, master_ids[0] ist eine der enqueued IDs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
github-actions Bot pushed a commit that referenced this pull request Jun 15, 2026
## <small>0.10.2 (2026-06-15)</small>

* refactor(main): _resolve_model_id_from_config nimmt PrinterYAMLConfig statt Any (#67) (#123) ([2ff51d2](2ff51d2)), closes [#67](#67) [#123](#123) [#67](#67) [#59](#59) [#67](#67) [#59](#59)
* refactor(snipeit): typisiere response payload als TypedDict statt dict[str, Any] (#67) (#122) ([e88601b](e88601b)), closes [#67](#67) [#122](#122) [#67](#67) [#67](#67) [#51](#51)
* perf(lifespan): plugin-discovery in Thread auslagern (Audit #67) (#121) ([48215b4](48215b4)), closes [#67](#67) [#121](#121) [#67](#67) [#59](#59)
* fix(config): stricter validation for log_level + webhook_api_key (#46) (#116) ([6b8ac30](6b8ac30)), closes [#46](#46) [#116](#116) [#46](#46) [#46](#46) [#46](#46) [#46](#46) [#116](#116)
* fix(print): copies-replication erzeugt UNIQUE job_ids (Round 2 #hangar-109) (#120) ([bd781ae](bd781ae)), closes [#hangar-109](https://github.com/strausmann/label-printer-hub/issues/hangar-109) [#120](#120) [#115](#115)
* fix(print): PrintOptions.copies replicates images for hardware print (#hangar-109) (#115) ([d27bbcc](d27bbcc)), closes [#hangar-109](https://github.com/strausmann/label-printer-hub/issues/hangar-109) [#115](#115) [strausmann/hangar#109](https://github.com/strausmann/hangar/issues/109)
* docs(metrics): präzisiere sse_events_published_total Beschreibung (Audit #67) (#119) ([ab8c4c4](ab8c4c4)), closes [#67](#67) [#119](#119) [#67](#67) [#67](#67) [#65](#65)
* docs(ptouch): korrigiere Tape-Klassen-Namen in ptouch-integration.md (Audit #67) (#118) ([0faab99](0faab99)), closes [#67](#67) [#118](#118) [#67](#67) [#59](#59)
* chore(readme): codecov badge ohne embedded Token (Audit #67) (#117) ([4bb5423](4bb5423)), closes [#67](#67) [#117](#117) [#67](#67) [#59](#59)

[skip ci]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants