Files
bambuddy/backend/tests/unit/test_spool_filament_preset_cascade.py
maziggy a7b563334e Configure a spool's filament preset and K profile per nozzle
A slicer preset is bound to a printer model: "Bambu PLA Basic @BBL X1C" is
not the same preset as "@BBL H2C", and Bambu names a nozzle size in it as
well. A spool carried exactly one, which was right until the same spool was
used on a second machine -- the AMS slot on the other one was then
configured with a preset that machine has no profile for. K profiles had
the matching gap from the other side: the tables have always been keyed per
hotend, but the picker could not express it.

spool_filament_preset and its Spoolman twin store the exceptions, keyed
(spool, printer_model, nozzle_diameter). Model rather than printer because
the preset is a property of the model -- "@BBL X1C" is the same preset on
every X1C, and asking per machine would mean picking the identical value
twice. K profiles stay on printer_id, because a K value is measured on one
physical hotend and two machines of the same model legitimately differ.
Resolution is exact (model, diameter) -> (model, "") -> the spool's own
preset, so a spool nobody has configured behaves exactly as it did before.
The form writes one row per nozzle size and never the "" row; that level is
kept for API clients wanting one value to cover a model.

Both halves cover every standard nozzle size rather than the size currently
fitted, because a spool is configured once and nozzles get swapped. The PA
Profile tab becomes a Printers tab: a model list beside a detail pane
holding a preset row per size and a K-profile grid of size by hotend. Each
model is offered only the presets that name it, through the same matcher
the Configure AMS Slot modal filters with, which moves out of that
component into utils/slicerPrinterMatch. Presets whose name identifies no
model -- most user-authored and OrcaSlicer ones -- stay offered everywhere,
as does whatever is already selected, so a saved override cannot vanish
from the control that shows it. Every preset carries an origin badge in the
wording and colours that modal already uses.

Every path that configures a slot now respects both: manual assign in
either inventory mode, RFID auto-assign, the Spoolman tag link, the re-fire
when a slot goes empty to loaded, the re-apply after a calibration-table
refresh, and the re-selection when a Filament Track Switch moves an AMS to
the other nozzle. Which nozzle a slot feeds, and how wide it is, was worked
out independently in seven of those places, each reading nozzles[0] for
every slot on the machine -- correct on a single-nozzle printer and on a
dual-nozzle printer with matching nozzles, wrong the moment two sizes are
fitted. That resolution is now services/slot_nozzle.

Which array entry belongs to which hotend is no longer inferred. Measured
on an H2D fitted with a 0.4 high flow on the left and a 0.6 on the right,
nozzles[0] reads the right hotend, so the array is indexed by extruder id
and the H2/X2 parser's convention is the one that holds. The legacy
parser's opposite convention never governs a real dual-nozzle machine:
every model in DUAL_NOZZLE_MODELS reports device.nozzle.info, and
left_nozzle_diameter appears in no log or wire capture. Two comments that
said otherwise were wrong and are fixed; amsHelpers' code was right all
along and only its comment lied.

Four defects surfaced while wiring it, all pre-existing except the last.
The picker identified a chosen calibration by cali_idx alone, and the
printer numbers its calibration table per nozzle -- on a dual-nozzle
machine the same index exists on both hotends meaning different things, so
saving could persist the other hotend's K value and diameter; SpoolBuddy's
write-tag page carried a verbatim copy and gets the same fix. RFID
auto-assign chose a K profile with no extruder test at all, so a spool
calibrated on both hotends had a coin toss decide which pressure-advance
value the slot got, on the path that runs unattended every time a Bambu
spool is loaded. The Spoolman tag-link path resolved no preset whatsoever,
configuring every linked slot with a generic material id and discarding a
preset set in inventory -- the same defect #1713 fixed on the assign path,
one function over. And an FTS inlet move re-selected K for nozzle 0 rather
than for the nozzle the AMS had just been moved to.

The last one is new here: a per-model override can be a cloud USER preset,
whose PFUS-prefixed id the slicer rejects, and passing it straight into
extrusion_cali_sel would silently lose the K-profile link. Reached the
printer only where such an override exists, which is why nothing in the
suite caught it. printer_safe_filament_id falls through to the spool's own
preset and then the tray's RFID value instead.

Reading a printer's calibration table asks for one nozzle size at a time.
H2-series firmware answers only the first one or two of a concurrent burst
of extrusion_cali_get and silently drops the rest, each dropped request
costing a five-second timeout before its retry: measured at 11 and 23
seconds on an H2C and an H2D for four parallel requests, against roughly
one second in series. An X1C answers all four at once, which is why this
only ever surfaced on dual-diameter printers. Printers themselves are read
in parallel -- separate machines are separate connections.

The Configure AMS Slot dialog opens on the spool's own configured values,
falling back to the slot's last manual configuration and then the tray's
RFID data. The spool form is wider for the two-pane layout, colour, weight,
cost and location move to their own tab in two columns, and a printer card
in expanded view lists every fitted nozzle size rather than the first entry
alone.
2026-08-27 13:03:15 +02:00

207 lines
8.8 KiB
Python

"""The per-printer-model preset cascade.
``Spool.slicer_filament`` holds one preset and is printer-agnostic by design.
That breaks as soon as a spool is used on two printer models, because a cloud
or Orca preset is bound to a model (``@BBL X1C``): the AMS slot on an H2C gets
configured with a preset that machine has no profile for.
``services.spool_filament_preset`` resolves, most specific first:
(model, diameter) -> (model, "") -> the spool's own slicer_filament
These pin the resolution order itself, including the two cases that are easy
to get backwards: a spool with no overrides must behave exactly as it did
before the feature existed, and a stored row whose preset is blank is the
user clearing the preset for that model, not a hole to fall through.
"""
from __future__ import annotations
import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from backend.app.models.spool import Spool
from backend.app.models.spool_filament_preset import SpoolFilamentPreset, SpoolmanFilamentPreset
from backend.app.services.spool_filament_preset import resolve_spool_preset, resolve_spoolman_preset
pytestmark = pytest.mark.asyncio
DEFAULT = ("GFSA00", "Bambu PLA Basic @BBL X1C")
async def _spool(engine) -> tuple[async_sessionmaker, int]:
maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async with maker() as db:
spool = Spool(
brand="Bambu",
material="PLA",
color_name="Charcoal",
slicer_filament=DEFAULT[0],
slicer_filament_name=DEFAULT[1],
)
db.add(spool)
await db.commit()
await db.refresh(spool)
return maker, spool.id
async def _resolve(maker, spool_id, model, diameter):
async with maker() as db:
return await resolve_spool_preset(
db,
spool_id=spool_id,
printer_model=model,
nozzle_diameter=diameter,
fallback_filament=DEFAULT[0],
fallback_name=DEFAULT[1],
)
async def _add(maker, spool_id, model, diameter, code, name):
async with maker() as db:
db.add(
SpoolFilamentPreset(
spool_id=spool_id,
printer_model=model,
nozzle_diameter=diameter,
slicer_filament=code,
slicer_filament_name=name,
)
)
await db.commit()
class TestNoOverrides:
"""Every spool in every existing install is this case."""
async def test_falls_back_to_the_spools_own_preset(self, test_engine):
maker, spool_id = await _spool(test_engine)
assert await _resolve(maker, spool_id, "H2C", "0.4") == DEFAULT
async def test_an_unknown_model_falls_back(self, test_engine):
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "X1C", "", "GFSA01", "PLA @X1C")
assert await _resolve(maker, spool_id, "P1S", "0.4") == DEFAULT
async def test_no_model_at_all_falls_back(self, test_engine):
"""A printer that has not reported its model yet cannot be more
specific than the spool itself -- it must not match some other row."""
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "X1C", "", "GFSA01", "PLA @X1C")
assert await _resolve(maker, spool_id, None, "0.4") == DEFAULT
assert await _resolve(maker, spool_id, "", "0.4") == DEFAULT
class TestModelDefault:
"""Diameter "" = any nozzle of the model.
The spool form writes one row per nozzle size and never this one, but the
API accepts it and it has to keep resolving -- these pin that level of the
cascade so a client using it does not break silently.
"""
async def test_model_row_wins_over_the_spool_default(self, test_engine):
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "H2C", "", "GFSA09", "Bambu PLA Basic @BBL H2C")
assert await _resolve(maker, spool_id, "H2C", "0.4") == ("GFSA09", "Bambu PLA Basic @BBL H2C")
async def test_it_applies_to_every_nozzle_of_that_model(self, test_engine):
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "H2C", "", "GFSA09", "Bambu PLA Basic @BBL H2C")
for diameter in ("0.2", "0.4", "0.6", "0.8", ""):
assert (await _resolve(maker, spool_id, "H2C", diameter))[0] == "GFSA09", diameter
async def test_other_models_are_untouched(self, test_engine):
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "H2C", "", "GFSA09", "Bambu PLA Basic @BBL H2C")
await _add(maker, spool_id, "A1 mini", "", "GFSA20", "Bambu PLA Basic @BBL A1M")
assert (await _resolve(maker, spool_id, "H2C", "0.4"))[0] == "GFSA09"
assert (await _resolve(maker, spool_id, "A1 mini", "0.4"))[0] == "GFSA20"
assert (await _resolve(maker, spool_id, "X1C", "0.4"))[0] == DEFAULT[0]
class TestPerDiameterException:
"""Why diameter is in the key at all: the preset lands on an AMS slot and
a slot feeds exactly one nozzle, so a machine with two diameters fitted
needs two answers for one model."""
async def test_exact_diameter_beats_the_model_default(self, test_engine):
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "A1 mini", "", "GFSA20", "Bambu PLA Basic @BBL A1M")
await _add(maker, spool_id, "A1 mini", "0.2", "GFSA21", "Bambu PLA Basic @BBL A1M 0.2 nozzle")
assert (await _resolve(maker, spool_id, "A1 mini", "0.2"))[0] == "GFSA21"
assert (await _resolve(maker, spool_id, "A1 mini", "0.4"))[0] == "GFSA20"
async def test_a_diameter_row_alone_still_leaves_other_nozzles_on_the_default(self, test_engine):
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "A1 mini", "0.2", "GFSA21", "Bambu PLA Basic @BBL A1M 0.2 nozzle")
assert (await _resolve(maker, spool_id, "A1 mini", "0.2"))[0] == "GFSA21"
assert (await _resolve(maker, spool_id, "A1 mini", "0.4"))[0] == DEFAULT[0]
async def test_the_two_hotends_of_one_machine_resolve_differently(self, test_engine):
"""The case that put diameter in the key: 0.4 on one hotend, 0.2 on
the other, one model, one spool."""
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "H2C", "0.4", "GFSA09", "Bambu PLA Basic @BBL H2C")
await _add(maker, spool_id, "H2C", "0.2", "GFSA10", "Bambu PLA Basic @BBL H2C 0.2 nozzle")
assert (await _resolve(maker, spool_id, "H2C", "0.4"))[0] == "GFSA09"
assert (await _resolve(maker, spool_id, "H2C", "0.2"))[0] == "GFSA10"
class TestClearedPreset:
async def test_a_blank_row_means_none_not_fall_through(self, test_engine):
"""The user picking the empty entry for a model is a decision. Falling
back to the spool's preset would silently reinstate what they cleared,
and it is the spool's preset that is wrong on that model."""
maker, spool_id = await _spool(test_engine)
await _add(maker, spool_id, "H2C", "", None, None)
assert await _resolve(maker, spool_id, "H2C", "0.4") == (None, None)
class TestSpoolmanFlavour:
"""Spoolman spools live in Spoolman; the override is Bambuddy's, keyed by
the remote id. Same cascade -- the two inventory modes must not drift."""
async def test_same_cascade(self, test_engine):
maker = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
async with maker() as db:
db.add(
SpoolmanFilamentPreset(
spoolman_spool_id=7,
printer_model="H2C",
nozzle_diameter="",
slicer_filament="GFSA09",
slicer_filament_name="Bambu PLA Basic @BBL H2C",
)
)
db.add(
SpoolmanFilamentPreset(
spoolman_spool_id=7,
printer_model="H2C",
nozzle_diameter="0.2",
slicer_filament="GFSA10",
slicer_filament_name="Bambu PLA Basic @BBL H2C 0.2 nozzle",
)
)
await db.commit()
async def resolve(model, diameter, spool_id=7):
async with maker() as db:
return await resolve_spoolman_preset(
db,
spoolman_spool_id=spool_id,
printer_model=model,
nozzle_diameter=diameter,
fallback_filament=DEFAULT[0],
fallback_name=DEFAULT[1],
)
assert (await resolve("H2C", "0.4"))[0] == "GFSA09"
assert (await resolve("H2C", "0.2"))[0] == "GFSA10"
assert (await resolve("X1C", "0.4"))[0] == DEFAULT[0]
# Another spool's rows must not leak into this one.
assert (await resolve("H2C", "0.4", spool_id=8))[0] == DEFAULT[0]