fix(print): PrintOptions.copies replicates images for hardware print#115
Conversation
…(#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
Summary of ChangesHello, 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
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
- On the first copy (
idx = 0), the job transitions fromQUEUEDtoPRINTINGsuccessfully, and0is added toactive_indices. - On subsequent copies (
idx > 0), the job is already in thePRINTINGstate. CallingJobStateMachine.transition(job, JobState.PRINTING)raises anInvalidStateTransitionError. - These subsequent copies are caught by the
exceptblock and skipped, meaning their indices are never added toactive_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
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).
-
In
backend/app/services/print_queue.py(_process_batch):
Allow duplicate jobs to bypass the transition if they are alreadyPRINTING: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: ...
-
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 Report✅ All modified and coverable lines are covered by tests. 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
... and 3 files with indirect coverage changes
Flags with carried forward coverage won't be shown. Click here to find out more. Continue to review full report in Codecov by Harness.
🚀 New features to boost your workflow:
|
…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>
## <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]
Bug
User-reported via Hangar issue
strausmann/hangar#109(2026-06-14):DB inspection on production:
Hangar had set
options.copies=3correctly — but only 1 label came off the printer.Root Cause
PrintService.submit_batch_jobbuilds the print-queue image list as one image per request, not honoringoptions.copies:options.copieslands in the DB job payload (for auditing) but is never used to grow the image list passed toprint_multi().Fix
In
submit_batch_job, after rendering, expandimagesandjob_idsbyreq.options.copiesper request. The same UUID is appended N times so:enqueue_batchlength validation still passes (len(images) == len(job_ids)).self._jobs[uuid] = joboverwrites idempotently (dict-set semantics), so DB tracking stays 1 row per Hangar request.Tests
backend/tests/unit/services/test_print_service.py::TestSubmitBatchJobCopies:test_copies_3_yields_three_images— single request withcopies=3→ 3 images, 1 distinct job_idtest_copies_1_yields_single_image— regression guard for default pathtest_mixed_copies_per_request—copies=2 + copies=1→ 3 images, 2 distinct job_idsVerification Path
After merge + deploy, retry the user's job from Hangar:
/samla/SMA-022-003→ Menge 3 → P750W buttonBatch <id> queued on <printer> with 3 itemsRefs
strausmann/hangar#109