فهرست منبع

Spool assignments survive a printer reconnecting mid-print (#3526)

- A tray reporting colour 00000000 with no type counts as blank, so
  the running-print, presence-bit and grace guards apply to it; a
  clear filament keeps its type and is unaffected
- The support package redacts virtual printer serials, whose A2L, P2S,
  H2 and X2D prefixes the generic serial pattern missed
- Tests for both, changelog entry
maziggy 1 هفته پیش
والد
کامیت
9817216253

+ 1 - 0
CHANGELOG.md

@@ -27,6 +27,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **"Any model" jobs go to the printer with the fewest print hours (#3480, sponsor vote Q4 2026)** — When several printers of a model can take a job, the queue used to pick the first one in its list, so on a farm the same printer got most of the work. It now picks the one with the fewest print hours (the Maintenance counter, including baseline hours entered there), so jobs and wear spread across the farm. Preferred colours still come first, and the queue powers on the least used printer too when it has to switch one on with an Auto Power On plug.
 
 ### Fixed
+- **Spool assignments survive a printer reconnecting mid-print (#3526, reported by @SaadShaya7)** — After a short network drop, the first report of a reconnecting printer can show a slot with no filament type and colour `00000000`. Bambuddy only recognised an empty colour as a blank slot, so it read this as a different spool and removed the inventory assignment, even during a print. All four assignments on an A1 mini's AMS lite and an A2L's external spool were lost that way and had to be made again. A slot reporting `00000000` with no type now counts as blank: during a print the assignment is kept as a possible runout, otherwise it is unlinked only if the slot stays blank for two minutes. A clear filament, which also reports `00000000` but with its type, is not affected. The support package also no longer contains a virtual printer's serial number: for the A2L, P2S, H2 series and X2D models it appeared in full in the certificate log lines.
 - **The slicer sidecars run as a non-root user again (#3524, reported by @cubic3d)** — Since 1.3.1, both the Bambu Studio and the OrcaSlicer sidecar failed to slice when the container runs as another user than root, as in a Kubernetes pod with `runAsNonRoot`: the log showed `bambu-studio: Permission denied`. The new slicer releases unpack with folders only root can open; the images now open them to every user, and the image build stops if any folder stays closed. Needs the updated sidecar images.
 - **The H2 series' and the H3C's exhaust fan is labelled Exhaust (#3521, reported by @Spegeli)** — The printer card called fan 3 "Chamber Fan" on the H2D, H2D Pro, H2C, H2S and H3C. On these printers it is the exhaust fan in the back wall, which Bambu Studio names "Exhaust", as on the P2S and X2D. Only the X1 series and P1S call it the chamber fan. The badge is still always shown on these printers, since the fan is built in, and the confirmation after setting the fan names it the exhaust fan too.
 - **Spools keep their ids when the inventory moves by CSV (#3520, reported by @hurr1k4ne)** — The CSV export had no id column, so importing it on another instance numbered the spools anew, in the order of the file, and every printed label, whose QR code carries the spool's id, found the wrong spool or none. The export now writes each spool's id, and the import keeps it when that instance has never used it, which on a fresh instance is every id. An id already used there, also by a deleted spool, or named twice in the file gets a new one, and the preview says how many. The preview shows the id each spool keeps. A CSV without the column imports as before.

+ 15 - 4
backend/app/main.py

@@ -2800,6 +2800,18 @@ def _slot_feeds_print(printer_id: int, ams_id: int, tray_id: int) -> bool:
     return any(slot.has_filament and slot.holds(ams_id, tray_id) for slot in slots.values())
 
 
+def _tray_reports_no_filament(color: str, tray_type: str) -> bool:
+    """Does this tray report carry no filament data at all?
+
+    No type, and a colour that is either empty or ``00000000``: firmware sends
+    both for a blank slot, and ``00000000`` is what Bambuddy's own slot reset
+    writes. A reconnect mid-print brought it in that form and got past every
+    guard that only knew the empty string (#3526). A clear spool also reports
+    ``00000000``, but always with a type, so it is not blank.
+    """
+    return not tray_type.strip() and color.strip().upper() in ("", "00000000")
+
+
 async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
     """Unlink built-in inventory assignments whose slot no longer holds their spool.
 
@@ -3054,7 +3066,7 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         # firmware clears colour and type when it unloads a spool
                         # it just emptied. Unlinking here would erase the record
                         # of which spool fed the print so far.
-                        if printing_now and not cur_color.strip() and not cur_type.strip():
+                        if printing_now and _tray_reports_no_filament(cur_color, cur_type):
                             logger.info(
                                 "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
                                 "(runout?)",
@@ -3078,8 +3090,7 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         # rather than cancelling it (#3186).
                         if (
                             spool_present(current_tray) is True
-                            and not cur_color.strip()
-                            and not cur_type.strip()
+                            and _tray_reports_no_filament(cur_color, cur_type)
                             and not slot_unlink_grace.is_held(
                                 printer_id,
                                 ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
@@ -3098,7 +3109,7 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         # unit's bits, colour and type for a moment and lost
                         # four saved assignments that way (#3186); unlink only
                         # if the slot is still blank after the grace period.
-                        if not cur_color.strip() and not cur_type.strip():
+                        if _tray_reports_no_filament(cur_color, cur_type):
                             hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
                             if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
                                 held.add(hold_key)

+ 16 - 2
backend/app/services/log_reader.py

@@ -25,6 +25,7 @@ from backend.app.core.logging_filters import (
 from backend.app.models.printer import Printer
 from backend.app.models.settings import Settings
 from backend.app.models.user import User
+from backend.app.models.virtual_printer import VirtualPrinter
 from backend.app.utils.printer_models import PRINTER_MODEL_ID_MAP, PRINTER_MODEL_MAP
 
 logger = logging.getLogger(__name__)
@@ -266,8 +267,8 @@ def _is_model_name(name: str, model: str | None) -> bool:
 async def collect_sensitive_strings(db: AsyncSession) -> dict[str, str]:
     """Collect known sensitive values from the database for log redaction.
 
-    Covers printer names, serial numbers, IP addresses, access codes, auth
-    usernames, and the Bambu Cloud email. Pass the result to
+    Covers printer names, serial numbers (virtual printers' too), IP
+    addresses, access codes, auth usernames, and the Bambu Cloud email. Pass the result to
     :func:`sanitize_log_content`.
     """
     sensitive_strings: dict[str, str] = {}
@@ -286,6 +287,19 @@ async def collect_sensitive_strings(db: AsyncSession) -> dict[str, str]:
         if access_code:
             sensitive_strings[access_code] = "[ACCESS_CODE]"
 
+    # Virtual printer serials. Stored only as a suffix: the serial is the
+    # model's prefix plus it, and many prefixes (A2L, P2S, H2D, X2D) are past
+    # what the serial pattern below matches, so the certificate log lines
+    # carried them whole (#3526). Every prefix, so a log written before the
+    # VP's model was changed is covered as well.
+    from backend.app.services.virtual_printer.manager import MODEL_SERIAL_PREFIXES, _get_serial_for_model
+
+    result = await db.execute(select(VirtualPrinter.serial_suffix))
+    for (suffix,) in result.all():
+        if suffix:
+            for model in (*MODEL_SERIAL_PREFIXES, ""):
+                sensitive_strings[_get_serial_for_model(model, suffix)] = "[SERIAL]"
+
     # Auth usernames
     result = await db.execute(select(User.username))
     for (username,) in result.all():

+ 137 - 0
backend/tests/integration/test_inventory_assign.py

@@ -2568,3 +2568,140 @@ class TestSpoolmanSlotAssignmentDuringRunout:
 
         db_session.expunge_all()
         assert await db_session.get(SpoolmanSlotAssignment, row_id) is None
+
+
+class TestAutoUnlinkZeroColourIsBlank:
+    """#3526: a blank tray can arrive as colour ``00000000`` rather than "".
+
+    Four printers lost MQTT for a minute or two; on reconnect an A1 mini's AMS
+    lite and an A2L's external spool first reported ``00000000`` with no type,
+    mid-print, and four assignments were deleted as fingerprint mismatches. The
+    runout guard, the presence-bit guard and the grace hold all only knew an
+    empty colour as blank.
+    """
+
+    BLANK = {"tray_type": "", "tray_color": "00000000"}
+
+    @staticmethod
+    async def _assignment(db_session, printer, spool, ams_id=0, tray_id=1):
+        from backend.app.models.spool_assignment import SpoolAssignment
+
+        assignment = SpoolAssignment(
+            spool_id=spool.id,
+            printer_id=printer.id,
+            ams_id=ams_id,
+            tray_id=tray_id,
+            fingerprint_color="91202BFF",
+            fingerprint_type="PLA",
+        )
+        db_session.add(assignment)
+        await db_session.commit()
+        return assignment.id
+
+    @staticmethod
+    async def _exists(db_session, assignment_id):
+        from backend.app.models.spool_assignment import SpoolAssignment
+
+        db_session.expunge_all()
+        return await db_session.get(SpoolAssignment, assignment_id) is not None
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_mid_print_keeps_the_assignment(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        """Held past the grace period too: during a print it is a runout, never
+        a removal, however long it lasts."""
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, **self.BLANK, "state": 3}]}]
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="PAUSE"))
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="PAUSE"))
+
+        assert await self._exists(db_session, assignment_id), "a blank report mid-print is a runout, not a swap"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_on_the_external_spool_mid_print_keeps_the_assignment(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A2L")
+        spool = await spool_factory(material="PLA+", rgba="E1E4E5FF")
+        assignment_id = await self._assignment(db_session, printer, spool, ams_id=255, tray_id=0)
+
+        status = _make_mock_status(ams_data=[], vt_tray=[{"id": "254", **self.BLANK}])
+        status.state = "RUNNING"
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, [], status)
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, [], status)
+
+        assert await self._exists(db_session, assignment_id)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_from_an_occupied_slot_keeps_the_assignment(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, "exists": True, **self.BLANK, "state": 3}]}]
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+
+        assert await self._exists(db_session, assignment_id)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_while_idle_is_held_for_the_grace_period(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, **self.BLANK, "state": 3}]}]
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+            assert await self._exists(db_session, assignment_id), "one blank push is not a removal"
+
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+
+        assert not await self._exists(db_session, assignment_id), "a slot that stays blank is still unlinked"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_clear_spool_reporting_zero_colour_is_not_blank(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        """A clear filament reports ``00000000`` too, but with its type: a clear
+        PETG in place of the assigned PLA is a swap, even mid-print."""
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, "tray_type": "PETG", "tray_color": "00000000", "state": 11}]}]
+        await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="RUNNING"))
+
+        assert not await self._exists(db_session, assignment_id)

+ 41 - 0
backend/tests/unit/test_support_vp_serial_redaction_3526.py

@@ -0,0 +1,41 @@
+"""A virtual printer's serial is redacted in the support package (#3526).
+
+Its serial is not stored whole -- it is the model's prefix plus the VP's
+``serial_suffix`` -- and the A2L's ``26A19A`` and the other newer prefixes are
+past what the generic serial pattern matches, so the certificate log lines
+carried it unredacted.
+"""
+
+import pytest
+
+from backend.app.models.virtual_printer import VirtualPrinter
+from backend.app.services.log_reader import collect_sensitive_strings, sanitize_log_content
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("model", ["N9", "N7", "O1D", "N6", "O1C2", None])
+async def test_the_virtual_printer_serial_is_redacted(db_session, model):
+    from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL, _get_serial_for_model
+
+    db_session.add(VirtualPrinter(name="Shop VP", model=model, serial_suffix="491800007"))
+    await db_session.commit()
+    serial = _get_serial_for_model(model or DEFAULT_VIRTUAL_PRINTER_MODEL, "491800007")
+
+    sensitive = await collect_sensitive_strings(db_session)
+    line = f"Generating certificates for virtual printer (serial: {serial})... Printer: CN={serial}"
+    assert sanitize_log_content(line, sensitive) == (
+        "Generating certificates for virtual printer (serial: [SERIAL])... Printer: CN=[SERIAL]"
+    )
+
+
+@pytest.mark.asyncio
+async def test_the_serial_from_before_a_model_change_is_redacted(db_session):
+    """The log may predate the VP's current model."""
+    from backend.app.services.virtual_printer.manager import _get_serial_for_model
+
+    db_session.add(VirtualPrinter(name="Shop VP", model="N9", serial_suffix="491800007"))
+    await db_session.commit()
+
+    sensitive = await collect_sensitive_strings(db_session)
+    old_serial = _get_serial_for_model("N7", "491800007")
+    assert sanitize_log_content(f"CN={old_serial}", sensitive) == "CN=[SERIAL]"