浏览代码

Queue: "Any model" jobs only go to a printer whose nozzle fits (#3536) (#3554)

Eifel-Joe 6 天之前
父节点
当前提交
977af4da00
共有 2 个文件被更改,包括 697 次插入 和 2 次删除
  1. 111 2
      backend/app/services/print_scheduler.py
  2. 586 0
      backend/tests/unit/test_scheduler_nozzle_pick_3536.py

+ 111 - 2
backend/app/services/print_scheduler.py

@@ -496,6 +496,8 @@ class _ModelCandidate:
     required_filament_types: str | None
     required_filament_types: str | None
     filament_overrides: str | None
     filament_overrides: str | None
     variant: "PrintQueueVariant | None" = None
     variant: "PrintQueueVariant | None" = None
+    # Nozzle diameter (mm) the file was sliced for, None when unknown (#3536).
+    sliced_nozzle: float | None = None
 
 
 
 
 def _sliced_for_model(archive, library_file) -> str | None:
 def _sliced_for_model(archive, library_file) -> str | None:
@@ -507,6 +509,26 @@ def _sliced_for_model(archive, library_file) -> str | None:
     return None
     return None
 
 
 
 
+def _sliced_nozzle(archive, library_file) -> float | None:
+    """Nozzle diameter (mm) a 3MF was sliced for, None when unknown (#3536).
+
+    Fail-safe: a missing, unparsable or non-positive value means "unknown", and
+    unknown never excludes a printer. Not rounded here; the tolerance lives in
+    ``_nozzle_mismatch_message``.
+    """
+    if archive is not None:
+        raw = archive.nozzle_diameter
+    elif library_file is not None and library_file.file_metadata:
+        raw = library_file.file_metadata.get("nozzle_diameter")
+    else:
+        return None
+    try:
+        value = float(raw)
+    except (TypeError, ValueError):
+        return None
+    return value if value > 0 else None
+
+
 def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
 def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
     """The filament a candidate needs, as ``(types, overrides)``.
     """The filament a candidate needs, as ``(types, overrides)``.
 
 
@@ -593,6 +615,7 @@ def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
                 sliced_for=_sliced_for_model(item.archive, item.library_file),
                 sliced_for=_sliced_for_model(item.archive, item.library_file),
                 required_filament_types=item.required_filament_types,
                 required_filament_types=item.required_filament_types,
                 filament_overrides=item.filament_overrides,
                 filament_overrides=item.filament_overrides,
+                sliced_nozzle=_sliced_nozzle(item.archive, item.library_file),
             )
             )
         ]
         ]
 
 
@@ -611,6 +634,7 @@ def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
             required_filament_types=v.required_filament_types,
             required_filament_types=v.required_filament_types,
             filament_overrides=v.filament_overrides,
             filament_overrides=v.filament_overrides,
             variant=v,
             variant=v,
+            sliced_nozzle=_sliced_nozzle(None, v.library_file),
         )
         )
         for v in ordered
         for v in ordered
     ]
     ]
@@ -1130,6 +1154,28 @@ def _nozzle_mismatch_message(
     )
     )
 
 
 
 
+def _wrong_nozzle_label(printer_name: str, status, sliced_nozzle: float | None) -> str | None:
+    """Label of a printer that cannot print a *sliced_nozzle* file, else None (#3536).
+
+    Used by the "Any <model>" pick, which before #3536 ignored the nozzle and
+    handed a 0.6 file to a 0.4 printer that then failed in ``_start_print``.
+    None means "fits or unknown" (no status, no sliced diameter, no reported
+    nozzles), so a printer is only ever skipped on a POSITIVE mismatch. The
+    decision stays in ``_nozzle_mismatch_message`` (same tolerance, same rack
+    rule as the start guard); this only formats the name for the wait reason.
+    """
+    if status is None:
+        return None
+    installed = _installed_nozzle_diameters(status)
+    rack = _rack_nozzle_diameters(status)
+    if _nozzle_mismatch_message(sliced_nozzle, installed, rack) is None:
+        return None
+    where = _format_diameters(installed) if installed else "no nozzle mounted"
+    if rack:
+        where += f", rack {_format_diameters(rack)}"
+    return f"{printer_name} ({where})"
+
+
 def _describe_filament(entry: dict, nozzle_key: str) -> str:
 def _describe_filament(entry: dict, nozzle_key: str) -> str:
     """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
     """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
 
 
@@ -2531,6 +2577,7 @@ class PrintScheduler:
                                 drying_ids=drying_held,
                                 drying_ids=drying_held,
                                 unmatched_on=unmatched_on,
                                 unmatched_on=unmatched_on,
                                 refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
                                 refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
+                                sliced_nozzle=candidate.sliced_nozzle,
                             )
                             )
                             # "Only if the previous print succeeded" is about the
                             # "Only if the previous print succeeded" is about the
                             # printer the job lands on: one whose last print failed
                             # printer the job lands on: one whose last print failed
@@ -3427,6 +3474,8 @@ class PrintScheduler:
         rather than woken (#2876): the colours are readable while it is off, so
         rather than woken (#2876): the colours are readable while it is off, so
         switching a farm on one machine at a time to discover them wakes
         switching a farm on one machine at a time to discover them wakes
         printers that could never have taken the job.
         printers that could never have taken the job.
+        A printer whose last known nozzle cannot print the file is passed over
+        the same way (#3536).
 
 
         Deliberately does NOT go on to match the job once a printer is up: AMS
         Deliberately does NOT go on to match the job once a printer is up: AMS
         trays arrive with the first status push after connect, so a filament
         trays arrive with the first status push after connect, so a filament
@@ -3466,6 +3515,23 @@ class PrintScheduler:
                     )
                     )
                     continue
                     continue
 
 
+                # #3536: the matcher rejects a printer whose nozzle cannot print
+                # the file, so waking one only spends this pass's single wake and
+                # the boot wait. A powered-off printer keeps its last status, so
+                # the nozzle is readable here. Fail-safe: no status or no reported
+                # nozzle means "fits" (None) and the printer is woken as before.
+                label = _wrong_nozzle_label(
+                    printer.name, printer_manager.get_status(printer.id), candidate.sliced_nozzle
+                )
+                if label:
+                    logger.info(
+                        "Not powering on printer %s for a %s job: its nozzle cannot print the file (%s)",
+                        printer.id,
+                        candidate.target_model,
+                        label,
+                    )
+                    continue
+
                 shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
                 shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
                 if shortfall:
                 if shortfall:
                     logger.info(
                     logger.info(
@@ -3530,6 +3596,7 @@ class PrintScheduler:
         drying_ids: set[int] | None = None,
         drying_ids: set[int] | None = None,
         unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
         unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
         refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
         refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
+        sliced_nozzle: float | None = None,
     ) -> tuple[int | None, str | None]:
     ) -> tuple[int | None, str | None]:
         """Find an idle, connected printer matching the model with compatible filaments.
         """Find an idle, connected printer matching the model with compatible filaments.
 
 
@@ -3562,6 +3629,9 @@ class PrintScheduler:
             refused_uploads: Excluded printers out of dispatch after a refused upload,
             refused_uploads: Excluded printers out of dispatch after a refused upload,
                              with why (#3409). Each is named with the reason its own
                              with why (#3409). Each is named with the reason its own
                              queue rows show, not as "Busy".
                              queue rows show, not as "Busy".
+            sliced_nozzle: Nozzle diameter the file was sliced for (#3536). A printer
+                           without that nozzle is passed over; None (unknown) passes
+                           every printer, as before.
 
 
         Returns:
         Returns:
             Tuple of (printer_id, waiting_reason):
             Tuple of (printer_id, waiting_reason):
@@ -3587,12 +3657,23 @@ class PrintScheduler:
         printers_offline = []
         printers_offline = []
         printers_offline_no_plug = []
         printers_offline_no_plug = []
         printers_missing_filament: list[tuple[str, list[str]]] = []
         printers_missing_filament: list[tuple[str, list[str]]] = []
+        printers_wrong_nozzle: list[str] = []
         candidates: list[tuple[int, int]] = []  # (printer_id, color_match_count)
         candidates: list[tuple[int, int]] = []  # (printer_id, color_match_count)
         # The first eligible printer that is short on filament, kept in case
         # The first eligible printer that is short on filament, kept in case
         # every eligible printer is (#3137).
         # every eligible printer is (#3137).
         short_fallback: int | None = None
         short_fallback: int | None = None
 
 
         for printer in printers:
         for printer in printers:
+            # #3536: the pick ignored the nozzle, so a job sliced for 0.6 mm went to a
+            # 0.4 mm printer and the #1899 guard then failed it in _start_print instead
+            # of trying another printer. Fail-safe: no diameter or no reported nozzle
+            # fits (_wrong_nozzle_label returns None). Checked first on purpose: a
+            # wrong-nozzle printer that is busy, excluded or offline must not read as
+            # "Busy"/"Offline", which would hold the job silently forever.
+            wrong_nozzle = _wrong_nozzle_label(printer.name, printer_manager.get_status(printer.id), sliced_nozzle)
+            if wrong_nozzle:
+                printers_wrong_nozzle.append(wrong_nozzle)
+                continue
             if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
             if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
                 printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
                 printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
                 continue
                 continue
@@ -3736,6 +3817,21 @@ class PrintScheduler:
         if short_fallback is not None:
         if short_fallback is not None:
             return short_fallback, None
             return short_fallback, None
 
 
+        # #3536: nothing else is in the way, so the nozzle is the whole reason. Named
+        # per printer; when something else also waits, the wrong ones stay out so
+        # that reason (e.g. "Busy") is not drowned by a printer that cannot help.
+        if printers_wrong_nozzle and not (
+            printers_busy
+            or printers_refused
+            or printers_offline
+            or printers_offline_no_plug
+            or printers_missing_filament
+        ):
+            return None, (
+                f"No {normalized_model}{location_suffix} has a {sliced_nozzle:g}mm nozzle: "
+                f"{', '.join(printers_wrong_nozzle)}"
+            )
+
         # Build waiting reason from what we found
         # Build waiting reason from what we found
         reasons = []
         reasons = []
         if printers_missing_filament:
         if printers_missing_filament:
@@ -6209,7 +6305,10 @@ class PrintScheduler:
         of each of its candidate models, in its location, that its creator may use.
         of each of its candidate models, in its location, that its creator may use.
 
 
         ``cache`` holds one lookup per model, location and creator for the pass,
         ``cache`` holds one lookup per model, location and creator for the pass,
-        so a long queue of model jobs does not query once per job."""
+        so a long queue of model jobs does not query once per job.
+
+        A printer whose last known nozzle cannot print the file is left out
+        (#3536): the job stays pending there, so it must not hold drying off."""
         printer_ids: set[int] = set()
         printer_ids: set[int] = set()
         for candidate in _candidates_for(item):
         for candidate in _candidates_for(item):
             if not candidate.target_model:
             if not candidate.target_model:
@@ -6218,7 +6317,16 @@ class PrintScheduler:
             if key not in cache:
             if key not in cache:
                 printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
                 printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
                 cache[key] = {printer.id for printer in printers}
                 cache[key] = {printer.id for printer in printers}
-            printer_ids |= cache[key]
+            # #3536: a job with no fitting nozzle now stays pending instead of
+            # failing at once, so it must not count for a printer whose last
+            # known nozzle cannot print it (it would block or trigger drying
+            # there for good). Unknown nozzle fits (fail-safe). The cache stays
+            # per model; the filter runs per candidate, not per cache entry.
+            printer_ids |= {
+                pid
+                for pid in cache[key]
+                if _wrong_nozzle_label("", printer_manager.get_status(pid), candidate.sliced_nozzle) is None
+            }
         return printer_ids
         return printer_ids
 
 
     async def _check_auto_drying(
     async def _check_auto_drying(
@@ -8650,6 +8758,7 @@ class PrintScheduler:
                 printer_scope=printer_scope,
                 printer_scope=printer_scope,
                 is_short=is_short,
                 is_short=is_short,
                 unmatched_on=unmatched_on,
                 unmatched_on=unmatched_on,
+                sliced_nozzle=candidates[0].sliced_nozzle,
             )
             )
             # Every idle printer short comes back as the first of them.
             # Every idle printer short comes back as the first of them.
             if match_id is None or await is_short(match_id):
             if match_id is None or await is_short(match_id):

+ 586 - 0
backend/tests/unit/test_scheduler_nozzle_pick_3536.py

@@ -0,0 +1,586 @@
+"""Nozzle-aware printer pick for "Any <model>" queue items (#3536).
+
+Before #3536 the model-based pick looked at model, filament and state but not
+at the nozzle: a file sliced for 0.6 mm could be assigned to a printer with a
+0.4 mm nozzle and then fail in ``_start_print``. These tests cover the pieces
+of the fix in order: the sliced diameter carried on each candidate, then the
+printer filter built on it.
+"""
+
+from contextlib import ExitStack
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.orm import selectinload
+
+import backend.app.models  # noqa: F401 - populate Base.metadata
+from backend.app.core.database import Base
+from backend.app.core.printer_scope import ALL_PRINTERS
+from backend.app.models.library import LibraryFile
+from backend.app.models.print_queue import PrintQueueItem
+from backend.app.models.printer import Printer
+from backend.app.services.print_scheduler import (
+    PrintScheduler,
+    _asks_nothing_new,
+    _candidates_for,
+    _ModelCandidate,
+    _sliced_nozzle,
+    _wrong_nozzle_label,
+)
+from backend.tests.unit.test_scheduler_dispatch_order_2915 import PRINTERS as ORDER_PRINTERS, _farm
+
+# --- Sliced diameter per candidate -------------------------------------------
+
+
+def _item(*, variants=None, archive=None, library_file=None):
+    return SimpleNamespace(
+        variants=variants or [],
+        archive=archive,
+        archive_id=1 if archive is not None else None,
+        library_file=library_file,
+        library_file_id=2 if library_file is not None else None,
+        target_model="A1",
+        required_filament_types=None,
+        filament_overrides=None,
+    )
+
+
+def _variant(vid, nozzle):
+    return SimpleNamespace(
+        id=vid,
+        position=vid,
+        attempt_count=0,
+        target_model="A1",
+        required_filament_types=None,
+        filament_overrides=None,
+        library_file=SimpleNamespace(deleted_at=None, file_metadata={"nozzle_diameter": nozzle}),
+    )
+
+
+def test_sliced_nozzle_from_archive():
+    assert _sliced_nozzle(SimpleNamespace(nozzle_diameter=0.6), None) == 0.6
+
+
+def test_sliced_nozzle_from_library_metadata():
+    assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": 0.6})) == 0.6
+
+
+def test_sliced_nozzle_unknown():
+    assert _sliced_nozzle(None, SimpleNamespace(file_metadata=None)) is None
+    assert _sliced_nozzle(None, SimpleNamespace(file_metadata={})) is None
+    assert _sliced_nozzle(None, None) is None
+
+
+def test_sliced_nozzle_rejects_garbage_and_non_positive():
+    assert _sliced_nozzle(SimpleNamespace(nozzle_diameter=0), None) is None
+    assert _sliced_nozzle(SimpleNamespace(nozzle_diameter=-0.4), None) is None
+    assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": "abc"})) is None
+    assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": [0.4]})) is None
+    assert _sliced_nozzle(None, SimpleNamespace(file_metadata={"nozzle_diameter": "0.6"})) == 0.6
+
+
+def test_sliced_nozzle_is_read_without_rounding():
+    # The tolerance lives in _nozzle_mismatch_message, not here.
+    meta = SimpleNamespace(file_metadata={"nozzle_diameter": "0.6000001"})
+    assert _sliced_nozzle(None, meta) == 0.6000001
+
+
+def test_candidates_carry_their_own_nozzle():
+    single = _item(library_file=SimpleNamespace(file_metadata={"nozzle_diameter": 0.6}))
+    assert [c.sliced_nozzle for c in _candidates_for(single)] == [0.6]
+
+    multi = _item(variants=[_variant(1, 0.4), _variant(2, 0.6)])
+    assert sorted(c.sliced_nozzle for c in _candidates_for(multi)) == [0.4, 0.6]
+
+
+# --- Does this nozzle fit? ---------------------------------------------------
+
+
+def _state(*diameters: str):
+    """PrinterState-shaped namespace with the given nozzle diameter strings."""
+    return SimpleNamespace(nozzles=[SimpleNamespace(nozzle_diameter=d) for d in diameters])
+
+
+def _h2c(*rack: tuple[int, str], mounted: str = "0.4"):
+    """H2C-shaped state: one mounted hotend plus docked nozzles (#2885 shape)."""
+    info = [{"id": 0, "diameter": mounted, "wear": 0, "max_temp": 350, "serial_number": "SN0"}]
+    info += [
+        {"id": nozzle_id, "diameter": d, "wear": 0, "max_temp": 350, "serial_number": f"SN{nozzle_id}"}
+        for nozzle_id, d in rack
+    ]
+    return SimpleNamespace(nozzles=[SimpleNamespace(nozzle_diameter=mounted)], nozzle_rack=info)
+
+
+def test_wrong_nozzle_label_single_and_dual():
+    assert _wrong_nozzle_label("A1-1", _state("0.4"), 0.6) == "A1-1 (0.4mm)"
+    assert _wrong_nozzle_label("A1-1", _state("0.6"), 0.6) is None
+    assert _wrong_nozzle_label("H2D-1", _state("0.4", "0.4"), 0.6) == "H2D-1 (0.4mm)"
+    assert _wrong_nozzle_label("H2D-1", _state("0.4", "0.6"), 0.6) is None
+
+
+def test_wrong_nozzle_label_unknown_fits():
+    assert _wrong_nozzle_label("A1-1", _state("0.4"), None) is None
+    assert _wrong_nozzle_label("A1-1", _state("0.4"), 0) is None
+    assert _wrong_nozzle_label("A1-1", None, 0.6) is None
+    assert _wrong_nozzle_label("A1-1", _state(""), 0.6) is None  # nothing reported
+
+
+def test_wrong_nozzle_label_rack():
+    assert _wrong_nozzle_label("H2C-1", _h2c((16, "0.6")), 0.6) is None
+    assert _wrong_nozzle_label("H2C-1", _h2c((16, "0.2"), (18, "0.8")), 0.6) == "H2C-1 (0.4mm, rack 0.2mm / 0.8mm)"
+
+
+def test_wrong_nozzle_label_rack_without_mounted_nozzle():
+    status = SimpleNamespace(
+        nozzles=[SimpleNamespace(nozzle_diameter="")],
+        nozzle_rack=[{"id": 16, "diameter": "0.2", "max_temp": 350, "serial_number": "SN16"}],
+    )
+    assert _wrong_nozzle_label("H2C-1", status, 0.6) == "H2C-1 (no nozzle mounted, rack 0.2mm)"
+
+
+SIZES = ["0.2", "0.4", "0.6", "0.8"]
+
+
+@pytest.mark.parametrize("sliced", SIZES)
+@pytest.mark.parametrize("installed", SIZES)
+def test_only_the_same_size_fits(sliced, installed):
+    # Same size fits, every other (also the neighbouring one) never does.
+    label = _wrong_nozzle_label("A1-1", _state(installed), float(sliced))
+    if sliced == installed:
+        assert label is None
+    else:
+        assert label == f"A1-1 ({installed}mm)"
+
+
+def test_float_noise_from_metadata_still_fits():
+    assert _wrong_nozzle_label("A1-1", _state("0.6"), 0.6000001) is None
+    assert _wrong_nozzle_label("A1-1", _state("0.4"), 0.6000001) == "A1-1 (0.4mm)"
+
+
+# --- Matcher: passes over a printer with the wrong nozzle --------------------
+
+
+@pytest.fixture
+async def a1_farm():
+    """Two A1s in "Workshop"; A1-1 is the one with fewer print hours."""
+    engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
+    async with engine.begin() as conn:
+        await conn.run_sync(Base.metadata.create_all)
+    session_maker = async_sessionmaker(engine, expire_on_commit=False)
+    async with session_maker() as db:
+        db.add_all(
+            [
+                Printer(
+                    id=pid,
+                    name=f"A1-{pid}",
+                    serial_number=f"A1000{pid}",
+                    ip_address=f"192.0.2.{pid}",
+                    access_code="x",
+                    model="A1",
+                    is_active=True,
+                    location="Workshop",
+                    runtime_seconds=pid * 3600,
+                )
+                for pid in (1, 2)
+            ]
+        )
+        await db.commit()
+    try:
+        yield SimpleNamespace(session_maker=session_maker)
+    finally:
+        await engine.dispose()
+
+
+async def _find(ctx, scheduler, states, *, model="A1", exclude=frozenset(), connected=True, idle=None, **kwargs):
+    """Run the matcher; ``states`` maps printer id to its reported state (or None)."""
+    idle = idle or {}
+    with (
+        patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
+        patch(
+            "backend.app.services.print_scheduler.printer_manager.is_connected",
+            lambda pid: connected if not callable(connected) else connected(pid),
+        ),
+        patch.object(scheduler, "_is_printer_idle", lambda pid, *_a, **_k: idle.get(pid, True)),
+    ):
+        async with ctx.session_maker() as db:
+            return await scheduler._find_idle_printer_for_model(db, model, set(exclude), **kwargs)
+
+
+class TestMatcherNozzle:
+    @pytest.mark.asyncio
+    async def test_skips_the_printer_with_the_wrong_nozzle(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.6")}
+        assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6) == (2, None)
+
+    @pytest.mark.asyncio
+    async def test_no_printer_fits_names_every_nozzle(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.4")}
+        assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6) == (
+            None,
+            "No A1 has a 0.6mm nozzle: A1-1 (0.4mm), A1-2 (0.4mm)",
+        )
+
+    @pytest.mark.asyncio
+    async def test_reason_names_the_location(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.4")}
+        _, reason = await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6, target_location="Workshop")
+        assert reason.startswith("No A1 in Workshop has a 0.6mm nozzle: ")
+
+    @pytest.mark.asyncio
+    async def test_float_noise_in_the_sliced_size_is_not_shown(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.4")}
+        _, reason = await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6000001)
+        assert reason.startswith("No A1 has a 0.6mm nozzle: ")
+
+    @pytest.mark.asyncio
+    async def test_unknown_sliced_nozzle_behaves_as_before(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.6")}
+        assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=None) == (1, None)
+
+    @pytest.mark.asyncio
+    async def test_printer_without_status_fits(self, a1_farm):
+        states = {1: None, 2: _state("0.4")}
+        assert await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6) == (1, None)
+
+    @pytest.mark.asyncio
+    async def test_wrong_nozzle_printer_does_not_hide_a_busy_matching_one(self, a1_farm):
+        """The only printer that fits is busy: the job just waits, silently."""
+        states = {1: _state("0.4"), 2: _state("0.6")}
+        pick, reason = await _find(a1_farm, PrintScheduler(), states, exclude={2}, sliced_nozzle=0.6)
+        assert pick is None
+        assert reason == "Busy: A1-2"
+        assert PrintScheduler._is_busy_only(reason) is True
+
+    @pytest.mark.asyncio
+    async def test_busy_or_offline_wrong_nozzle_printers_read_as_nozzle_not_busy(self, a1_farm):
+        """A1-1 is printing, A1-2 offline, both 0.4: waiting would never help."""
+        states = {1: _state("0.4"), 2: _state("0.4")}
+        pick, reason = await _find(
+            a1_farm,
+            PrintScheduler(),
+            states,
+            connected=lambda pid: pid == 1,
+            idle={1: False},
+            sliced_nozzle=0.6,
+        )
+        assert pick is None
+        assert reason == "No A1 has a 0.6mm nozzle: A1-1 (0.4mm), A1-2 (0.4mm)"
+
+    @pytest.mark.asyncio
+    async def test_excluded_wrong_nozzle_printer_is_not_listed_as_busy(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.4")}
+        _, reason = await _find(a1_farm, PrintScheduler(), states, exclude={1, 2}, sliced_nozzle=0.6)
+        assert reason.startswith("No A1 has a 0.6mm nozzle: ")
+
+    @pytest.mark.asyncio
+    async def test_nozzle_reason_is_not_busy_only_and_asks_something(self, a1_farm):
+        states = {1: _state("0.4"), 2: _state("0.4")}
+        _, reason = await _find(a1_farm, PrintScheduler(), states, sliced_nozzle=0.6)
+        assert PrintScheduler._is_busy_only(reason) is False
+        assert _asks_nothing_new(reason) is False
+
+    @pytest.mark.asyncio
+    async def test_missing_filament_and_wrong_nozzle_mixed(self, a1_farm):
+        """A1-1 has the wrong nozzle, A1-2 fits but lacks PETG: only the filament is named."""
+        scheduler = PrintScheduler()
+        states = {1: _state("0.4"), 2: _state("0.6")}
+        with patch.object(
+            scheduler, "_get_missing_filament_types", lambda pid, _types, *_a, **_k: ["PETG"] if pid == 2 else []
+        ):
+            pick, reason = await _find(a1_farm, scheduler, states, sliced_nozzle=0.6, required_filament_types=["PETG"])
+        assert pick is None
+        assert reason == "Waiting for filament: A1-2 (needs PETG)"
+
+
+# --- Wake path: does not power on a printer with the wrong nozzle ------------
+
+
+class TestWakeNozzle:
+    async def _wake(self, ctx, sliced_nozzle):
+        scheduler = PrintScheduler()
+        plug = SimpleNamespace(id=1, auto_on=True, enabled=True, controls_printer_power=True)
+        power_on = AsyncMock(return_value=True)
+        # Both printers are off but keep their last status (A1-1 0.4, A1-2 0.6).
+        states = {1: _state("0.4"), 2: _state("0.6")}
+        with (
+            patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=False)),
+            patch(
+                "backend.app.services.print_scheduler.printer_manager.is_awaiting_plate_clear",
+                MagicMock(return_value=False),
+            ),
+            patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
+            patch.object(scheduler, "_cached_filament_shortfall", MagicMock(return_value=[])),
+            patch.object(scheduler, "_get_smart_plugs", AsyncMock(return_value=[plug])),
+            patch.object(scheduler, "_power_on_and_wait", power_on),
+        ):
+            async with ctx.session_maker() as db:
+                return await scheduler._wake_printer_for_model(
+                    db,
+                    [
+                        _ModelCandidate(
+                            target_model="A1",
+                            sliced_for=None,
+                            required_filament_types=None,
+                            filament_overrides=None,
+                            sliced_nozzle=sliced_nozzle,
+                        )
+                    ],
+                    None,
+                    set(),
+                    {1, 2},
+                    require_plate_clear=False,
+                )
+
+    @pytest.mark.asyncio
+    async def test_wakes_the_printer_whose_nozzle_fits(self, a1_farm):
+        assert await self._wake(a1_farm, 0.6) == (2, 2)
+
+    @pytest.mark.asyncio
+    async def test_unknown_sliced_nozzle_wakes_the_least_worn_as_before(self, a1_farm):
+        assert await self._wake(a1_farm, None) == (1, 1)
+
+
+# --- Queue pass: end to end ---------------------------------------------------
+
+
+async def _add_any_a1(ctx, nozzle, **fields):
+    async with ctx.session_maker() as db:
+        lib = LibraryFile(
+            filename="part-a.gcode.3mf",
+            file_path="/library/part-a.gcode.3mf",
+            file_size=10,
+            file_type="gcode.3mf",
+            file_metadata={"nozzle_diameter": nozzle},
+        )
+        db.add(lib)
+        await db.flush()
+        values = {"status": "pending", "position": 1, "target_model": "A1", "library_file_id": lib.id}
+        values.update(fields)
+        item = PrintQueueItem(**values)
+        db.add(item)
+        await db.commit()
+        return item.id
+
+
+async def _load(db, item_id):
+    return (
+        await db.execute(
+            select(PrintQueueItem)
+            .where(PrintQueueItem.id == item_id)
+            .options(
+                selectinload(PrintQueueItem.library_file),
+                selectinload(PrintQueueItem.archive),
+                selectinload(PrintQueueItem.variants),
+            )
+        )
+    ).scalar_one()
+
+
+async def _get_item(ctx, item_id):
+    async with ctx.session_maker() as db:
+        return await _load(db, item_id)
+
+
+class TestQueuePassNozzle:
+    async def _pass(self, ctx, states):
+        scheduler = PrintScheduler()
+        launched = MagicMock()
+        dispatched = AsyncMock()
+        patches = [
+            patch("backend.app.services.print_scheduler.async_session", ctx.session_maker),
+            patch("backend.app.core.database.async_session", ctx.session_maker),
+            patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
+            patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
+            patch(
+                "backend.app.services.print_scheduler.ha_sensor_manager.blocked_printers",
+                AsyncMock(return_value={}),
+            ),
+            patch(
+                "backend.app.services.notification_service.notification_service.on_queue_job_waiting",
+                AsyncMock(),
+            ),
+            patch(
+                "backend.app.services.notification_service.notification_service.on_queue_job_assigned",
+                AsyncMock(),
+            ),
+            patch("backend.app.services.print_scheduler.compute_deficit_for_queue_item", AsyncMock(return_value=[])),
+            patch.object(scheduler, "_filament_short_on", AsyncMock(return_value=False)),
+            patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
+            patch.object(scheduler, "_check_auto_drying", AsyncMock()),
+            patch.object(scheduler, "_ensure_ams_mapping", AsyncMock(return_value=None)),
+            patch.object(scheduler, "_block_on_unmatched_filament", AsyncMock(return_value=False)),
+            patch.object(scheduler, "_unmatched_on", AsyncMock(return_value=[])),
+            patch.object(scheduler, "_launch_uploads", launched),
+            patch.object(scheduler, "_dispatch_one", dispatched),
+        ]
+        with ExitStack() as stack:
+            for p in patches:
+                stack.enter_context(p)
+            await scheduler.check_queue()
+        return launched, dispatched
+
+    @pytest.mark.asyncio
+    async def test_waits_with_the_nozzle_reason_when_no_printer_fits(self, a1_farm):
+        item_id = await _add_any_a1(a1_farm, 0.6)
+        launched, dispatched = await self._pass(a1_farm, {1: _state("0.4"), 2: _state("0.4")})
+
+        item = await _get_item(a1_farm, item_id)
+        assert item.status == "pending"
+        assert item.printer_id is None
+        assert item.waiting_reason == "No A1 has a 0.6mm nozzle: A1-1 (0.4mm), A1-2 (0.4mm)"
+        launched.assert_not_called()
+        dispatched.assert_not_called()
+
+    @pytest.mark.asyncio
+    async def test_goes_to_the_printer_whose_nozzle_fits(self, a1_farm):
+        item_id = await _add_any_a1(a1_farm, 0.6)
+        launched, _ = await self._pass(a1_farm, {1: _state("0.4"), 2: _state("0.6")})
+
+        launched.assert_called_once()
+        assert launched.call_args[0][0] == [item_id]
+        assert launched.call_args[0][1] == {item_id: 2}
+        assert (await _get_item(a1_farm, item_id)).printer_id == 2
+
+
+# --- Low-filament hold release -----------------------------------------------
+
+
+class TestShortHoldNozzle:
+    """A job held for low filament on A1-1 only moves to a printer whose nozzle fits.
+
+    Without the nozzle the move would pin it on a 0.4 mm A1, where the
+    dispatch guard (#1899) then fails it.
+    """
+
+    async def _release(self, ctx, states):
+        item_id = await _add_any_a1(ctx, 0.6, printer_id=1, manual_start=True, filament_short=True)
+        scheduler = PrintScheduler()
+
+        async def short_on(db, item, printer_id, *, require_known=False):
+            return printer_id == 1  # A1-2 has enough filament
+
+        with (
+            patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
+            patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
+            patch.object(scheduler, "_filament_short_on", AsyncMock(side_effect=short_on)),
+            patch.object(scheduler, "_unmatched_on", AsyncMock(return_value=[])),
+            patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
+        ):
+            async with ctx.session_maker() as db:
+                item = await _load(db, item_id)
+                moved = await scheduler._release_short_model_hold(db, item, set(), False, ALL_PRINTERS)
+                return moved, item.printer_id
+
+    @pytest.mark.asyncio
+    async def test_not_moved_to_a_printer_with_the_wrong_nozzle(self, a1_farm):
+        assert await self._release(a1_farm, {1: _state("0.6"), 2: _state("0.4")}) == (False, 1)
+
+    @pytest.mark.asyncio
+    async def test_moved_to_a_printer_whose_nozzle_fits(self, a1_farm):
+        assert await self._release(a1_farm, {1: _state("0.6"), 2: _state("0.6")}) == (True, 2)
+
+
+# --- Auto-drying: which printers an "Any model" job counts for ---------------
+
+
+class TestDryingPrinterIds:
+    """An "Any A1" job that no 0.4 mm A1 can print must not block or trigger drying there."""
+
+    async def _ids(self, ctx, nozzle, states):
+        item_id = await _add_any_a1(ctx, nozzle)
+        with patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)):
+            async with ctx.session_maker() as db:
+                item = await _load(db, item_id)
+                return await PrintScheduler()._model_job_printer_ids(db, item, ALL_PRINTERS, {})
+
+    @pytest.mark.asyncio
+    async def test_only_printers_whose_nozzle_fits_count(self, a1_farm):
+        assert await self._ids(a1_farm, 0.6, {1: _state("0.4"), 2: _state("0.6")}) == {2}
+
+    @pytest.mark.asyncio
+    async def test_unknown_sliced_nozzle_counts_every_printer(self, a1_farm):
+        assert await self._ids(a1_farm, None, {1: _state("0.4"), 2: _state("0.6")}) == {1, 2}
+
+
+# --- Chosen pick order (#2915) plus nozzle ------------------------------------
+
+
+class TestPickOrderNozzle:
+    """The nozzle check passes a printer over whatever order the setting picks in.
+
+    Farm from the #2915 tests: X1C-1 most worn (priority 2), X1C-2 priority 1,
+    X1C-3 fewest hours (no priority).
+    """
+
+    async def _pick(self, setting, nozzles, sliced_nozzle=0.6):
+        engine, ctx = await _farm(setting, **ORDER_PRINTERS)
+        try:
+            states = {pid: _state(d) for pid, d in nozzles.items()}
+            return await _find(ctx, PrintScheduler(), states, model="X1C", sliced_nozzle=sliced_nozzle)
+        finally:
+            await engine.dispose()
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("setting", "nozzles", "expected"),
+        [
+            ("priority", {1: "0.6", 2: "0.4", 3: "0.6"}, 1),  # priority 1 has the wrong nozzle
+            ("priority", {1: "0.4", 2: "0.4", 3: "0.6"}, 3),  # only the one without priority fits
+            ("most_hours", {1: "0.4", 2: "0.6", 3: "0.6"}, 2),  # the most worn has the wrong nozzle
+            ("fewest_hours", {1: "0.6", 2: "0.6", 3: "0.4"}, 2),  # the least worn has the wrong nozzle
+        ],
+    )
+    async def test_the_next_printer_in_the_chosen_order_whose_nozzle_fits(self, setting, nozzles, expected):
+        assert await self._pick(setting, nozzles) == (expected, None)
+
+    @pytest.mark.asyncio
+    async def test_the_reason_names_the_printers_in_the_chosen_order(self):
+        assert await self._pick("priority", {1: "0.4", 2: "0.4", 3: "0.4"}) == (
+            None,
+            "No X1C has a 0.6mm nozzle: X1C-2 (0.4mm), X1C-1 (0.4mm), X1C-3 (0.4mm)",
+        )
+
+    @pytest.mark.asyncio
+    async def test_the_wake_step_passes_over_the_first_in_order_with_the_wrong_nozzle(self):
+        """All off; X1C-2 (priority 1) last reported 0.4, so X1C-1 is woken instead."""
+        engine, ctx = await _farm("priority", **ORDER_PRINTERS)
+        scheduler = PrintScheduler()
+        plug = SimpleNamespace(id=1, auto_on=True, enabled=True, controls_printer_power=True)
+        states = {1: _state("0.6"), 2: _state("0.4"), 3: _state("0.6")}
+        try:
+            with (
+                patch(
+                    "backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=False)
+                ),
+                patch(
+                    "backend.app.services.print_scheduler.printer_manager.is_awaiting_plate_clear",
+                    MagicMock(return_value=False),
+                ),
+                patch("backend.app.services.print_scheduler.printer_manager.get_status", lambda pid: states.get(pid)),
+                patch.object(scheduler, "_cached_filament_shortfall", MagicMock(return_value=[])),
+                patch.object(scheduler, "_get_smart_plugs", AsyncMock(return_value=[plug])),
+                patch.object(scheduler, "_power_on_and_wait", AsyncMock(return_value=True)),
+            ):
+                async with ctx.session_maker() as db:
+                    woken = await scheduler._wake_printer_for_model(
+                        db,
+                        [
+                            _ModelCandidate(
+                                target_model="X1C",
+                                sliced_for=None,
+                                required_filament_types=None,
+                                filament_overrides=None,
+                                sliced_nozzle=0.6,
+                            )
+                        ],
+                        None,
+                        set(),
+                        {1, 2, 3},
+                        require_plate_clear=False,
+                    )
+        finally:
+            await engine.dispose()
+        assert woken == (1, 1)