Explorar el Código

Spools with a custom cloud preset resolve from API keys too (#3519)

- An API-key assign (SpoolBuddy client) has no signed-in user, so a
  PFUS/PFCN preset was looked up with the shared cloud sign-in, empty
  with per-user sign-ins, and the slot got GFL99. The key's owner's
  sign-in is used now.
- New spool_assignment.assigned_by_user_id records who assigned a
  spool; the replay on insert uses that user's sign-in instead of none
  (login on only). Set null on user delete, on SQLite via sqlite_fk.
- A custom preset that still can't be looked up is logged.
- Tests for both paths, the login-off and deleted/deactivated cases,
  the warning, and the SQLite delete rule.
maziggy hace 1 semana
padre
commit
a9c169fa40

+ 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.
 - **"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
 ### Fixed
+- **A spool with a custom cloud preset gets it from a SpoolBuddy client too (#3519, reported by @pleasantone)** — With login on, each user signs in to Bambu Cloud separately. Assigning a spool from an API key, as a SpoolBuddy client does, had no signed-in user, so its custom preset (PFUS or PFCN) could not be looked up and the slot got Generic PLA, while the same assign from the web UI got the preset's own filament. Configuring a pre-assigned slot when the spool is inserted had the same problem, even for assignments made in the web UI. Both now use a user's sign-in: the API key's owner, and whoever made the assignment. A custom preset that still can't be looked up is now named in the log.
 - **Closing a camera view no longer leaves a CPU core at 100% (#3515, reported by @BrainDeLook)** — A viewer leaving while its stream was reading from the SQLite database could leave that connection's close waiting forever, on a bug in aiosqlite (omnilib/aiosqlite#403). Bambuddy then kept one CPU core fully busy, even with every viewer closed, and other pages such as Projects and Spool Inventory became very slow until a restart. Bambuddy now works around the aiosqlite bug, for every database connection, not only the camera's, and the camera stream's short reads (the chamber light settings and the periodic access check) finish before a leaving viewer ends the stream. PostgreSQL was not affected.
 - **Closing a camera view no longer leaves a CPU core at 100% (#3515, reported by @BrainDeLook)** — A viewer leaving while its stream was reading from the SQLite database could leave that connection's close waiting forever, on a bug in aiosqlite (omnilib/aiosqlite#403). Bambuddy then kept one CPU core fully busy, even with every viewer closed, and other pages such as Projects and Spool Inventory became very slow until a restart. Bambuddy now works around the aiosqlite bug, for every database connection, not only the camera's, and the camera stream's short reads (the chamber light settings and the periodic access check) finish before a leaving viewer ends the stream. PostgreSQL was not affected.
 - **The external spool keeps its filament after Configure Slot on an A1 or A1 mini (#3513, reported by @SaadShaya7)** — These printers report a change to the external spool with only what changed, often just the colour. Bambuddy stored that as the whole slot, so after a colour or preset change the spool showed as empty, with no filament type, until the printer's next full update. The check that the printer took the new preset also could not find the slot and reported it as not confirmed. A partial update now changes only what it carries, and the check confirms the new preset as soon as the printer reports it.
 - **The external spool keeps its filament after Configure Slot on an A1 or A1 mini (#3513, reported by @SaadShaya7)** — These printers report a change to the external spool with only what changed, often just the colour. Bambuddy stored that as the whole slot, so after a colour or preset change the spool showed as empty, with no filament type, until the printer's next full update. The check that the printer took the new preset also could not find the slot and reported it as not confirmed. A partial update now changes only what it carries, and the check confirms the new preset as soon as the printer reports it.
 - **A print that fails before its first layer no longer charges a whole spool (#3511)** — When a print failed or was cancelled before its first layer, Bambuddy worked out from the sliced file that no filament was used, but still let the AMS remaining % decide for that slot. The AMS can read 0% for a moment as the filament unloads, so a new spool at 100% was charged in full: 1000 g and its cost for a print stopped after five minutes, which then topped the Stats page as the heaviest and most expensive print. A slot whose spool the sliced file already accounts for is now left to that figure, so such a print charges nothing. Prints without a sliced file still use the AMS remaining %.
 - **A print that fails before its first layer no longer charges a whole spool (#3511)** — When a print failed or was cancelled before its first layer, Bambuddy worked out from the sliced file that no filament was used, but still let the AMS remaining % decide for that slot. The AMS can read 0% for a moment as the filament unloads, so a new spool at 100% was charged in full: 1000 g and its cost for a print stopped after five minutes, which then topped the Stats page as the heaviest and most expensive print. A slot whose spool the sliced file already accounts for is now left to that figure, so such a print charges nothing. Prints without a sliced file still use the AMS remaining %.

+ 29 - 1
backend/app/api/routes/inventory.py

@@ -13,6 +13,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.orm import selectinload
 from sqlalchemy.orm import selectinload
 
 
 from backend.app.core.auth import (
 from backend.app.core.auth import (
+    ApiKeyActor,
+    RequestActor,
     RequestPrinterScope,
     RequestPrinterScope,
     RequireAnyPermissionIfAuthEnabled,
     RequireAnyPermissionIfAuthEnabled,
     RequirePermissionIfAuthEnabled,
     RequirePermissionIfAuthEnabled,
@@ -127,6 +129,23 @@ def spool_response_loads():
     )
     )
 
 
 
 
+async def load_preset_lookup_user(db: AsyncSession, user_id: int | None) -> User | None:
+    """The user whose cloud sign-in resolves a spool's preset, by id (#3519).
+
+    For callers that have no signed-in user of their own: an API key (its
+    owner) and the replay on insert (whoever made the assignment). Without
+    one, a custom cloud preset (PFUS/PFCN) can't be looked up when each user
+    signs in to the cloud separately, and the slot gets a generic filament.
+    None for no id or a deactivated user. Groups are loaded because the
+    resolver asks the user for permissions.
+    """
+    if user_id is None:
+        return None
+    result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
+    user = result.scalar_one_or_none()
+    return user if user is not None and user.is_active else None
+
+
 # Bounded read size for the CSV import body so a chunked upload with no
 # Bounded read size for the CSV import body so a chunked upload with no
 # Content-Length can't stream past the cap into memory before we notice.
 # Content-Length can't stream past the cap into memory before we notice.
 _CSV_UPLOAD_CHUNK_BYTES = 64 * 1024
 _CSV_UPLOAD_CHUNK_BYTES = 64 * 1024
@@ -2427,12 +2446,20 @@ async def assign_spool(
     db: AsyncSession = Depends(get_db, scope="function"),
     db: AsyncSession = Depends(get_db, scope="function"),
     current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
     current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
     printer_scope: PrinterScope = RequestPrinterScope,
     printer_scope: PrinterScope = RequestPrinterScope,
+    actor: User | ApiKeyActor | None = RequestActor,
 ):
 ):
     """Assign a spool to an AMS slot and auto-configure via MQTT."""
     """Assign a spool to an AMS slot and auto-configure via MQTT."""
     from backend.app.services.printer_manager import printer_manager
     from backend.app.services.printer_manager import printer_manager
 
 
     printer_scope.ensure(data.printer_id)
     printer_scope.ensure(data.printer_id)
 
 
+    # An API key (a SpoolBuddy client) has no signed-in user, so its owner's
+    # cloud sign-in resolves a custom preset; without it the slot got Generic
+    # PLA where the web UI got the preset's own filament (#3519).
+    preset_user = current_user
+    if preset_user is None and isinstance(actor, ApiKeyActor):
+        preset_user = await load_preset_lookup_user(db, actor.id)
+
     # 1. Validate spool exists and is not archived
     # 1. Validate spool exists and is not archived
     result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == data.spool_id))
     result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == data.spool_id))
     spool = result.scalar_one_or_none()
     spool = result.scalar_one_or_none()
@@ -2555,6 +2582,7 @@ async def assign_spool(
                 tray_id=data.tray_id,
                 tray_id=data.tray_id,
                 fingerprint_color=fingerprint_color,
                 fingerprint_color=fingerprint_color,
                 fingerprint_type=fingerprint_type,
                 fingerprint_type=fingerprint_type,
+                assigned_by_user_id=preset_user.id if preset_user is not None else None,
             )
             )
             db.add(assignment)
             db.add(assignment)
             await spool_swaps.record_assignment(
             await spool_swaps.record_assignment(
@@ -2636,7 +2664,7 @@ async def assign_spool(
         try:
         try:
             configured = await apply_spool_to_slot_via_mqtt(
             configured = await apply_spool_to_slot_via_mqtt(
                 db=db,
                 db=db,
-                current_user=current_user,
+                current_user=preset_user,
                 spool=spool,
                 spool=spool,
                 printer_id=data.printer_id,
                 printer_id=data.printer_id,
                 ams_id=data.ams_id,
                 ams_id=data.ams_id,

+ 8 - 0
backend/app/core/database.py

@@ -6107,6 +6107,14 @@ async def _run_migrations(conn):
     # (``print_cost_estimate.fill_plate_estimates``).
     # (``print_cost_estimate.fill_plate_estimates``).
     await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN plate_estimates JSON")
     await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN plate_estimates JSON")
 
 
+    # Migration: who assigned a spool to a slot, whose cloud sign-in the replay
+    # on insert resolves a custom preset with (#3519). Nullable, no backfill:
+    # earlier assignments replay as before.
+    await _safe_execute(
+        conn,
+        "ALTER TABLE spool_assignment ADD COLUMN assigned_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL",
+    )
+
     await _backfill_archive_run_photos(conn)
     await _backfill_archive_run_photos(conn)
     await _migrate_h3c_queue_tray_ids(conn)
     await _migrate_h3c_queue_tray_ids(conn)
 
 

+ 3 - 0
backend/app/core/sqlite_fk.py

@@ -130,6 +130,9 @@ APPLIED: frozenset[tuple[str, str]] = frozenset(
         ("print_queue", "created_by_id"),
         ("print_queue", "created_by_id"),
         ("scheduled_dryings", "created_by_id"),
         ("scheduled_dryings", "created_by_id"),
         ("slicer_pipelines", "created_by"),
         ("slicer_pipelines", "created_by"),
+        # A new user given the id would have their cloud sign-in used for the
+        # slot's preset (#3519).
+        ("spool_assignment", "assigned_by_user_id"),
         ("sponsor_toast_state", "user_id"),
         ("sponsor_toast_state", "user_id"),
         ("user_email_preferences", "user_id"),
         ("user_email_preferences", "user_id"),
         ("user_groups", "user_id"),
         ("user_groups", "user_id"),

+ 11 - 1
backend/app/main.py

@@ -2995,11 +2995,21 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         try:
                         try:
                             from backend.app.api.routes.inventory import (
                             from backend.app.api.routes.inventory import (
                                 apply_spool_to_slot_via_mqtt,
                                 apply_spool_to_slot_via_mqtt,
+                                load_preset_lookup_user,
                             )
                             )
+                            from backend.app.core.auth import is_auth_enabled
+
+                            # Whoever made the assignment: their cloud sign-in
+                            # resolves a custom preset, which nobody's did here,
+                            # so the slot got Generic PLA on insert (#3519). With
+                            # login off the shared sign-in applies, as before.
+                            replay_user = None
+                            if assignment.assigned_by_user_id is not None and await is_auth_enabled(db):
+                                replay_user = await load_preset_lookup_user(db, assignment.assigned_by_user_id)
 
 
                             configured = await apply_spool_to_slot_via_mqtt(
                             configured = await apply_spool_to_slot_via_mqtt(
                                 db=db,
                                 db=db,
-                                current_user=None,
+                                current_user=replay_user,
                                 spool=assignment.spool,
                                 spool=assignment.spool,
                                 printer_id=printer_id,
                                 printer_id=printer_id,
                                 ams_id=assignment.ams_id,
                                 ams_id=assignment.ams_id,

+ 4 - 0
backend/app/models/spool_assignment.py

@@ -18,6 +18,10 @@ class SpoolAssignment(Base):
     tray_id: Mapped[int] = mapped_column(Integer)  # 0-3
     tray_id: Mapped[int] = mapped_column(Integer)  # 0-3
     fingerprint_color: Mapped[str | None] = mapped_column(String(8))  # tray_color snapshot
     fingerprint_color: Mapped[str | None] = mapped_column(String(8))  # tray_color snapshot
     fingerprint_type: Mapped[str | None] = mapped_column(String(50))  # tray_type snapshot
     fingerprint_type: Mapped[str | None] = mapped_column(String(50))  # tray_type snapshot
+    # Who assigned it from the inventory route: the signed-in user, or an API
+    # key's owner. The replay on insert resolves a custom cloud preset with this
+    # user's cloud sign-in; it has none of its own (#3519).
+    assigned_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
     created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
     created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
 
 
     spool: Mapped["Spool"] = relationship(back_populates="assignments")
     spool: Mapped["Spool"] = relationship(back_populates="assignments")

+ 18 - 9
backend/app/services/slicer_filament_resolver.py

@@ -24,11 +24,12 @@ Resolver outcomes:
 
 
 The resolver is async because the GFS / PFUS / PFCN branches need cloud
 The resolver is async because the GFS / PFUS / PFCN branches need cloud
 authentication and the local-preset branch reads ``LocalPreset`` from the
 authentication and the local-preset branch reads ``LocalPreset`` from the
-DB. Pass ``current_user=None`` to skip cloud auth (the on_ams_change
-replay path uses this); cloud-prefix presets then fall back to a static
-``normalize_slicer_filament`` parse, which is correct when the slot was
-already configured by an earlier authenticated assign and the printer's
-calibration table preserves the real filament_id.
+DB. ``current_user=None`` reads the shared cloud sign-in, the one used with
+login off. With login on that one is usually empty, so a caller without a
+user of its own (tag auto-assign, the Spoolman link) gets no cloud lookup, and
+cloud-prefix presets fall back to a static ``normalize_slicer_filament``
+parse. API-key assigns and the replay on insert pass the key's owner or the
+assigning user instead (#3519).
 """
 """
 
 
 from __future__ import annotations
 from __future__ import annotations
@@ -445,6 +446,15 @@ async def resolve_slicer_filament(
                     await cloud.close()
                     await cloud.close()
             elif cloud is not None:
             elif cloud is not None:
                 await cloud.close()
                 await cloud.close()
+            elif not base_sf.startswith("GFS"):
+                # A custom preset has no static form; without a sign-in the slot
+                # falls back to a generic filament, which nothing else reports
+                # (#3519). An official GFS one parses fine without the cloud.
+                logger.warning(
+                    "Slicer-filament resolve: custom preset %r not looked up, no Bambu Cloud sign-in "
+                    "for this caller; the slot may get a generic filament",
+                    sf,
+                )
         except Exception as e:
         except Exception as e:
             logger.warning("Slicer-filament resolve: cloud lookup failed for %r: %s", sf, e)
             logger.warning("Slicer-filament resolve: cloud lookup failed for %r: %s", sf, e)
 
 
@@ -522,10 +532,9 @@ async def resolve_slicer_filament(
     #      by the slicer as tray_info_idx (the printer's calibration table
     #      by the slicer as tray_info_idx (the printer's calibration table
     #      indexes by filament_id, and a PFUS isn't one). This normally gets
     #      indexes by filament_id, and a PFUS isn't one). This normally gets
     #      realigned to a P-prefix local id via the caller's printer_kp
     #      realigned to a P-prefix local id via the caller's printer_kp
-    #      lookup, but on the replay path in main.py.on_ams_change
-    #      current_user=None skips cloud auth and leaves the raw PFUS in
-    #      tray_info_idx — overwriting the correctly-configured slot from
-    #      the original assign.
+    #      lookup, but a caller with no cloud sign-in (see the module
+    #      docstring) gets no cloud lookup and would leave the raw PFUS in
+    #      tray_info_idx — overwriting a correctly-configured slot.
     #   3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's
     #   3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's
     #      "(Custom)" H2D variants, #1648) — same shape problem as PFUS.
     #      "(Custom)" H2D variants, #1648) — same shape problem as PFUS.
     #   4. Orca Cloud profile UUIDs, when the branch above could not reach the
     #   4. Orca Cloud profile UUIDs, when the branch above could not reach the

+ 315 - 0
backend/tests/integration/test_assign_preset_cloud_user_3519.py

@@ -0,0 +1,315 @@
+"""A custom cloud preset resolves the same way from an API key and on insert (#3519).
+
+With login on, each user signs in to Bambu Cloud separately and the shared
+sign-in is empty. An API key (a SpoolBuddy client) has no signed-in user, and
+the replay on insert has none either, so both looked the PFUS preset up with
+nobody's sign-in and sent Generic PLA (GFL99) where the web UI sent the
+preset's own filament. Both now use a user: the key's owner, and whoever made
+the assignment.
+"""
+
+import logging
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from backend.app.models.spool import Spool
+from backend.app.models.spool_assignment import SpoolAssignment
+
+PFUS = "PFUSdfae86e31579cb"
+
+
+def _status(ams_data):
+    status = MagicMock()
+    status.raw_data = {"ams": {"ams": ams_data}}
+    status.nozzles = [MagicMock(nozzle_diameter="0.4")]
+    status.ams_extruder_map = None
+    return status
+
+
+def _fake_cloud(seen: list):
+    """build_authenticated_cloud stand-in: records whose sign-in was asked for.
+
+    Only a user's own sign-in finds the preset, as on a per-user install
+    where the shared one is empty.
+    """
+    cloud = MagicMock()
+    cloud.is_authenticated = True
+    cloud.get_setting_detail = AsyncMock(return_value={"filament_id": "SUN20011", "name": "SUNLU PLA META"})
+    cloud.close = AsyncMock()
+
+    async def build(_db, user):
+        seen.append(user.id if user is not None else None)
+        return cloud if user is not None else None
+
+    return build
+
+
+@pytest.fixture
+async def auth_on(db_session: AsyncSession):
+    from backend.app.models.settings import Settings
+
+    db_session.add(Settings(key="auth_enabled", value="true"))
+    await db_session.commit()
+
+
+@pytest.fixture
+async def owner(db_session: AsyncSession):
+    from backend.app.models.user import User
+
+    user = User(username="spoolowner", password_hash="x", role="admin", is_active=True)
+    db_session.add(user)
+    await db_session.commit()
+    await db_session.refresh(user)
+    return user
+
+
+@pytest.fixture
+async def spool(db_session: AsyncSession):
+    row = Spool(
+        material="PLA",
+        subtype="Basic",
+        brand="SUNLU",
+        rgba="FF0000FF",
+        label_weight=1000,
+        weight_used=0,
+        slicer_filament=PFUS,
+    )
+    db_session.add(row)
+    await db_session.commit()
+    await db_session.refresh(row)
+    return row
+
+
+async def _owned_key(db_session: AsyncSession, user_id: int | None) -> str:
+    from backend.app.core.auth import generate_api_key
+    from backend.app.models.api_key import APIKey
+
+    full_key, key_hash, key_prefix = generate_api_key()
+    db_session.add(
+        APIKey(
+            name="espoolbuddy",
+            key_hash=key_hash,
+            key_prefix=key_prefix,
+            user_id=user_id,
+            can_manage_inventory=True,
+            can_read_status=True,
+            enabled=True,
+        )
+    )
+    await db_session.commit()
+    return full_key
+
+
+async def _assign_with_key(async_client: AsyncClient, key: str, printer_id: int, spool_id: int, seen: list):
+    mock_client = MagicMock()
+    mock_client.ams_set_filament_setting.return_value = True
+    mock_client.extrusion_cali_sel.return_value = True
+    status = _status([{"id": 0, "tray": [{"id": 0, "tray_info_idx": "", "tray_type": "PLA", "state": 11}]}])
+    with (
+        patch("backend.app.services.printer_manager.printer_manager") as mock_pm,
+        patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud(seen)),
+    ):
+        mock_pm.get_client.return_value = mock_client
+        mock_pm.get_status.return_value = status
+        response = await async_client.post(
+            "/api/v1/inventory/assignments",
+            json={"spool_id": spool_id, "printer_id": printer_id, "ams_id": 0, "tray_id": 0},
+            headers={"X-API-Key": key},
+        )
+    return response, mock_client
+
+
+async def _replay(printer_id: int, seen: list):
+    from backend.app.main import on_ams_change
+
+    ams_data = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF", "state": 11}]}]
+    mock_client = MagicMock()
+    mock_client.ams_set_filament_setting.return_value = True
+    mock_client.extrusion_cali_sel.return_value = True
+    status = _status(ams_data)
+    with (
+        patch("backend.app.main.printer_manager") as mock_pm_main,
+        patch("backend.app.services.printer_manager.printer_manager") as mock_pm_inv,
+        patch("backend.app.main.mqtt_relay") as mock_relay,
+        patch("backend.app.main.ws_manager") as mock_ws,
+        patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud(seen)),
+    ):
+        mock_pm_main.get_printer.return_value = MagicMock(name="H2C", serial_number="0948BB540200427")
+        mock_pm_main.get_status.return_value = status
+        mock_pm_main.get_client.return_value = mock_client
+        mock_pm_main.get_model.return_value = "H2C"
+        mock_pm_inv.get_client.return_value = mock_client
+        mock_pm_inv.get_status.return_value = status
+        mock_relay.on_ams_change = AsyncMock()
+        mock_ws.send_printer_status = AsyncMock()
+        mock_ws.broadcast = AsyncMock()
+        await on_ams_change(printer_id, ams_data)
+    return mock_client
+
+
+class TestApiKeyAssign:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_keys_owner_resolves_the_preset(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        printer = await printer_factory(name="H2C")
+        key = await _owned_key(db_session, owner.id)
+        seen: list = []
+
+        response, mock_client = await _assign_with_key(async_client, key, printer.id, spool.id, seen)
+
+        assert response.status_code == 200
+        assert seen == [owner.id]
+        kwargs = mock_client.ams_set_filament_setting.call_args.kwargs
+        assert kwargs["tray_info_idx"] == "SUN20011"
+        assert kwargs["setting_id"] == PFUS
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_assignment_remembers_the_owner(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        printer = await printer_factory(name="H2C")
+        key = await _owned_key(db_session, owner.id)
+
+        response, _ = await _assign_with_key(async_client, key, printer.id, spool.id, [])
+
+        assert response.status_code == 200
+        row = await db_session.get(SpoolAssignment, response.json()["id"])
+        await db_session.refresh(row)
+        assert row.assigned_by_user_id == owner.id
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_an_ownerless_key_still_assigns(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, spool
+    ):
+        """A key from before keys had owners has no sign-in to use: generic, as before."""
+        printer = await printer_factory(name="H2C")
+        key = await _owned_key(db_session, None)
+        seen: list = []
+
+        response, mock_client = await _assign_with_key(async_client, key, printer.id, spool.id, seen)
+
+        assert response.status_code == 200
+        assert seen == [None]
+        assert mock_client.ams_set_filament_setting.call_args.kwargs["tray_info_idx"] == "GFL99"
+
+
+class TestReplayOnInsert:
+    async def _pre_assigned(self, db_session: AsyncSession, printer_id: int, spool_id: int, user_id: int | None):
+        db_session.add(
+            SpoolAssignment(
+                spool_id=spool_id,
+                printer_id=printer_id,
+                ams_id=0,
+                tray_id=0,
+                fingerprint_color=None,
+                fingerprint_type=None,
+                assigned_by_user_id=user_id,
+            )
+        )
+        await db_session.commit()
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_assigning_user_resolves_the_preset(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        printer = await printer_factory(name="H2C")
+        await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
+        seen: list = []
+
+        mock_client = await _replay(printer.id, seen)
+
+        assert seen == [owner.id]
+        assert mock_client.ams_set_filament_setting.call_args.kwargs["tray_info_idx"] == "SUN20011"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_with_login_off_the_shared_sign_in_applies(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, owner, spool
+    ):
+        """A user id kept from when login was on doesn't pick a per-user sign-in."""
+        printer = await printer_factory(name="H2C")
+        await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
+        seen: list = []
+
+        await _replay(printer.id, seen)
+
+        assert seen == [None]
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_deactivated_user_is_not_used(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        owner.is_active = False
+        await db_session.commit()
+        printer = await printer_factory(name="H2C")
+        await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
+        seen: list = []
+
+        await _replay(printer.id, seen)
+
+        assert seen == [None]
+
+
+class TestUnresolvedPresetIsLogged:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_custom_preset_without_a_sign_in_warns(self, db_session: AsyncSession, caplog):
+        from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
+
+        with (
+            patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud([])),
+            caplog.at_level(logging.WARNING, logger="backend.app.services.slicer_filament_resolver"),
+        ):
+            await resolve_slicer_filament(
+                db=db_session, current_user=None, slicer_filament=PFUS, slicer_filament_name=None, material="PLA"
+            )
+
+        assert any("not looked up" in r.getMessage() and PFUS in r.getMessage() for r in caplog.records)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_an_official_preset_does_not(self, db_session: AsyncSession, caplog):
+        """A GFS id parses without the cloud, so nothing is lost."""
+        from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
+
+        with (
+            patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud([])),
+            caplog.at_level(logging.WARNING, logger="backend.app.services.slicer_filament_resolver"),
+        ):
+            await resolve_slicer_filament(
+                db=db_session, current_user=None, slicer_filament="GFSL05", slicer_filament_name=None, material="PLA"
+            )
+
+        assert not any("not looked up" in r.getMessage() for r in caplog.records)
+
+
+class TestDeletedUser:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_deleting_the_user_clears_the_assignment_s_user(
+        self, db_session: AsyncSession, printer_factory, owner, spool
+    ):
+        """Or the next user given the freed id would lend the slot their sign-in."""
+        from sqlalchemy import select
+
+        printer = await printer_factory(name="H2C")
+        db_session.add(
+            SpoolAssignment(spool_id=spool.id, printer_id=printer.id, ams_id=0, tray_id=0, assigned_by_user_id=owner.id)
+        )
+        await db_session.commit()
+
+        await db_session.delete(owner)
+        await db_session.commit()
+
+        db_session.expire_all()
+        row = (await db_session.execute(select(SpoolAssignment))).scalar_one()
+        assert row.assigned_by_user_id is None