test_library_slice_api.py 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496
  1. """Integration tests for the slice-via-API flow.
  2. Routes under test:
  3. - POST /library/files/{id}/slice (returns 202 + job_id; bg task does the work)
  4. - POST /archives/{id}/slice (same shape; result lands in archives table)
  5. - GET /slice-jobs/{id} (poll for terminal state)
  6. The synchronous validation paths (404 missing source, 400 wrong file type)
  7. are tested directly. The bg-task paths poll until the job finishes and then
  8. assert on the captured state.
  9. """
  10. from __future__ import annotations
  11. import asyncio
  12. import io
  13. import json
  14. import zipfile
  15. from collections.abc import Callable
  16. import httpx
  17. import pytest
  18. from httpx import AsyncClient
  19. from backend.app.api.routes.library import _slicer_rejection_message
  20. from backend.app.core.config import settings as app_settings
  21. from backend.app.models.library import LibraryFile
  22. from backend.app.models.local_preset import LocalPreset
  23. from backend.app.models.settings import Settings as SettingsModel
  24. from backend.app.services import slicer_api as slicer_api_module
  25. from backend.app.services.slice_dispatch import slice_dispatch
  26. # ---------------------------------------------------------------------------
  27. # Helpers
  28. # ---------------------------------------------------------------------------
  29. def _make_3mf_with_settings(settings_payload: dict | None = None) -> bytes:
  30. """Build a tiny in-memory 3MF zip with all the embedded-config files
  31. that real-world Bambu Studio / OrcaSlicer 3MFs ship with.
  32. The strip-before-forwarding helper has to remove ALL of these (not
  33. just `project_settings.config`) — leftover entries reference printer
  34. / filament IDs from the original slice and trip the CLI's input
  35. validation when a different `--load-settings` triplet is supplied.
  36. """
  37. buf = io.BytesIO()
  38. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  39. zf.writestr("3D/3dmodel.model", "<model/>")
  40. zf.writestr(
  41. "Metadata/project_settings.config",
  42. json.dumps(settings_payload or {"prime_tower_brim_width": "-1"}),
  43. )
  44. zf.writestr("Metadata/model_settings.config", "<config><object id='1'/></config>")
  45. zf.writestr(
  46. "Metadata/slice_info.config",
  47. "<config><plate><metadata key='filament' value='GFL00'/></plate></config>",
  48. )
  49. zf.writestr("Metadata/cut_information.xml", "<cut><part id='1'/></cut>")
  50. return buf.getvalue()
  51. def _install_mock_sidecar(handler: Callable[[httpx.Request], httpx.Response]) -> httpx.AsyncClient:
  52. """Pin a MockTransport-backed httpx client onto the slicer_api singleton
  53. so per-request `SlicerApiService` instances reuse it instead of opening
  54. a real connection."""
  55. client = httpx.AsyncClient(transport=httpx.MockTransport(handler), timeout=10.0)
  56. slicer_api_module.set_shared_http_client(client)
  57. return client
  58. def _is_slice_post(request: httpx.Request) -> bool:
  59. """True for the slice call itself, false for the progress polls beside it.
  60. Since #2730 a slice is supervised by a 1 Hz poll of
  61. ``GET /slice/progress/{id}``, which shares this mock transport. Tests that
  62. count *slice attempts* — primary vs embedded-settings fallback — have to
  63. exclude those, or the count becomes a measure of how long the test took.
  64. """
  65. return request.method == "POST" and request.url.path.endswith("/slice")
  66. async def _wait_for_job(client: AsyncClient, job_id: int, timeout: float = 5.0) -> dict:
  67. """Poll `/api/v1/slice-jobs/{id}` until the job hits a terminal state.
  68. The dispatcher runs work as an asyncio task on the same event loop, so
  69. poll-with-sleep here is enough — a few yields and the task finishes.
  70. """
  71. deadline = asyncio.get_event_loop().time() + timeout
  72. while asyncio.get_event_loop().time() < deadline:
  73. r = await client.get(f"/api/v1/slice-jobs/{job_id}")
  74. if r.status_code != 200:
  75. raise AssertionError(f"slice-jobs poll failed: {r.status_code} {r.text}")
  76. body = r.json()
  77. if body["status"] in ("completed", "failed"):
  78. return body
  79. await asyncio.sleep(0.05)
  80. raise AssertionError(f"slice job {job_id} did not finish in {timeout}s")
  81. # ---------------------------------------------------------------------------
  82. # Fixtures
  83. # ---------------------------------------------------------------------------
  84. @pytest.fixture
  85. async def slice_test_setup(db_session, tmp_path, monkeypatch):
  86. """Source LibraryFile + 3 LocalPresets + preferred_slicer=orcaslicer.
  87. ``base_dir`` is patched via ``monkeypatch`` rather than assigned and
  88. restored by hand. ``app_settings`` is a process-wide singleton, and the
  89. hand-rolled version only restored after the ``yield`` — so anything raising
  90. during setup (a commit, a refresh) left ``base_dir`` pointing at a
  91. ``tmp_path`` that pytest then deleted, and every later test in that xdist
  92. worker which reads it failed. That was the cause of intermittent failures
  93. in ``TestLibraryPathHelpers`` and ``TestArchivePlatesDesignOverrides``,
  94. which share nothing with this module but land in the same worker.
  95. """
  96. storage_dir = tmp_path / "library" / "files"
  97. storage_dir.mkdir(parents=True, exist_ok=True)
  98. src_path = storage_dir / "Cube.stl"
  99. src_path.write_bytes(b"solid Cube\nendsolid\n")
  100. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  101. src_file = LibraryFile(
  102. filename="Cube.stl",
  103. file_path=str(src_path.relative_to(tmp_path)),
  104. file_type="stl",
  105. file_size=src_path.stat().st_size,
  106. )
  107. db_session.add(src_file)
  108. presets = {}
  109. for kind in ("printer", "process", "filament"):
  110. p = LocalPreset(
  111. name=f"Test {kind}",
  112. preset_type=kind,
  113. source="orcaslicer",
  114. setting=json.dumps({"name": f"Test {kind}", "type": kind}),
  115. )
  116. db_session.add(p)
  117. presets[kind] = p
  118. db_session.add(SettingsModel(key="preferred_slicer", value="orcaslicer"))
  119. await db_session.commit()
  120. for p in presets.values():
  121. await db_session.refresh(p)
  122. await db_session.refresh(src_file)
  123. yield {
  124. "src_file_id": src_file.id,
  125. "printer_id": presets["printer"].id,
  126. "process_id": presets["process"].id,
  127. "filament_id": presets["filament"].id,
  128. "tmp_path": tmp_path,
  129. }
  130. slicer_api_module.set_shared_http_client(None)
  131. # ---------------------------------------------------------------------------
  132. # POST /library/files/{id}/slice — synchronous validation paths
  133. # ---------------------------------------------------------------------------
  134. class TestSliceValidation:
  135. @pytest.mark.asyncio
  136. @pytest.mark.integration
  137. async def test_returns_404_when_source_missing(self, async_client: AsyncClient, slice_test_setup):
  138. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  139. response = await async_client.post(
  140. "/api/v1/library/files/999999/slice",
  141. json={
  142. "printer_preset_id": slice_test_setup["printer_id"],
  143. "process_preset_id": slice_test_setup["process_id"],
  144. "filament_preset_id": slice_test_setup["filament_id"],
  145. },
  146. )
  147. assert response.status_code == 404
  148. @pytest.mark.asyncio
  149. @pytest.mark.integration
  150. async def test_returns_400_for_wrong_file_type(self, async_client: AsyncClient, db_session, slice_test_setup):
  151. gcode_path = slice_test_setup["tmp_path"] / "library" / "files" / "out.gcode"
  152. gcode_path.write_bytes(b"; gcode\n")
  153. gfile = LibraryFile(
  154. filename="out.gcode",
  155. file_path=str(gcode_path.relative_to(slice_test_setup["tmp_path"])),
  156. file_type="gcode",
  157. file_size=10,
  158. )
  159. db_session.add(gfile)
  160. await db_session.commit()
  161. await db_session.refresh(gfile)
  162. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  163. response = await async_client.post(
  164. f"/api/v1/library/files/{gfile.id}/slice",
  165. json={
  166. "printer_preset_id": slice_test_setup["printer_id"],
  167. "process_preset_id": slice_test_setup["process_id"],
  168. "filament_preset_id": slice_test_setup["filament_id"],
  169. },
  170. )
  171. assert response.status_code == 400
  172. assert "STL or 3MF" in response.json()["detail"]
  173. @pytest.mark.asyncio
  174. @pytest.mark.integration
  175. async def test_step_source_is_refused_with_an_explanation(
  176. self, async_client: AsyncClient, db_session, slice_test_setup
  177. ):
  178. """STEP was accepted here and then failed at the sidecar.
  179. Neither slicer's CLI can load STEP -- it answers "Unknown file format"
  180. and exits 250 -- so the job was read, converted and uploaded only to
  181. come back as "The input model file to the slicer can not be parsed",
  182. which reads as a corrupt model rather than an unsupported format.
  183. """
  184. from backend.app.models.library import LibraryFile
  185. step_path = slice_test_setup["tmp_path"] / "part.step"
  186. step_path.write_bytes(b"ISO-10303-21;\n")
  187. sfile = LibraryFile(
  188. filename="part.step",
  189. file_path=str(step_path.relative_to(slice_test_setup["tmp_path"])),
  190. file_type="step",
  191. file_size=14,
  192. )
  193. db_session.add(sfile)
  194. await db_session.commit()
  195. await db_session.refresh(sfile)
  196. response = await async_client.post(
  197. f"/api/v1/library/files/{sfile.id}/slice",
  198. json={
  199. "printer_preset_id": slice_test_setup["printer_id"],
  200. "process_preset_id": slice_test_setup["process_id"],
  201. "filament_preset_id": slice_test_setup["filament_id"],
  202. },
  203. )
  204. assert response.status_code == 400
  205. detail = response.json()["detail"]
  206. assert "STEP" in detail
  207. # Naming the way out matters more than the refusal.
  208. assert "export" in detail.lower()
  209. # ---------------------------------------------------------------------------
  210. # POST /library/files/{id}/slice — async dispatch + bg job
  211. # ---------------------------------------------------------------------------
  212. class TestSliceLibraryFile:
  213. @pytest.mark.asyncio
  214. @pytest.mark.integration
  215. async def test_happy_path_returns_202_then_job_completes_with_library_file(
  216. self, async_client: AsyncClient, slice_test_setup
  217. ):
  218. captured: dict = {}
  219. def handler(request: httpx.Request) -> httpx.Response:
  220. captured["url"] = str(request.url)
  221. return httpx.Response(
  222. status_code=200,
  223. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  224. headers={
  225. "x-print-time-seconds": "656",
  226. "x-filament-used-g": "0.94",
  227. "x-filament-used-mm": "302.5",
  228. },
  229. )
  230. _install_mock_sidecar(handler)
  231. response = await async_client.post(
  232. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  233. json={
  234. "printer_preset_id": slice_test_setup["printer_id"],
  235. "process_preset_id": slice_test_setup["process_id"],
  236. "filament_preset_id": slice_test_setup["filament_id"],
  237. },
  238. )
  239. assert response.status_code == 202, response.text
  240. body = response.json()
  241. assert body["status"] == "pending"
  242. assert body["status_url"].startswith("/api/v1/slice-jobs/")
  243. final = await _wait_for_job(async_client, body["job_id"])
  244. assert final["status"] == "completed", final
  245. assert final["result"]["library_file_id"] != slice_test_setup["src_file_id"]
  246. assert final["result"]["print_time_seconds"] == 656
  247. assert captured["url"].endswith("/slice")
  248. @pytest.mark.asyncio
  249. @pytest.mark.integration
  250. async def test_bed_type_override_patches_process_profile(self, async_client: AsyncClient, slice_test_setup):
  251. """#1337: when SliceRequest.bed_type is set, the process JSON sent to
  252. the sidecar must carry curr_bed_type with that exact value. Without
  253. the patch, slicing high-temp filaments on a "Cool Plate" process
  254. preset fails inside the slicer CLI with "does not support filament 1"
  255. and the user has no way to switch plates from the SliceModal."""
  256. captured: dict = {}
  257. def handler(request: httpx.Request) -> httpx.Response:
  258. captured["body"] = bytes(request.content)
  259. return httpx.Response(
  260. status_code=200,
  261. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  262. headers={
  263. "x-print-time-seconds": "10",
  264. "x-filament-used-g": "0.1",
  265. "x-filament-used-mm": "1.0",
  266. },
  267. )
  268. _install_mock_sidecar(handler)
  269. response = await async_client.post(
  270. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  271. json={
  272. "printer_preset_id": slice_test_setup["printer_id"],
  273. "process_preset_id": slice_test_setup["process_id"],
  274. "filament_preset_id": slice_test_setup["filament_id"],
  275. "bed_type": "Textured PEI Plate",
  276. },
  277. )
  278. assert response.status_code == 202
  279. final = await _wait_for_job(async_client, response.json()["job_id"])
  280. assert final["status"] == "completed", final
  281. # The presetProfile part of the multipart upload now carries the
  282. # override. Searching the raw body avoids parsing the multipart by
  283. # hand — the substring is unique enough since we control the JSON
  284. # being patched.
  285. assert b'"curr_bed_type": "Textured PEI Plate"' in captured["body"], (
  286. "bed_type override must appear in the process JSON sent to the sidecar"
  287. )
  288. @pytest.mark.asyncio
  289. @pytest.mark.integration
  290. async def test_bed_type_omitted_leaves_process_profile_untouched(self, async_client: AsyncClient, slice_test_setup):
  291. """Companion to the override test: the patch must NOT fire when the
  292. client omits bed_type, so the process preset's own curr_bed_type
  293. (or absence thereof) is forwarded to the sidecar unchanged."""
  294. captured: dict = {}
  295. def handler(request: httpx.Request) -> httpx.Response:
  296. captured["body"] = bytes(request.content)
  297. return httpx.Response(
  298. status_code=200,
  299. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  300. headers={
  301. "x-print-time-seconds": "10",
  302. "x-filament-used-g": "0.1",
  303. "x-filament-used-mm": "1.0",
  304. },
  305. )
  306. _install_mock_sidecar(handler)
  307. response = await async_client.post(
  308. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  309. json={
  310. "printer_preset_id": slice_test_setup["printer_id"],
  311. "process_preset_id": slice_test_setup["process_id"],
  312. "filament_preset_id": slice_test_setup["filament_id"],
  313. },
  314. )
  315. assert response.status_code == 202
  316. final = await _wait_for_job(async_client, response.json()["job_id"])
  317. assert final["status"] == "completed", final
  318. assert b"curr_bed_type" not in captured["body"], (
  319. "bed_type must stay out of the process JSON when no override is set"
  320. )
  321. @pytest.mark.asyncio
  322. @pytest.mark.integration
  323. async def test_auto_orient_and_arrange_reach_the_sidecar(self, async_client: AsyncClient, slice_test_setup):
  324. """#2548: the two layout passes are per-slice options, so ticking
  325. them in the SliceModal has to come out the other end as the
  326. sidecar's ``orient`` / ``arrange`` form fields. Before this the
  327. flags existed on the wire but only #1493's cross-class detector
  328. could set arrange, and nothing at all could set orient."""
  329. captured: dict = {}
  330. def handler(request: httpx.Request) -> httpx.Response:
  331. captured["body"] = bytes(request.content)
  332. return httpx.Response(
  333. status_code=200,
  334. content=_make_3mf_with_settings(),
  335. headers={
  336. "x-print-time-seconds": "10",
  337. "x-filament-used-g": "0.1",
  338. "x-filament-used-mm": "1.0",
  339. },
  340. )
  341. _install_mock_sidecar(handler)
  342. response = await async_client.post(
  343. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  344. json={
  345. "printer_preset_id": slice_test_setup["printer_id"],
  346. "process_preset_id": slice_test_setup["process_id"],
  347. "filament_preset_id": slice_test_setup["filament_id"],
  348. "auto_orient": True,
  349. "auto_arrange": True,
  350. },
  351. )
  352. assert response.status_code == 202
  353. final = await _wait_for_job(async_client, response.json()["job_id"])
  354. assert final["status"] == "completed", final
  355. assert b'name="orient"' in captured["body"]
  356. assert b'name="arrange"' in captured["body"]
  357. @pytest.mark.asyncio
  358. @pytest.mark.integration
  359. async def test_layout_flags_absent_by_default(self, async_client: AsyncClient, slice_test_setup):
  360. """Companion to the above. Both default to off, and off is expressed
  361. by omitting the field — the sidecar reads any present value as
  362. truthy, so a "false" on the wire would auto-arrange every slice."""
  363. captured: dict = {}
  364. def handler(request: httpx.Request) -> httpx.Response:
  365. captured["body"] = bytes(request.content)
  366. return httpx.Response(
  367. status_code=200,
  368. content=_make_3mf_with_settings(),
  369. headers={
  370. "x-print-time-seconds": "10",
  371. "x-filament-used-g": "0.1",
  372. "x-filament-used-mm": "1.0",
  373. },
  374. )
  375. _install_mock_sidecar(handler)
  376. response = await async_client.post(
  377. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  378. json={
  379. "printer_preset_id": slice_test_setup["printer_id"],
  380. "process_preset_id": slice_test_setup["process_id"],
  381. "filament_preset_id": slice_test_setup["filament_id"],
  382. },
  383. )
  384. assert response.status_code == 202
  385. final = await _wait_for_job(async_client, response.json()["job_id"])
  386. assert final["status"] == "completed", final
  387. assert b'name="orient"' not in captured["body"]
  388. assert b'name="arrange"' not in captured["body"]
  389. @pytest.mark.asyncio
  390. @pytest.mark.integration
  391. async def test_invalid_preset_id_surfaces_as_failed_job_with_status_400(
  392. self, async_client: AsyncClient, slice_test_setup
  393. ):
  394. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  395. response = await async_client.post(
  396. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  397. json={
  398. # Swap printer/filament — both exist but wrong preset_type.
  399. "printer_preset_id": slice_test_setup["filament_id"],
  400. "process_preset_id": slice_test_setup["process_id"],
  401. "filament_preset_id": slice_test_setup["printer_id"],
  402. },
  403. )
  404. assert response.status_code == 202
  405. final = await _wait_for_job(async_client, response.json()["job_id"])
  406. assert final["status"] == "failed"
  407. assert final["error_status"] == 400
  408. assert "preset_type" in (final["error_detail"] or "")
  409. @pytest.mark.asyncio
  410. @pytest.mark.integration
  411. @pytest.mark.parametrize(
  412. ("slicer", "source", "as_designed", "reaches_the_slicer"),
  413. [
  414. ("bambu_studio", "stl", False, False),
  415. # The flag does nothing for an STL, so the plate is still applied.
  416. ("bambu_studio", "stl", True, False),
  417. # "Slice as designed" on a 3MF never applies the picked plate.
  418. ("bambu_studio", "3mf", True, True),
  419. ("orcaslicer", "stl", False, True),
  420. ],
  421. )
  422. async def test_an_orca_only_plate_is_refused_for_bambu_studio(
  423. self, async_client: AsyncClient, db_session, slice_test_setup, slicer, source, as_designed, reaches_the_slicer
  424. ):
  425. """Bambu Studio slices a plate name it does not know as Cool Plate (#3359)."""
  426. await db_session.execute(
  427. SettingsModel.__table__.update().where(SettingsModel.key == "preferred_slicer").values(value=slicer)
  428. )
  429. await db_session.commit()
  430. file_id = slice_test_setup["src_file_id"]
  431. if source == "3mf":
  432. path = slice_test_setup["tmp_path"] / "library" / "files" / "designed.3mf"
  433. path.write_bytes(_make_3mf_with_settings({"wall_loops": "5"}))
  434. threemf = LibraryFile(
  435. filename="designed.3mf",
  436. file_path=str(path.relative_to(slice_test_setup["tmp_path"])),
  437. file_type="3mf",
  438. file_size=path.stat().st_size,
  439. )
  440. db_session.add(threemf)
  441. await db_session.commit()
  442. file_id = threemf.id
  443. sent: list = []
  444. def handler(request: httpx.Request) -> httpx.Response:
  445. sent.append(request)
  446. return httpx.Response(
  447. status_code=200,
  448. content=_make_3mf_with_settings(),
  449. headers={"x-print-time-seconds": "10", "x-filament-used-g": "0.1", "x-filament-used-mm": "1.0"},
  450. )
  451. _install_mock_sidecar(handler)
  452. response = await async_client.post(
  453. f"/api/v1/library/files/{file_id}/slice",
  454. json={
  455. "printer_preset_id": slice_test_setup["printer_id"],
  456. "process_preset_id": slice_test_setup["process_id"],
  457. "filament_preset_id": slice_test_setup["filament_id"],
  458. "bed_type": "Textured Cool Plate",
  459. "use_embedded_settings": as_designed,
  460. },
  461. )
  462. assert response.status_code == 202
  463. final = await _wait_for_job(async_client, response.json()["job_id"])
  464. if reaches_the_slicer:
  465. assert final["status"] == "completed", final
  466. assert any(_is_slice_post(r) for r in sent)
  467. else:
  468. assert final["status"] == "failed"
  469. assert final["error_status"] == 400
  470. assert "Bambu Studio has no Textured Cool Plate" in final["error_detail"]
  471. assert not any(_is_slice_post(r) for r in sent)
  472. @pytest.mark.asyncio
  473. @pytest.mark.integration
  474. async def test_unknown_preferred_slicer_fails_with_400(
  475. self, async_client: AsyncClient, db_session, slice_test_setup
  476. ):
  477. await db_session.execute(
  478. SettingsModel.__table__.update().where(SettingsModel.key == "preferred_slicer").values(value="prusaslicer")
  479. )
  480. await db_session.commit()
  481. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  482. response = await async_client.post(
  483. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  484. json={
  485. "printer_preset_id": slice_test_setup["printer_id"],
  486. "process_preset_id": slice_test_setup["process_id"],
  487. "filament_preset_id": slice_test_setup["filament_id"],
  488. },
  489. )
  490. assert response.status_code == 202
  491. final = await _wait_for_job(async_client, response.json()["job_id"])
  492. assert final["status"] == "failed"
  493. assert final["error_status"] == 400
  494. assert "preferred_slicer" in (final["error_detail"] or "")
  495. @pytest.mark.asyncio
  496. @pytest.mark.integration
  497. async def test_sidecar_unreachable_fails_with_502(self, async_client: AsyncClient, slice_test_setup):
  498. def handler(_: httpx.Request) -> httpx.Response:
  499. raise httpx.ConnectError("connection refused")
  500. _install_mock_sidecar(handler)
  501. response = await async_client.post(
  502. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  503. json={
  504. "printer_preset_id": slice_test_setup["printer_id"],
  505. "process_preset_id": slice_test_setup["process_id"],
  506. "filament_preset_id": slice_test_setup["filament_id"],
  507. },
  508. )
  509. assert response.status_code == 202
  510. final = await _wait_for_job(async_client, response.json()["job_id"])
  511. assert final["status"] == "failed"
  512. assert final["error_status"] == 502
  513. assert "unreachable" in (final["error_detail"] or "").lower()
  514. @pytest.mark.asyncio
  515. @pytest.mark.integration
  516. @pytest.mark.parametrize(
  517. ("source_model", "target_model", "falls_back"),
  518. [
  519. # Same printer: the file's own settings are a valid slice for it.
  520. ("Bambu Lab X1 Carbon", "Bambu Lab X1 Carbon", True),
  521. # #3535: another printer, or one side unknown -- the fallback would
  522. # hand back G-code for the file's printer as a completed slice.
  523. ("Bambu Lab P1S", "Bambu Lab X1 Carbon", False),
  524. (None, "Bambu Lab X1 Carbon", False),
  525. ("Bambu Lab X1 Carbon", None, False),
  526. ],
  527. )
  528. async def test_3mf_falls_back_to_embedded_settings_on_cli_failure_only_for_its_own_printer(
  529. self, async_client: AsyncClient, db_session, slice_test_setup, source_model, target_model, falls_back
  530. ):
  531. # When the slicer CLI fails on the --load-settings path (segfault
  532. # on complex H2D models), Bambuddy retries with no profile triplet
  533. # so the CLI uses the file's embedded settings -- which describe the
  534. # printer the file was sliced for, so only when that is the target.
  535. settings = {"prime_tower_brim_width": "-1"}
  536. if source_model:
  537. settings["printer_model"] = source_model
  538. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "complex.3mf"
  539. src_3mf_path.write_bytes(_make_3mf_with_settings(settings))
  540. threemf = LibraryFile(
  541. filename="complex.3mf",
  542. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  543. file_type="3mf",
  544. file_size=src_3mf_path.stat().st_size,
  545. )
  546. db_session.add(threemf)
  547. printer_id = slice_test_setup["printer_id"]
  548. if target_model:
  549. target = LocalPreset(
  550. name="# Target printer 0.4 nozzle",
  551. preset_type="printer",
  552. source="orcaslicer",
  553. setting=json.dumps({"name": "Target printer 0.4 nozzle", "printer_model": target_model}),
  554. )
  555. db_session.add(target)
  556. await db_session.commit()
  557. await db_session.refresh(threemf)
  558. if target_model:
  559. await db_session.refresh(target)
  560. printer_id = target.id
  561. call_count = {"n": 0}
  562. def handler(request: httpx.Request) -> httpx.Response:
  563. if not _is_slice_post(request):
  564. return httpx.Response(404)
  565. call_count["n"] += 1
  566. # First call: profile triplet present → simulate CLI 5xx
  567. if call_count["n"] == 1:
  568. return httpx.Response(
  569. status_code=500,
  570. json={"message": "Failed to slice the model"},
  571. )
  572. # Retry: no profile triplet → succeed with embedded settings
  573. return httpx.Response(
  574. status_code=200,
  575. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  576. headers={
  577. "x-print-time-seconds": "100",
  578. "x-filament-used-g": "1.0",
  579. "x-filament-used-mm": "100",
  580. },
  581. )
  582. _install_mock_sidecar(handler)
  583. response = await async_client.post(
  584. f"/api/v1/library/files/{threemf.id}/slice",
  585. json={
  586. "printer_preset_id": printer_id,
  587. "process_preset_id": slice_test_setup["process_id"],
  588. "filament_preset_id": slice_test_setup["filament_id"],
  589. },
  590. )
  591. assert response.status_code == 202
  592. final = await _wait_for_job(async_client, response.json()["job_id"])
  593. if falls_back:
  594. assert final["status"] == "completed", final
  595. assert final["result"]["used_embedded_settings"] is True
  596. assert call_count["n"] == 2 # primary + fallback retry
  597. else:
  598. assert final["status"] == "failed", final
  599. assert final["error_status"] == 502
  600. assert call_count["n"] == 1 # no retry with another printer's settings
  601. @pytest.mark.asyncio
  602. @pytest.mark.integration
  603. async def test_stl_does_not_fall_back_on_cli_failure(self, async_client: AsyncClient, slice_test_setup):
  604. # STL has no embedded settings — the CLI 5xx is terminal.
  605. call_count = {"n": 0}
  606. def handler(request: httpx.Request) -> httpx.Response:
  607. if not _is_slice_post(request):
  608. return httpx.Response(404)
  609. call_count["n"] += 1
  610. return httpx.Response(
  611. status_code=500,
  612. json={"message": "Failed to slice the model"},
  613. )
  614. _install_mock_sidecar(handler)
  615. response = await async_client.post(
  616. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  617. json={
  618. "printer_preset_id": slice_test_setup["printer_id"],
  619. "process_preset_id": slice_test_setup["process_id"],
  620. "filament_preset_id": slice_test_setup["filament_id"],
  621. },
  622. )
  623. assert response.status_code == 202
  624. final = await _wait_for_job(async_client, response.json()["job_id"])
  625. assert final["status"] == "failed"
  626. assert final["error_status"] == 502
  627. assert call_count["n"] == 1 # No retry for STL
  628. @pytest.mark.asyncio
  629. @pytest.mark.integration
  630. async def test_3mf_input_forwarded_unmodified_to_sidecar(
  631. self, async_client: AsyncClient, db_session, slice_test_setup
  632. ):
  633. # 3MF input must be forwarded to the sidecar verbatim — every
  634. # Metadata/*.config the source carries (project_settings,
  635. # model_settings, slice_info, cut_information) is needed by the
  636. # CLI to find plate definitions and baseline config; an earlier
  637. # version of this code stripped them and caused the CLI to
  638. # silently exit immediately after "Initializing StaticPrintConfigs"
  639. # for every 3MF slice. --load-settings overrides the specific
  640. # fields the user changed; the rest comes from the embedded data.
  641. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "real.3mf"
  642. src_3mf_path.write_bytes(_make_3mf_with_settings({"prime_tower_brim_width": "-1"}))
  643. threemf = LibraryFile(
  644. filename="real.3mf",
  645. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  646. file_type="3mf",
  647. file_size=src_3mf_path.stat().st_size,
  648. )
  649. db_session.add(threemf)
  650. await db_session.commit()
  651. await db_session.refresh(threemf)
  652. captured: dict = {}
  653. def handler(request: httpx.Request) -> httpx.Response:
  654. captured["body"] = request.content
  655. return httpx.Response(
  656. status_code=200,
  657. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  658. headers={
  659. "x-print-time-seconds": "1",
  660. "x-filament-used-g": "0",
  661. "x-filament-used-mm": "0",
  662. },
  663. )
  664. _install_mock_sidecar(handler)
  665. response = await async_client.post(
  666. f"/api/v1/library/files/{threemf.id}/slice",
  667. json={
  668. "printer_preset_id": slice_test_setup["printer_id"],
  669. "process_preset_id": slice_test_setup["process_id"],
  670. "filament_preset_id": slice_test_setup["filament_id"],
  671. },
  672. )
  673. assert response.status_code == 202
  674. final = await _wait_for_job(async_client, response.json()["job_id"])
  675. assert final["status"] == "completed", final
  676. # Recover the embedded zip from the multipart body and assert ALL
  677. # the source's Metadata/*.config files are still present — the
  678. # opposite of the previous (broken) "strip everything" test.
  679. body = captured["body"]
  680. pk = body.find(b"PK\x03\x04")
  681. assert pk >= 0, "3MF body not found in multipart payload"
  682. with zipfile.ZipFile(io.BytesIO(body[pk:]), "r") as zin:
  683. names = set(zin.namelist())
  684. assert "Metadata/project_settings.config" in names
  685. assert "Metadata/model_settings.config" in names
  686. assert "Metadata/slice_info.config" in names
  687. assert "Metadata/cut_information.xml" in names
  688. assert "3D/3dmodel.model" in names
  689. @pytest.mark.asyncio
  690. @pytest.mark.integration
  691. async def test_use_embedded_settings_skips_profile_triplet(
  692. self, async_client: AsyncClient, db_session, slice_test_setup
  693. ):
  694. # "Slice as designed" (#2611): with use_embedded_settings the 3MF is
  695. # sliced on its own project_settings.config — no --load-settings — so
  696. # the sidecar request carries ONLY the model file, never the
  697. # printer/process/filament profile parts. Succeeds on the first call
  698. # (no crash-fallback), and the result is flagged used_embedded_settings.
  699. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "designed.3mf"
  700. src_3mf_path.write_bytes(_make_3mf_with_settings({"wall_loops": "5"}))
  701. threemf = LibraryFile(
  702. filename="designed.3mf",
  703. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  704. file_type="3mf",
  705. file_size=src_3mf_path.stat().st_size,
  706. )
  707. db_session.add(threemf)
  708. await db_session.commit()
  709. await db_session.refresh(threemf)
  710. captured: dict = {}
  711. call_count = {"n": 0}
  712. def handler(request: httpx.Request) -> httpx.Response:
  713. if not _is_slice_post(request):
  714. return httpx.Response(404)
  715. call_count["n"] += 1
  716. captured["body"] = request.content
  717. return httpx.Response(
  718. status_code=200,
  719. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  720. headers={
  721. "x-print-time-seconds": "100",
  722. "x-filament-used-g": "1.0",
  723. "x-filament-used-mm": "100",
  724. },
  725. )
  726. _install_mock_sidecar(handler)
  727. response = await async_client.post(
  728. f"/api/v1/library/files/{threemf.id}/slice",
  729. json={
  730. "printer_preset_id": slice_test_setup["printer_id"],
  731. "process_preset_id": slice_test_setup["process_id"],
  732. "filament_preset_id": slice_test_setup["filament_id"],
  733. "use_embedded_settings": True,
  734. },
  735. )
  736. assert response.status_code == 202
  737. final = await _wait_for_job(async_client, response.json()["job_id"])
  738. assert final["status"] == "completed", final
  739. assert final["result"]["used_embedded_settings"] is True
  740. assert call_count["n"] == 1 # embedded path taken directly, no fallback retry
  741. # The multipart body must NOT carry any profile part — that is the
  742. # whole point of the mode. Their presence would mean --load-settings
  743. # ran and overrode the designer's embedded settings.
  744. body = captured["body"]
  745. assert b"printerProfile" not in body
  746. assert b"presetProfile" not in body
  747. assert b"filamentProfile" not in body
  748. @pytest.mark.asyncio
  749. @pytest.mark.integration
  750. async def test_use_embedded_settings_ignored_for_stl(self, async_client: AsyncClient, slice_test_setup):
  751. # An STL has no embedded project settings to honour, so the flag is a
  752. # no-op: the normal profile path runs and the triplet is forwarded.
  753. captured: dict = {}
  754. def handler(request: httpx.Request) -> httpx.Response:
  755. captured["body"] = request.content
  756. return httpx.Response(
  757. status_code=200,
  758. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  759. headers={
  760. "x-print-time-seconds": "1",
  761. "x-filament-used-g": "0",
  762. "x-filament-used-mm": "0",
  763. },
  764. )
  765. _install_mock_sidecar(handler)
  766. response = await async_client.post(
  767. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  768. json={
  769. "printer_preset_id": slice_test_setup["printer_id"],
  770. "process_preset_id": slice_test_setup["process_id"],
  771. "filament_preset_id": slice_test_setup["filament_id"],
  772. "use_embedded_settings": True,
  773. },
  774. )
  775. assert response.status_code == 202
  776. final = await _wait_for_job(async_client, response.json()["job_id"])
  777. assert final["status"] == "completed", final
  778. assert final["result"]["used_embedded_settings"] is False
  779. assert b"printerProfile" in captured["body"] # profile path still ran
  780. # ---------------------------------------------------------------------------
  781. # GET /slice-jobs/{id}
  782. # ---------------------------------------------------------------------------
  783. class TestSliceJobs:
  784. @pytest.mark.asyncio
  785. @pytest.mark.integration
  786. async def test_unknown_job_returns_404(self, async_client: AsyncClient):
  787. # Sweep dispatcher state so a fresh ID is unknown.
  788. slice_dispatch._jobs.clear()
  789. r = await async_client.get("/api/v1/slice-jobs/999999")
  790. assert r.status_code == 404
  791. # ---------------------------------------------------------------------------
  792. # POST /archives/{id}/slice — re-sliced archive reflects the target printer
  793. # ---------------------------------------------------------------------------
  794. def _make_sliced_3mf(printer_model_id: str, bed_type: str | None = None) -> bytes:
  795. """A minimal sliced-output 3MF that embeds a printer_model_id in
  796. slice_info.config, the way a real Bambu Studio / OrcaSlicer export does.
  797. ThreeMFParser reads this into metadata['sliced_for_model']. When
  798. ``bed_type`` is set, also embed ``curr_bed_type`` so the parser surfaces
  799. ``metadata['bed_type']`` — needed for the bed-type lift assertion in
  800. TestSliceArchiveReslicedBedType."""
  801. extra_meta = f"<metadata key='curr_bed_type' value='{bed_type}'/>" if bed_type else ""
  802. buf = io.BytesIO()
  803. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  804. zf.writestr("3D/3dmodel.model", "<model/>")
  805. zf.writestr(
  806. "Metadata/slice_info.config",
  807. (
  808. "<config><plate>"
  809. f"<metadata key='printer_model_id' value='{printer_model_id}'/>"
  810. f"{extra_meta}"
  811. "</plate></config>"
  812. ),
  813. )
  814. return buf.getvalue()
  815. class TestCrossClassSliceAllLoop:
  816. """#1493: when the user picks "Slice all plates" on a cross-class source
  817. (X1C → H2D), Bambuddy must NOT send a single ``--slice 0 --arrange 1``
  818. call — that consolidates every plate's objects onto one bed via BS's
  819. project-wide arrange. Instead it loops per plate (``plate=N, arrange=true``)
  820. and merges the N single-plate outputs into one multi-plate 3MF locally.
  821. This test mocks the sidecar to assert (a) N calls happen, one per plate,
  822. each with arrange=true, and (b) the resulting archive's stored 3MF
  823. contains plate_1..plate_N.gcode entries."""
  824. @staticmethod
  825. def _make_multi_plate_x1c_source(plate_count: int = 3) -> bytes:
  826. """Source 3MF: X1C-stamped, N plates declared via model_settings."""
  827. plate_blocks = "\n".join(
  828. f'<plate><metadata key="plater_id" value="{i}"/></plate>' for i in range(1, plate_count + 1)
  829. )
  830. buf = io.BytesIO()
  831. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  832. zf.writestr("3D/3dmodel.model", "<model/>")
  833. zf.writestr(
  834. "Metadata/project_settings.config",
  835. json.dumps({"printer_model": "Bambu Lab X1 Carbon"}),
  836. )
  837. zf.writestr(
  838. "Metadata/model_settings.config",
  839. f"<?xml version='1.0'?>\n<config>\n{plate_blocks}\n</config>\n",
  840. )
  841. return buf.getvalue()
  842. @staticmethod
  843. def _make_single_plate_sliced_output(plate_num: int) -> bytes:
  844. """Mock per-plate output: looks like what BS CLI returns for
  845. --slice N. Carries an H2D project_settings (target), a one-line
  846. slice_info <plate> block, and a per-plate gcode + thumbnail."""
  847. buf = io.BytesIO()
  848. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  849. zf.writestr("3D/3dmodel.model", "<model/>")
  850. zf.writestr(
  851. "Metadata/project_settings.config",
  852. json.dumps({"printer_model": "Bambu Lab H2D"}),
  853. )
  854. zf.writestr("Metadata/model_settings.config", "<config/>")
  855. zf.writestr(
  856. "Metadata/slice_info.config",
  857. f"<config><plate><metadata key='index' value='{plate_num}'/>"
  858. f"<metadata key='printer_model_id' value='O1D'/></plate></config>",
  859. )
  860. zf.writestr(f"Metadata/plate_{plate_num}.gcode", f"G{plate_num}".encode())
  861. zf.writestr(f"Metadata/plate_{plate_num}.gcode.md5", b"deadbeef")
  862. zf.writestr(f"Metadata/plate_{plate_num}.json", b"{}")
  863. zf.writestr(f"Metadata/plate_{plate_num}.png", f"P{plate_num}".encode())
  864. return buf.getvalue()
  865. @pytest.mark.asyncio
  866. @pytest.mark.integration
  867. async def test_loops_per_plate_when_cross_class_with_plate_zero(
  868. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  869. ):
  870. from backend.app.models.archive import PrintArchive
  871. tmp_path = slice_test_setup["tmp_path"]
  872. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  873. src_dir = tmp_path / "archives" / "src"
  874. src_dir.mkdir(parents=True, exist_ok=True)
  875. src_3mf = src_dir / "mewtwo.3mf"
  876. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=3))
  877. printer = await printer_factory()
  878. source = await archive_factory(
  879. printer.id,
  880. filename="mewtwo.3mf",
  881. file_path=str(src_3mf.relative_to(tmp_path)),
  882. sliced_for_model="X1C",
  883. with_run=False,
  884. )
  885. # H2D target preset — the cross-class detector reads the
  886. # ``printer_model`` field off the resolved JSON.
  887. h2d = LocalPreset(
  888. name="# Bambu Lab H2D 0.4 nozzle",
  889. preset_type="printer",
  890. source="orcaslicer",
  891. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  892. )
  893. db_session.add(h2d)
  894. await db_session.commit()
  895. await db_session.refresh(h2d)
  896. # Mock sidecar: capture every request and respond with that
  897. # plate's single-plate output. We expect one request per plate
  898. # in the source (3 here).
  899. captured_requests: list[dict] = []
  900. def handler(request: httpx.Request) -> httpx.Response:
  901. if not _is_slice_post(request):
  902. return httpx.Response(404)
  903. # Multipart bodies aren't trivially parseable here; pull
  904. # the plate field by string search since the helper sends
  905. # ``name="plate"`` immediately followed by the value.
  906. body = request.content
  907. plate = None
  908. marker = b'name="plate"\r\n\r\n'
  909. idx = body.find(marker)
  910. if idx != -1:
  911. # Find the next CRLF after the value start.
  912. start = idx + len(marker)
  913. end = body.find(b"\r\n", start)
  914. try:
  915. plate = int(body[start:end].decode("utf-8"))
  916. except (UnicodeDecodeError, ValueError):
  917. plate = None
  918. arrange_in_body = b'name="arrange"' in body
  919. captured_requests.append({"plate": plate, "arrange": arrange_in_body})
  920. return httpx.Response(
  921. status_code=200,
  922. content=self._make_single_plate_sliced_output(plate or 1),
  923. headers={
  924. "x-print-time-seconds": "600",
  925. "x-filament-used-g": "5.0",
  926. "x-filament-used-mm": "1600.0",
  927. },
  928. )
  929. _install_mock_sidecar(handler)
  930. # plate=0 + cross-class triplet → backend should enter the
  931. # per-plate loop, slice each of the 3 plates with arrange=True,
  932. # and merge into one archive.
  933. resp = await async_client.post(
  934. f"/api/v1/archives/{source.id}/slice",
  935. json={
  936. "printer_preset": {"source": "local", "id": str(h2d.id)},
  937. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  938. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  939. "plate": 0,
  940. },
  941. )
  942. assert resp.status_code == 202, resp.text
  943. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  944. assert final["status"] == "completed", final
  945. # Exactly one sidecar call per plate, in plate order. The
  946. # ``--arrange 1`` flag travels with every per-plate sub-slice
  947. # (it's what fixes the cross-class boundary error).
  948. plates_called = [c["plate"] for c in captured_requests]
  949. arrange_used = [c["arrange"] for c in captured_requests]
  950. assert plates_called == [1, 2, 3], plates_called
  951. assert all(arrange_used), arrange_used
  952. # The merged archive has plate_1..plate_3.gcode inside its one
  953. # output 3MF (single Bambuddy archive, three plates).
  954. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  955. archive_path = tmp_path / new_archive.file_path
  956. with zipfile.ZipFile(archive_path, "r") as zf:
  957. entries = set(zf.namelist())
  958. assert "Metadata/plate_1.gcode" in entries
  959. assert "Metadata/plate_2.gcode" in entries
  960. assert "Metadata/plate_3.gcode" in entries
  961. # Per-plate-result totals are summed onto the merged archive.
  962. assert new_archive.print_time_seconds == 600 * 3
  963. assert new_archive.filament_used_grams == pytest.approx(5.0 * 3)
  964. @pytest.mark.asyncio
  965. @pytest.mark.integration
  966. async def test_user_requested_arrange_also_loops_per_plate(
  967. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  968. ):
  969. """#2548 inherits #1493's hazard. The per-plate loop exists because
  970. ``--arrange`` is project-wide: a single ``--slice 0 --arrange 1``
  971. collapses every plate's objects onto one bed. That is a property of
  972. the flag, not of the cross-class detour that first needed it — so a
  973. user ticking auto-arrange over "all plates" on a SAME-class source
  974. must take the same loop. Keying the loop on the cross-class decision
  975. alone would send one call and silently return a one-plate result.
  976. """
  977. from backend.app.models.archive import PrintArchive
  978. tmp_path = slice_test_setup["tmp_path"]
  979. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  980. src_dir = tmp_path / "archives" / "src_same_class"
  981. src_dir.mkdir(parents=True, exist_ok=True)
  982. src_3mf = src_dir / "tray.3mf"
  983. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=2))
  984. printer = await printer_factory()
  985. source = await archive_factory(
  986. printer.id,
  987. filename="tray.3mf",
  988. file_path=str(src_3mf.relative_to(tmp_path)),
  989. sliced_for_model="X1C",
  990. with_run=False,
  991. )
  992. # X1C target: same nozzle class as the X1C source, so #1493's
  993. # detector stays off and only the user's flag is in play.
  994. x1c = LocalPreset(
  995. name="# Bambu Lab X1 Carbon 0.4 nozzle",
  996. preset_type="printer",
  997. source="orcaslicer",
  998. setting=json.dumps({"name": "Bambu Lab X1 Carbon 0.4 nozzle", "printer_model": "Bambu Lab X1 Carbon"}),
  999. )
  1000. db_session.add(x1c)
  1001. await db_session.commit()
  1002. await db_session.refresh(x1c)
  1003. captured_requests: list[dict] = []
  1004. def handler(request: httpx.Request) -> httpx.Response:
  1005. if not _is_slice_post(request):
  1006. return httpx.Response(404)
  1007. body = request.content
  1008. plate = None
  1009. marker = b'name="plate"\r\n\r\n'
  1010. idx = body.find(marker)
  1011. if idx != -1:
  1012. start = idx + len(marker)
  1013. end = body.find(b"\r\n", start)
  1014. try:
  1015. plate = int(body[start:end].decode("utf-8"))
  1016. except (UnicodeDecodeError, ValueError):
  1017. plate = None
  1018. captured_requests.append(
  1019. {
  1020. "plate": plate,
  1021. "arrange": b'name="arrange"' in body,
  1022. "orient": b'name="orient"' in body,
  1023. }
  1024. )
  1025. return httpx.Response(
  1026. status_code=200,
  1027. content=self._make_single_plate_sliced_output(plate or 1),
  1028. headers={
  1029. "x-print-time-seconds": "300",
  1030. "x-filament-used-g": "2.0",
  1031. "x-filament-used-mm": "800.0",
  1032. },
  1033. )
  1034. _install_mock_sidecar(handler)
  1035. resp = await async_client.post(
  1036. f"/api/v1/archives/{source.id}/slice",
  1037. json={
  1038. "printer_preset": {"source": "local", "id": str(x1c.id)},
  1039. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1040. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1041. "plate": 0,
  1042. "auto_arrange": True,
  1043. "auto_orient": True,
  1044. },
  1045. )
  1046. assert resp.status_code == 202, resp.text
  1047. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  1048. assert final["status"] == "completed", final
  1049. assert [c["plate"] for c in captured_requests] == [1, 2]
  1050. assert all(c["arrange"] for c in captured_requests)
  1051. # Orient rides along on every sub-slice too — it is per-object, so
  1052. # dropping it on the loop path would quietly ignore the user's tick.
  1053. assert all(c["orient"] for c in captured_requests)
  1054. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1055. with zipfile.ZipFile(tmp_path / new_archive.file_path, "r") as zf:
  1056. entries = set(zf.namelist())
  1057. assert "Metadata/plate_1.gcode" in entries
  1058. assert "Metadata/plate_2.gcode" in entries
  1059. @pytest.mark.asyncio
  1060. @pytest.mark.integration
  1061. async def test_embedded_settings_slice_all_with_arrange_still_loops(
  1062. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1063. ):
  1064. """ "Slice as designed" must not skip the loop. The project-wide
  1065. collapse comes from ``--arrange``; where the print config came from
  1066. has no bearing on it. Taking the single-call embedded branch here
  1067. would return one consolidated plate for a job the user asked to
  1068. slice as N — and the per-plate calls must still omit the profile
  1069. triplet, or "as designed" would silently stop meaning that.
  1070. """
  1071. from backend.app.models.archive import PrintArchive
  1072. tmp_path = slice_test_setup["tmp_path"]
  1073. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1074. src_dir = tmp_path / "archives" / "src_embedded"
  1075. src_dir.mkdir(parents=True, exist_ok=True)
  1076. src_3mf = src_dir / "kit.3mf"
  1077. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=2))
  1078. printer = await printer_factory()
  1079. source = await archive_factory(
  1080. printer.id,
  1081. filename="kit.3mf",
  1082. file_path=str(src_3mf.relative_to(tmp_path)),
  1083. sliced_for_model="X1C",
  1084. with_run=False,
  1085. )
  1086. x1c = LocalPreset(
  1087. name="# Bambu Lab X1 Carbon 0.4 nozzle",
  1088. preset_type="printer",
  1089. source="orcaslicer",
  1090. setting=json.dumps({"name": "Bambu Lab X1 Carbon 0.4 nozzle", "printer_model": "Bambu Lab X1 Carbon"}),
  1091. )
  1092. db_session.add(x1c)
  1093. await db_session.commit()
  1094. await db_session.refresh(x1c)
  1095. captured_requests: list[dict] = []
  1096. def handler(request: httpx.Request) -> httpx.Response:
  1097. if not _is_slice_post(request):
  1098. return httpx.Response(404)
  1099. body = request.content
  1100. plate = None
  1101. marker = b'name="plate"\r\n\r\n'
  1102. idx = body.find(marker)
  1103. if idx != -1:
  1104. start = idx + len(marker)
  1105. end = body.find(b"\r\n", start)
  1106. try:
  1107. plate = int(body[start:end].decode("utf-8"))
  1108. except (UnicodeDecodeError, ValueError):
  1109. plate = None
  1110. captured_requests.append(
  1111. {
  1112. "plate": plate,
  1113. "arrange": b'name="arrange"' in body,
  1114. "has_profiles": b'name="printerProfile"' in body,
  1115. }
  1116. )
  1117. return httpx.Response(
  1118. status_code=200,
  1119. content=self._make_single_plate_sliced_output(plate or 1),
  1120. headers={
  1121. "x-print-time-seconds": "300",
  1122. "x-filament-used-g": "2.0",
  1123. "x-filament-used-mm": "800.0",
  1124. },
  1125. )
  1126. _install_mock_sidecar(handler)
  1127. resp = await async_client.post(
  1128. f"/api/v1/archives/{source.id}/slice",
  1129. json={
  1130. "printer_preset": {"source": "local", "id": str(x1c.id)},
  1131. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1132. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1133. "plate": 0,
  1134. "use_embedded_settings": True,
  1135. "auto_arrange": True,
  1136. },
  1137. )
  1138. assert resp.status_code == 202, resp.text
  1139. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  1140. assert final["status"] == "completed", final
  1141. assert [c["plate"] for c in captured_requests] == [1, 2]
  1142. assert all(c["arrange"] for c in captured_requests)
  1143. # No --load-settings on any sub-call: the file's own settings drive
  1144. # each plate, which is what "slice as designed" promises.
  1145. assert not any(c["has_profiles"] for c in captured_requests)
  1146. assert final["result"]["used_embedded_settings"] is True
  1147. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1148. with zipfile.ZipFile(tmp_path / new_archive.file_path, "r") as zf:
  1149. entries = set(zf.namelist())
  1150. assert "Metadata/plate_1.gcode" in entries
  1151. assert "Metadata/plate_2.gcode" in entries
  1152. @pytest.mark.asyncio
  1153. @pytest.mark.integration
  1154. async def test_cross_class_arrange_survives_user_leaving_the_box_unticked(
  1155. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1156. ):
  1157. """The user's per-slice choice is a union with #1493's decision, not
  1158. a replacement for it. Arrange is what keeps a class-crossing slice
  1159. from landing in the target's dead zone or segfaulting ZFiller — so
  1160. the default-false ``auto_arrange`` must not be able to turn it off.
  1161. """
  1162. tmp_path = slice_test_setup["tmp_path"]
  1163. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1164. src_dir = tmp_path / "archives" / "src_cross_single"
  1165. src_dir.mkdir(parents=True, exist_ok=True)
  1166. src_3mf = src_dir / "clip.3mf"
  1167. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=1))
  1168. printer = await printer_factory()
  1169. source = await archive_factory(
  1170. printer.id,
  1171. filename="clip.3mf",
  1172. file_path=str(src_3mf.relative_to(tmp_path)),
  1173. sliced_for_model="X1C",
  1174. with_run=False,
  1175. )
  1176. h2d = LocalPreset(
  1177. name="# Bambu Lab H2D 0.4 nozzle",
  1178. preset_type="printer",
  1179. source="orcaslicer",
  1180. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  1181. )
  1182. db_session.add(h2d)
  1183. await db_session.commit()
  1184. await db_session.refresh(h2d)
  1185. captured: dict = {}
  1186. def handler(request: httpx.Request) -> httpx.Response:
  1187. if not _is_slice_post(request):
  1188. return httpx.Response(404)
  1189. captured["body"] = bytes(request.content)
  1190. return httpx.Response(
  1191. status_code=200,
  1192. content=self._make_single_plate_sliced_output(1),
  1193. headers={
  1194. "x-print-time-seconds": "300",
  1195. "x-filament-used-g": "2.0",
  1196. "x-filament-used-mm": "800.0",
  1197. },
  1198. )
  1199. _install_mock_sidecar(handler)
  1200. resp = await async_client.post(
  1201. f"/api/v1/archives/{source.id}/slice",
  1202. json={
  1203. "printer_preset": {"source": "local", "id": str(h2d.id)},
  1204. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1205. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1206. "plate": 1,
  1207. "auto_arrange": False,
  1208. },
  1209. )
  1210. assert resp.status_code == 202, resp.text
  1211. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  1212. assert final["status"] == "completed", final
  1213. assert b'name="arrange"' in captured["body"], "cross-class arrange must survive an explicit auto_arrange=false"
  1214. class TestSliceArchiveResliceModel:
  1215. """Re-slicing an archive for a different printer must stamp the new
  1216. archive with the printer it was sliced FOR, not the source's printer."""
  1217. @pytest.mark.asyncio
  1218. @pytest.mark.integration
  1219. async def test_reslice_uses_target_model_not_source_model(
  1220. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1221. ):
  1222. from backend.app.models.archive import PrintArchive
  1223. tmp_path = slice_test_setup["tmp_path"]
  1224. # archive_dir is a static path off the real data dir; point it under
  1225. # base_dir (= tmp_path) so the new archive's file resolves there.
  1226. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1227. # Source archive: a 3MF that was sliced for an X1C.
  1228. src_dir = tmp_path / "archives" / "src"
  1229. src_dir.mkdir(parents=True, exist_ok=True)
  1230. src_3mf = src_dir / "cube.3mf"
  1231. src_3mf.write_bytes(_make_3mf_with_settings())
  1232. printer = await printer_factory()
  1233. source = await archive_factory(
  1234. printer.id,
  1235. filename="cube.3mf",
  1236. file_path=str(src_3mf.relative_to(tmp_path)),
  1237. sliced_for_model="X1C",
  1238. with_run=False,
  1239. )
  1240. source_id = source.id
  1241. # The slicer returns a 3MF whose embedded printer_model_id is O1D (H2D).
  1242. def handler(request: httpx.Request) -> httpx.Response:
  1243. return httpx.Response(
  1244. status_code=200,
  1245. content=_make_sliced_3mf("O1D"),
  1246. headers={
  1247. "x-print-time-seconds": "600",
  1248. "x-filament-used-g": "5.0",
  1249. "x-filament-used-mm": "1600.0",
  1250. },
  1251. )
  1252. _install_mock_sidecar(handler)
  1253. resp = await async_client.post(
  1254. f"/api/v1/archives/{source_id}/slice",
  1255. json={
  1256. "printer_preset_id": slice_test_setup["printer_id"],
  1257. "process_preset_id": slice_test_setup["process_id"],
  1258. "filament_preset_id": slice_test_setup["filament_id"],
  1259. },
  1260. )
  1261. assert resp.status_code == 202, resp.text
  1262. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1263. assert final["status"] == "completed", final
  1264. new_id = final["result"]["archive_id"]
  1265. assert new_id != source_id
  1266. new_archive = await db_session.get(PrintArchive, new_id)
  1267. # The fix: the re-sliced archive reflects H2D — the printer it was
  1268. # sliced for — instead of inheriting X1C from the source archive.
  1269. assert new_archive.sliced_for_model == "H2D"
  1270. # Source archive is untouched.
  1271. source_reloaded = await db_session.get(PrintArchive, source_id)
  1272. assert source_reloaded.sliced_for_model == "X1C"
  1273. @pytest.mark.asyncio
  1274. @pytest.mark.integration
  1275. async def test_cross_model_reslice_drops_source_printer_id(
  1276. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1277. ):
  1278. """A cross-model re-slice (source's X1C → target's H2D) must not carry
  1279. over ``source.printer_id``. The archive card and reprint modal both
  1280. read ``printer_id`` first and only fall back to ``sliced_for_model``
  1281. when it's None, so leaving the inherited id makes the H2D-sliced card
  1282. display the source's X1C printer name (the "Workshop H2C" bug)."""
  1283. from backend.app.models.archive import PrintArchive
  1284. tmp_path = slice_test_setup["tmp_path"]
  1285. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1286. src_dir = tmp_path / "archives" / "src"
  1287. src_dir.mkdir(parents=True, exist_ok=True)
  1288. src_3mf = src_dir / "cube.3mf"
  1289. src_3mf.write_bytes(_make_3mf_with_settings())
  1290. source_printer = await printer_factory()
  1291. source = await archive_factory(
  1292. source_printer.id,
  1293. filename="cube.3mf",
  1294. file_path=str(src_3mf.relative_to(tmp_path)),
  1295. sliced_for_model="X1C",
  1296. with_run=False,
  1297. )
  1298. source_id = source.id
  1299. source_printer_id = source_printer.id
  1300. def handler(request: httpx.Request) -> httpx.Response:
  1301. return httpx.Response(
  1302. status_code=200,
  1303. content=_make_sliced_3mf("O1D"), # H2D
  1304. headers={
  1305. "x-print-time-seconds": "600",
  1306. "x-filament-used-g": "5.0",
  1307. "x-filament-used-mm": "1600.0",
  1308. },
  1309. )
  1310. _install_mock_sidecar(handler)
  1311. resp = await async_client.post(
  1312. f"/api/v1/archives/{source_id}/slice",
  1313. json={
  1314. "printer_preset_id": slice_test_setup["printer_id"],
  1315. "process_preset_id": slice_test_setup["process_id"],
  1316. "filament_preset_id": slice_test_setup["filament_id"],
  1317. },
  1318. )
  1319. assert resp.status_code == 202, resp.text
  1320. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1321. assert final["status"] == "completed", final
  1322. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1323. assert new_archive.sliced_for_model == "H2D"
  1324. # Card / reprint modal will now fall back to the sliced_for_model
  1325. # badge instead of showing the source printer's name.
  1326. assert new_archive.printer_id is None
  1327. # Source untouched: still bound to its original printer.
  1328. source_reloaded = await db_session.get(PrintArchive, source_id)
  1329. assert source_reloaded.printer_id == source_printer_id
  1330. @pytest.mark.asyncio
  1331. @pytest.mark.integration
  1332. async def test_same_model_reslice_preserves_source_printer_id(
  1333. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1334. ):
  1335. """Same-model re-slice (X1C → X1C, e.g. just swapped a process preset)
  1336. keeps ``printer_id`` so the reprint modal pre-selects the original
  1337. printer. Only cross-model re-slices null it out."""
  1338. from backend.app.models.archive import PrintArchive
  1339. tmp_path = slice_test_setup["tmp_path"]
  1340. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1341. src_dir = tmp_path / "archives" / "src"
  1342. src_dir.mkdir(parents=True, exist_ok=True)
  1343. src_3mf = src_dir / "cube.3mf"
  1344. src_3mf.write_bytes(_make_3mf_with_settings())
  1345. source_printer = await printer_factory()
  1346. source = await archive_factory(
  1347. source_printer.id,
  1348. filename="cube.3mf",
  1349. file_path=str(src_3mf.relative_to(tmp_path)),
  1350. sliced_for_model="X1C",
  1351. with_run=False,
  1352. )
  1353. def handler(request: httpx.Request) -> httpx.Response:
  1354. return httpx.Response(
  1355. status_code=200,
  1356. content=_make_sliced_3mf("BL-P001"), # X1C — same model as source
  1357. headers={
  1358. "x-print-time-seconds": "600",
  1359. "x-filament-used-g": "5.0",
  1360. "x-filament-used-mm": "1600.0",
  1361. },
  1362. )
  1363. _install_mock_sidecar(handler)
  1364. resp = await async_client.post(
  1365. f"/api/v1/archives/{source.id}/slice",
  1366. json={
  1367. "printer_preset_id": slice_test_setup["printer_id"],
  1368. "process_preset_id": slice_test_setup["process_id"],
  1369. "filament_preset_id": slice_test_setup["filament_id"],
  1370. },
  1371. )
  1372. assert resp.status_code == 202, resp.text
  1373. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1374. assert final["status"] == "completed", final
  1375. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1376. assert new_archive.sliced_for_model == "X1C"
  1377. # Same-model: keep the source's printer assignment so reprint pre-selects it.
  1378. assert new_archive.printer_id == source_printer.id
  1379. @pytest.mark.asyncio
  1380. @pytest.mark.integration
  1381. async def test_reslice_with_unknown_source_model_preserves_printer_id(
  1382. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1383. ):
  1384. """When ``source.sliced_for_model`` is None (older archive that
  1385. predates that column being populated), the backend can't tell whether
  1386. this is a cross-model re-slice. Fail open and preserve ``printer_id``
  1387. rather than spuriously nulling it — current pre-fix behaviour, kept
  1388. as a deliberate edge case."""
  1389. from backend.app.models.archive import PrintArchive
  1390. tmp_path = slice_test_setup["tmp_path"]
  1391. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1392. src_dir = tmp_path / "archives" / "src"
  1393. src_dir.mkdir(parents=True, exist_ok=True)
  1394. src_3mf = src_dir / "cube.3mf"
  1395. src_3mf.write_bytes(_make_3mf_with_settings())
  1396. source_printer = await printer_factory()
  1397. source = await archive_factory(
  1398. source_printer.id,
  1399. filename="cube.3mf",
  1400. file_path=str(src_3mf.relative_to(tmp_path)),
  1401. sliced_for_model=None,
  1402. with_run=False,
  1403. )
  1404. def handler(request: httpx.Request) -> httpx.Response:
  1405. return httpx.Response(
  1406. status_code=200,
  1407. content=_make_sliced_3mf("O1D"),
  1408. headers={
  1409. "x-print-time-seconds": "600",
  1410. "x-filament-used-g": "5.0",
  1411. "x-filament-used-mm": "1600.0",
  1412. },
  1413. )
  1414. _install_mock_sidecar(handler)
  1415. resp = await async_client.post(
  1416. f"/api/v1/archives/{source.id}/slice",
  1417. json={
  1418. "printer_preset_id": slice_test_setup["printer_id"],
  1419. "process_preset_id": slice_test_setup["process_id"],
  1420. "filament_preset_id": slice_test_setup["filament_id"],
  1421. },
  1422. )
  1423. assert resp.status_code == 202, resp.text
  1424. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1425. assert final["status"] == "completed", final
  1426. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1427. # Insufficient info to decide cross-model → preserve printer_id.
  1428. assert new_archive.printer_id == source_printer.id
  1429. class TestSliceArchiveReslicedThumbnail:
  1430. """#1493 follow-up: the re-sliced archive's cover image preference order is
  1431. source's per-plate render > sliced output's per-plate render >
  1432. Auxiliaries marketing thumbnail. BS CLI rarely writes a fresh
  1433. ``Metadata/plate_N.png`` on the sliced output, so the source's render
  1434. of the same plate (closer to what's actually printing) wins over the
  1435. project-wide marketing image."""
  1436. @staticmethod
  1437. def _make_source_with_plate_png(plate_png_bytes: bytes) -> bytes:
  1438. buf = io.BytesIO()
  1439. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1440. zf.writestr("3D/3dmodel.model", "<model/>")
  1441. zf.writestr("Metadata/plate_1.png", plate_png_bytes)
  1442. # Project-wide marketing image — the unwanted fallback target.
  1443. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"COVER_ART")
  1444. return buf.getvalue()
  1445. @pytest.mark.asyncio
  1446. @pytest.mark.integration
  1447. async def test_uses_source_plate_png_when_sliced_output_lacks_one(
  1448. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1449. ):
  1450. """Sliced output has no per-plate PNG (typical of BS CLI output
  1451. with --arrange). The source's plate_1.png must win over the
  1452. sliced output's Auxiliaries fallback."""
  1453. from backend.app.models.archive import PrintArchive
  1454. tmp_path = slice_test_setup["tmp_path"]
  1455. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1456. # Source has its own plate_1.png AND a project-wide cover.
  1457. source_plate_marker = b"SOURCE_PLATE_RENDER"
  1458. src_dir = tmp_path / "archives" / "src"
  1459. src_dir.mkdir(parents=True, exist_ok=True)
  1460. src_3mf = src_dir / "cube.3mf"
  1461. src_3mf.write_bytes(self._make_source_with_plate_png(source_plate_marker))
  1462. printer = await printer_factory()
  1463. source = await archive_factory(
  1464. printer.id,
  1465. filename="cube.3mf",
  1466. file_path=str(src_3mf.relative_to(tmp_path)),
  1467. sliced_for_model="X1C",
  1468. with_run=False,
  1469. )
  1470. # Mock slicer returns a 3MF with NO Metadata/plate_1.png — only
  1471. # the Auxiliaries cover, mimicking BS CLI output with --arrange.
  1472. def handler(request: httpx.Request) -> httpx.Response:
  1473. sliced_buf = io.BytesIO()
  1474. with zipfile.ZipFile(sliced_buf, "w") as zf:
  1475. zf.writestr("3D/3dmodel.model", "<model/>")
  1476. zf.writestr("Metadata/slice_info.config", "<config/>")
  1477. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"SLICED_COVER_ART")
  1478. return httpx.Response(
  1479. status_code=200,
  1480. content=sliced_buf.getvalue(),
  1481. headers={"x-print-time-seconds": "60", "x-filament-used-g": "1", "x-filament-used-mm": "100"},
  1482. )
  1483. _install_mock_sidecar(handler)
  1484. resp = await async_client.post(
  1485. f"/api/v1/archives/{source.id}/slice",
  1486. json={
  1487. "printer_preset_id": slice_test_setup["printer_id"],
  1488. "process_preset_id": slice_test_setup["process_id"],
  1489. "filament_preset_id": slice_test_setup["filament_id"],
  1490. },
  1491. )
  1492. assert resp.status_code == 202, resp.text
  1493. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1494. assert final["status"] == "completed", final
  1495. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1496. assert new.thumbnail_path is not None
  1497. thumb_full = tmp_path / new.thumbnail_path
  1498. assert thumb_full.read_bytes() == source_plate_marker, (
  1499. "Re-sliced archive's thumbnail should be the source's per-plate render, not the Auxiliaries cover art."
  1500. )
  1501. @pytest.mark.asyncio
  1502. @pytest.mark.integration
  1503. async def test_falls_back_to_auxiliaries_when_source_lacks_plate_png(
  1504. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1505. ):
  1506. """When the source has no per-plate render (unsliced library upload),
  1507. the Auxiliaries marketing image from the sliced output is the
  1508. next-best preview — better than no card thumbnail at all."""
  1509. from backend.app.models.archive import PrintArchive
  1510. tmp_path = slice_test_setup["tmp_path"]
  1511. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1512. # Source has no Metadata/plate_1.png at all.
  1513. bare_buf = io.BytesIO()
  1514. with zipfile.ZipFile(bare_buf, "w") as zf:
  1515. zf.writestr("3D/3dmodel.model", "<model/>")
  1516. src_dir = tmp_path / "archives" / "src"
  1517. src_dir.mkdir(parents=True, exist_ok=True)
  1518. src_3mf = src_dir / "bare.3mf"
  1519. src_3mf.write_bytes(bare_buf.getvalue())
  1520. printer = await printer_factory()
  1521. source = await archive_factory(
  1522. printer.id,
  1523. filename="bare.3mf",
  1524. file_path=str(src_3mf.relative_to(tmp_path)),
  1525. sliced_for_model="X1C",
  1526. with_run=False,
  1527. )
  1528. def handler(request: httpx.Request) -> httpx.Response:
  1529. sliced_buf = io.BytesIO()
  1530. with zipfile.ZipFile(sliced_buf, "w") as zf:
  1531. zf.writestr("3D/3dmodel.model", "<model/>")
  1532. zf.writestr("Metadata/slice_info.config", "<config/>")
  1533. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"COVER_ART_FALLBACK")
  1534. return httpx.Response(
  1535. status_code=200,
  1536. content=sliced_buf.getvalue(),
  1537. headers={"x-print-time-seconds": "60", "x-filament-used-g": "1", "x-filament-used-mm": "100"},
  1538. )
  1539. _install_mock_sidecar(handler)
  1540. resp = await async_client.post(
  1541. f"/api/v1/archives/{source.id}/slice",
  1542. json={
  1543. "printer_preset_id": slice_test_setup["printer_id"],
  1544. "process_preset_id": slice_test_setup["process_id"],
  1545. "filament_preset_id": slice_test_setup["filament_id"],
  1546. },
  1547. )
  1548. assert resp.status_code == 202, resp.text
  1549. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1550. assert final["status"] == "completed", final
  1551. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1552. assert new.thumbnail_path is not None
  1553. thumb_full = tmp_path / new.thumbnail_path
  1554. assert thumb_full.read_bytes() == b"COVER_ART_FALLBACK"
  1555. class TestSliceArchiveReslicedBedType:
  1556. """#1493 follow-up: the re-sliced archive's ``bed_type`` column must be
  1557. set from the produced 3MF's ``curr_bed_type`` so the frontend's archive
  1558. card shows the right build-plate badge (the card reads the column, not
  1559. extra_data, so the value was previously invisible after a re-slice)."""
  1560. @pytest.mark.asyncio
  1561. @pytest.mark.integration
  1562. async def test_bed_type_lifted_from_sliced_output(
  1563. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1564. ):
  1565. from backend.app.models.archive import PrintArchive
  1566. tmp_path = slice_test_setup["tmp_path"]
  1567. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1568. src_dir = tmp_path / "archives" / "src"
  1569. src_dir.mkdir(parents=True, exist_ok=True)
  1570. src_3mf = src_dir / "cube.3mf"
  1571. src_3mf.write_bytes(_make_3mf_with_settings())
  1572. printer = await printer_factory()
  1573. source = await archive_factory(
  1574. printer.id,
  1575. filename="cube.3mf",
  1576. file_path=str(src_3mf.relative_to(tmp_path)),
  1577. sliced_for_model="X1C",
  1578. bed_type="Cool Plate",
  1579. with_run=False,
  1580. )
  1581. # Mock slicer: produced 3MF declares a different plate type than
  1582. # the source archive's ``Cool Plate``. The new column must reflect
  1583. # the slicer's value (the user picked a different plate in the
  1584. # SliceModal) instead of inheriting the source's.
  1585. def handler(request: httpx.Request) -> httpx.Response:
  1586. return httpx.Response(
  1587. status_code=200,
  1588. content=_make_sliced_3mf("O1D", bed_type="Textured PEI Plate"),
  1589. headers={
  1590. "x-print-time-seconds": "600",
  1591. "x-filament-used-g": "5.0",
  1592. "x-filament-used-mm": "1600.0",
  1593. },
  1594. )
  1595. _install_mock_sidecar(handler)
  1596. resp = await async_client.post(
  1597. f"/api/v1/archives/{source.id}/slice",
  1598. json={
  1599. "printer_preset_id": slice_test_setup["printer_id"],
  1600. "process_preset_id": slice_test_setup["process_id"],
  1601. "filament_preset_id": slice_test_setup["filament_id"],
  1602. },
  1603. )
  1604. assert resp.status_code == 202, resp.text
  1605. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1606. assert final["status"] == "completed", final
  1607. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1608. assert new.bed_type == "Textured PEI Plate"
  1609. @pytest.mark.asyncio
  1610. @pytest.mark.integration
  1611. async def test_bed_type_falls_back_to_source_when_missing_from_output(
  1612. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1613. ):
  1614. """An older sidecar or sparse slice profile may produce a 3MF without
  1615. ``curr_bed_type``. The source archive's ``bed_type`` is the right
  1616. default in that case — better than leaving the badge blank."""
  1617. from backend.app.models.archive import PrintArchive
  1618. tmp_path = slice_test_setup["tmp_path"]
  1619. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1620. src_dir = tmp_path / "archives" / "src"
  1621. src_dir.mkdir(parents=True, exist_ok=True)
  1622. src_3mf = src_dir / "cube.3mf"
  1623. src_3mf.write_bytes(_make_3mf_with_settings())
  1624. printer = await printer_factory()
  1625. source = await archive_factory(
  1626. printer.id,
  1627. filename="cube.3mf",
  1628. file_path=str(src_3mf.relative_to(tmp_path)),
  1629. sliced_for_model="X1C",
  1630. bed_type="Cool Plate",
  1631. with_run=False,
  1632. )
  1633. def handler(request: httpx.Request) -> httpx.Response:
  1634. return httpx.Response(
  1635. status_code=200,
  1636. # No bed_type embedded — simulates a sidecar that drops it.
  1637. content=_make_sliced_3mf("O1D"),
  1638. headers={
  1639. "x-print-time-seconds": "600",
  1640. "x-filament-used-g": "5.0",
  1641. "x-filament-used-mm": "1600.0",
  1642. },
  1643. )
  1644. _install_mock_sidecar(handler)
  1645. resp = await async_client.post(
  1646. f"/api/v1/archives/{source.id}/slice",
  1647. json={
  1648. "printer_preset_id": slice_test_setup["printer_id"],
  1649. "process_preset_id": slice_test_setup["process_id"],
  1650. "filament_preset_id": slice_test_setup["filament_id"],
  1651. },
  1652. )
  1653. assert resp.status_code == 202, resp.text
  1654. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1655. assert final["status"] == "completed", final
  1656. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1657. assert new.bed_type == "Cool Plate"
  1658. # ---------------------------------------------------------------------------
  1659. # Slicer content rejections surface instead of silently falling back
  1660. # ---------------------------------------------------------------------------
  1661. class TestSlicerRejectionMessage:
  1662. """_slicer_rejection_message distinguishes a real slicer content rejection
  1663. (surface it to the user) from a CLI crash (fall back to embedded)."""
  1664. def test_extracts_bed_boundary_reason(self):
  1665. text = (
  1666. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1667. "Some objects are located over the boundary of the heated bed.: "
  1668. "Slicer process failed (exit code 204)\nstdout: trace ..."
  1669. )
  1670. assert _slicer_rejection_message(text) == "Some objects are located over the boundary of the heated bed."
  1671. def test_extracts_filament_temp_reason(self):
  1672. text = (
  1673. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1674. "The temperature difference of the filaments used is too large.: "
  1675. "Slicer process failed (exit code 194)"
  1676. )
  1677. assert _slicer_rejection_message(text) == "The temperature difference of the filaments used is too large."
  1678. def test_generic_cli_failure_is_not_a_rejection(self):
  1679. # The #1201 CLI-crash signature carries no slicer error_string, so it
  1680. # must still fall through to the embedded-settings fallback.
  1681. assert _slicer_rejection_message("Slicer CLI failed (500): Failed to slice the model") is None
  1682. def test_empty_or_unrelated_text(self):
  1683. assert _slicer_rejection_message("") is None
  1684. assert _slicer_rejection_message("Slicer sidecar unreachable: connection reset") is None
  1685. def test_replaces_input_preset_invalid_placeholder_with_cli_error_line(self):
  1686. # #1851: the CLI emits its catch-all "input preset file is invalid"
  1687. # placeholder for every -5 exit, including real preset-vs-printer
  1688. # compatibility rejections. The actual diagnostic only appears in the
  1689. # stdout `[error] run NNNN:` line; the function must prefer that.
  1690. text = (
  1691. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1692. "The input preset file is invalid and can not be parsed.: "
  1693. "Slicer process failed (exit code 251)\n"
  1694. "stdout: [2026-06-29 04:12:11.952784] [trace] Initializing StaticPrintConfigs\n"
  1695. "[2026-06-29 04:12:12.175810] [error] run 3008: filament preset "
  1696. "Generic PLA @BBL H2C (slot 1) is not compatible with printer "
  1697. "Bambu Lab A1 0.4 nozzle.\n"
  1698. "run found error, return -5, exit..."
  1699. )
  1700. assert (
  1701. _slicer_rejection_message(text) == "filament preset Generic PLA @BBL H2C (slot 1) is not compatible with "
  1702. "printer Bambu Lab A1 0.4 nozzle."
  1703. )
  1704. def test_keeps_meaningful_reason_even_when_cli_error_line_present(self):
  1705. # When the headline error_string is already a useful reason (here:
  1706. # the bed-boundary rejection), don't override it with a generic
  1707. # `[error]` line that may just be the same message restated. Avoids
  1708. # double-text duplication in the user-facing detail.
  1709. text = (
  1710. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1711. "Some objects are located over the boundary of the heated bed.: "
  1712. "Slicer process failed (exit code 204)\n"
  1713. "stdout: [error] some unrelated stdout chatter"
  1714. )
  1715. assert _slicer_rejection_message(text) == "Some objects are located over the boundary of the heated bed."
  1716. def test_cli_error_line_without_run_prefix(self):
  1717. # The CLI sometimes logs `[error] <msg>` without the `run NNNN:`
  1718. # prefix (different code paths). The regex must still pick it up.
  1719. text = (
  1720. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1721. "The input preset file is invalid and can not be parsed.: "
  1722. "Slicer process failed (exit code 251)\n"
  1723. "stdout: [2026-06-29 12:00:00.000000] [error] Configuration parse failed: missing key 'printer_settings_id'"
  1724. )
  1725. assert _slicer_rejection_message(text) == "Configuration parse failed: missing key 'printer_settings_id'"
  1726. class TestSliceSlicerRejection:
  1727. @pytest.mark.asyncio
  1728. @pytest.mark.integration
  1729. async def test_3mf_surfaces_slicer_rejection_instead_of_falling_back(
  1730. self, async_client: AsyncClient, db_session, slice_test_setup
  1731. ):
  1732. """A real slicer content rejection (e.g. re-slicing for a printer with
  1733. a smaller bed) must surface as a 400 — not silently fall back to the
  1734. source 3MF's embedded settings, which would re-slice for the original
  1735. printer and hide the problem."""
  1736. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "toobig.3mf"
  1737. src_3mf_path.write_bytes(_make_3mf_with_settings())
  1738. threemf = LibraryFile(
  1739. filename="toobig.3mf",
  1740. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  1741. file_type="3mf",
  1742. file_size=src_3mf_path.stat().st_size,
  1743. )
  1744. db_session.add(threemf)
  1745. await db_session.commit()
  1746. await db_session.refresh(threemf)
  1747. call_count = {"n": 0}
  1748. def handler(request: httpx.Request) -> httpx.Response:
  1749. if not _is_slice_post(request):
  1750. return httpx.Response(404)
  1751. call_count["n"] += 1
  1752. return httpx.Response(
  1753. status_code=500,
  1754. json={
  1755. "message": (
  1756. "Slicing failed with error from slicer: Some objects are "
  1757. "located over the boundary of the heated bed."
  1758. ),
  1759. "details": "Slicer process failed (exit code 204)",
  1760. },
  1761. )
  1762. _install_mock_sidecar(handler)
  1763. response = await async_client.post(
  1764. f"/api/v1/library/files/{threemf.id}/slice",
  1765. json={
  1766. "printer_preset_id": slice_test_setup["printer_id"],
  1767. "process_preset_id": slice_test_setup["process_id"],
  1768. "filament_preset_id": slice_test_setup["filament_id"],
  1769. },
  1770. )
  1771. assert response.status_code == 202
  1772. final = await _wait_for_job(async_client, response.json()["job_id"])
  1773. assert final["status"] == "failed", final
  1774. assert final["error_status"] == 400
  1775. assert "boundary of the heated bed" in (final["error_detail"] or "")
  1776. # The slicer rejection must NOT trigger the embedded-settings retry.
  1777. assert call_count["n"] == 1
  1778. # ---------------------------------------------------------------------------
  1779. # Nozzle-class re-slice guard — single-nozzle <-> dual-nozzle (H2D) is blocked
  1780. # ---------------------------------------------------------------------------
  1781. from fastapi import HTTPException # noqa: E402
  1782. from backend.app.api.routes.library import ( # noqa: E402
  1783. _canonical_printer_model,
  1784. guard_nozzle_class_reslice,
  1785. )
  1786. class TestCanonicalPrinterModel:
  1787. """_canonical_printer_model strips the '# ' clone prefix and the
  1788. ' 0.4 nozzle' variant suffix so preset names resolve to a model code."""
  1789. def test_strips_nozzle_suffix(self):
  1790. assert _canonical_printer_model("Bambu Lab H2D 0.4 nozzle") == "H2D"
  1791. def test_strips_clone_prefix_and_suffix(self):
  1792. assert _canonical_printer_model("# Bambu Lab X1 Carbon 0.4 nozzle") == "X1C"
  1793. def test_bare_model_and_empty(self):
  1794. assert _canonical_printer_model("Bambu Lab H2D") == "H2D"
  1795. assert _canonical_printer_model(None) is None
  1796. assert _canonical_printer_model("") is None
  1797. class TestNozzleClassGuard:
  1798. """guard_nozzle_class_reslice is now a no-op (#1493). Cross-class re-slicing
  1799. is handled by the two-pass conversion in _run_slicer_with_fallback — so the
  1800. guard never blocks. The function is kept (and these tests with it) so
  1801. external forks / pinned versions that call it still link, and so a future
  1802. regression that re-introduces a raise inside the helper gets caught here."""
  1803. @staticmethod
  1804. def _request() -> object:
  1805. return type("_Req", (), {})()
  1806. @pytest.mark.asyncio
  1807. async def test_single_to_dual_is_allowed(self, monkeypatch):
  1808. """Cross-class re-slice: handled by the two-pass converter, so the
  1809. guard does NOT raise."""
  1810. import backend.app.api.routes.library as lib
  1811. async def _target(_db, _user, _request):
  1812. return "H2D"
  1813. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1814. # No raise — the converter handles this case now.
  1815. await guard_nozzle_class_reslice(None, None, self._request(), "X1C")
  1816. @pytest.mark.asyncio
  1817. async def test_dual_to_single_is_allowed(self, monkeypatch):
  1818. import backend.app.api.routes.library as lib
  1819. async def _target(_db, _user, _request):
  1820. return "X1C"
  1821. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1822. await guard_nozzle_class_reslice(None, None, self._request(), "H2D")
  1823. @pytest.mark.asyncio
  1824. async def test_same_nozzle_class_is_allowed(self, monkeypatch):
  1825. import backend.app.api.routes.library as lib
  1826. async def _target(_db, _user, _request):
  1827. return "P1S"
  1828. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1829. await guard_nozzle_class_reslice(None, None, self._request(), "X1C")
  1830. @pytest.mark.asyncio
  1831. async def test_no_source_model_is_a_noop(self, monkeypatch):
  1832. import backend.app.api.routes.library as lib
  1833. async def _target(_db, _user, _request):
  1834. return "H2D"
  1835. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1836. await guard_nozzle_class_reslice(None, None, self._request(), None)
  1837. @pytest.mark.asyncio
  1838. async def test_null_request_is_a_noop(self):
  1839. await guard_nozzle_class_reslice(None, None, None, "X1C")
  1840. @pytest.mark.asyncio
  1841. @pytest.mark.integration
  1842. async def test_archive_reslice_x1c_to_h2d_preset_path_is_not_400(
  1843. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1844. ):
  1845. """End to end: the preset-driven archive re-slice from X1C to H2D no
  1846. longer gets a synchronous 400 from the guard. It may still fail
  1847. downstream (no sidecar in test env), but it must not be rejected by
  1848. the nozzle-class guard's old "isn't supported yet" message."""
  1849. tmp_path = slice_test_setup["tmp_path"]
  1850. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1851. src_dir = tmp_path / "archives" / "src"
  1852. src_dir.mkdir(parents=True, exist_ok=True)
  1853. src_3mf = src_dir / "cube.3mf"
  1854. src_3mf.write_bytes(_make_3mf_with_settings())
  1855. printer = await printer_factory()
  1856. source = await archive_factory(
  1857. printer.id,
  1858. filename="cube.3mf",
  1859. file_path=str(src_3mf.relative_to(tmp_path)),
  1860. sliced_for_model="X1C",
  1861. with_run=False,
  1862. )
  1863. h2d = LocalPreset(
  1864. name="# Bambu Lab H2D 0.4 nozzle",
  1865. preset_type="printer",
  1866. source="orcaslicer",
  1867. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  1868. )
  1869. db_session.add(h2d)
  1870. await db_session.commit()
  1871. await db_session.refresh(h2d)
  1872. resp = await async_client.post(
  1873. f"/api/v1/archives/{source.id}/slice",
  1874. json={
  1875. "printer_preset": {"source": "local", "id": str(h2d.id)},
  1876. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1877. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1878. },
  1879. )
  1880. if resp.status_code == 400:
  1881. detail = resp.json().get("detail", "")
  1882. assert "isn't supported" not in detail, f"guard still firing on preset path: {detail!r}"
  1883. class TestUnusedSlotSubstitutionOnSinglePlateSource:
  1884. """#2711: a single-plate 3MF must still get its unused slots substituted.
  1885. The SliceModal omits ``plate`` entirely for single-plate and STL sources —
  1886. it skips the plate picker, so ``selectedPlate`` stays null and the field
  1887. never reaches the body. The schema documents an absent plate as "plate 1",
  1888. but the substitution used to read it as "unknown plate" and skip, so every
  1889. single-plate project reached the CLI with the dropdown values of slots the
  1890. plate never paints with.
  1891. In the reported case that was a MakerWorld project declaring four filaments
  1892. while plate 1 paints with one, the other three carrying presets baked into
  1893. the source for a different printer. The CLI rejected the whole slice with
  1894. "filament preset ... (slot 1) is not compatible with printer ...", and the
  1895. modal disables unused rows so there was no way to correct it by hand.
  1896. """
  1897. @staticmethod
  1898. def _single_plate_using_only_slot_3() -> bytes:
  1899. """One plate, one object, painted with slot 3 — slots 1, 2 and 4 are
  1900. declared by the project but unused. Mirrors the reported file."""
  1901. buf = io.BytesIO()
  1902. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1903. zf.writestr("3D/3dmodel.model", "<model/>")
  1904. zf.writestr(
  1905. "Metadata/project_settings.config",
  1906. json.dumps({"filament_type": ["PLA", "PLA", "PLA", "TPU"]}),
  1907. )
  1908. zf.writestr(
  1909. "Metadata/model_settings.config",
  1910. "<?xml version='1.0'?>\n<config>"
  1911. '<object id="1"><metadata key="extruder" value="3"/></object>'
  1912. '<plate><metadata key="plater_id" value="1"/>'
  1913. '<model_instance><metadata key="object_id" value="1"/>'
  1914. '<metadata key="instance_id" value="0"/></model_instance>'
  1915. "</plate></config>",
  1916. )
  1917. return buf.getvalue()
  1918. @staticmethod
  1919. def _filament_names_sent(body: bytes) -> list[str]:
  1920. """Pull the ``name`` of each ``filamentProfile`` part, in slot order.
  1921. ``slice_model`` sends one repeated ``filamentProfile`` part per slot as
  1922. ``filament_N.json``; the parts stay in submission order, so a plain
  1923. scan preserves the slot mapping.
  1924. """
  1925. names: list[str] = []
  1926. marker = b'name="filamentProfile"; filename="filament_'
  1927. pos = body.find(marker)
  1928. while pos != -1:
  1929. start = body.find(b"{", pos)
  1930. end = body.find(b"\r\n", start)
  1931. names.append(json.loads(body[start:end].decode("utf-8"))["name"])
  1932. pos = body.find(marker, end)
  1933. return names
  1934. @pytest.mark.asyncio
  1935. @pytest.mark.integration
  1936. async def test_unused_slots_are_substituted_when_the_body_omits_plate(
  1937. self, async_client: AsyncClient, db_session, slice_test_setup
  1938. ):
  1939. tmp_path = slice_test_setup["tmp_path"]
  1940. src = tmp_path / "library" / "files" / "train.3mf"
  1941. src.write_bytes(self._single_plate_using_only_slot_3())
  1942. threemf = LibraryFile(
  1943. filename="train.3mf",
  1944. file_path=str(src.relative_to(tmp_path)),
  1945. file_type="3mf",
  1946. file_size=src.stat().st_size,
  1947. )
  1948. db_session.add(threemf)
  1949. # Four distinguishable filament presets, one per project slot. Only
  1950. # slot 3's is compatible with the target in the reported scenario.
  1951. slots = []
  1952. for i in range(1, 5):
  1953. p = LocalPreset(
  1954. name=f"slot{i}",
  1955. preset_type="filament",
  1956. source="orcaslicer",
  1957. setting=json.dumps({"name": f"slot{i}", "type": "filament"}),
  1958. )
  1959. db_session.add(p)
  1960. slots.append(p)
  1961. await db_session.commit()
  1962. await db_session.refresh(threemf)
  1963. for p in slots:
  1964. await db_session.refresh(p)
  1965. captured: list[list[str]] = []
  1966. def handler(request: httpx.Request) -> httpx.Response:
  1967. if not _is_slice_post(request):
  1968. return httpx.Response(404)
  1969. captured.append(self._filament_names_sent(request.content))
  1970. return httpx.Response(
  1971. status_code=200,
  1972. content=_make_3mf_with_settings(),
  1973. headers={
  1974. "x-print-time-seconds": "100",
  1975. "x-filament-used-g": "1.0",
  1976. "x-filament-used-mm": "100",
  1977. },
  1978. )
  1979. _install_mock_sidecar(handler)
  1980. response = await async_client.post(
  1981. f"/api/v1/library/files/{threemf.id}/slice",
  1982. json={
  1983. "printer_preset": {"source": "local", "id": str(slice_test_setup["printer_id"])},
  1984. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1985. "filament_presets": [{"source": "local", "id": str(p.id)} for p in slots],
  1986. # No "plate" — exactly what the modal sends for a single-plate
  1987. # source. This is the whole point of the test.
  1988. },
  1989. )
  1990. assert response.status_code == 202, response.text
  1991. final = await _wait_for_job(async_client, response.json()["job_id"])
  1992. assert final["status"] == "completed", final
  1993. assert captured, "sidecar was never called"
  1994. # Every slot carries slot 3's profile: the array length stays intact
  1995. # (the source's per-slot references depend on it) while nothing the
  1996. # plate doesn't print with can fail the CLI's validators.
  1997. assert captured[0] == ["slot3", "slot3", "slot3", "slot3"], captured[0]
  1998. @pytest.mark.asyncio
  1999. @pytest.mark.integration
  2000. async def test_slice_all_keeps_every_slot(self, async_client: AsyncClient, db_session, slice_test_setup):
  2001. """``plate=0`` is the all-plates sentinel, so nothing is unused.
  2002. It reaches the same call site, and plate ids are 1-indexed — the
  2003. geometry lookup for plate 0 matches nothing. Without an explicit
  2004. exclusion the project's support-filament slot would be the only
  2005. member of the used set and would be copied over every colour.
  2006. """
  2007. tmp_path = slice_test_setup["tmp_path"]
  2008. buf = io.BytesIO()
  2009. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  2010. zf.writestr("3D/3dmodel.model", "<model/>")
  2011. zf.writestr(
  2012. "Metadata/project_settings.config",
  2013. json.dumps(
  2014. {
  2015. "enable_support": "1",
  2016. "support_filament": "4",
  2017. "support_interface_filament": "4",
  2018. "filament_type": ["PLA", "PLA", "PLA", "PVA"],
  2019. }
  2020. ),
  2021. )
  2022. zf.writestr(
  2023. "Metadata/model_settings.config",
  2024. "<?xml version='1.0'?>\n<config>"
  2025. '<object id="1"><metadata key="extruder" value="1"/></object>'
  2026. '<object id="2"><metadata key="extruder" value="2"/></object>'
  2027. '<plate><metadata key="plater_id" value="1"/>'
  2028. '<model_instance><metadata key="object_id" value="1"/></model_instance></plate>'
  2029. '<plate><metadata key="plater_id" value="2"/>'
  2030. '<model_instance><metadata key="object_id" value="2"/></model_instance></plate>'
  2031. "</config>",
  2032. )
  2033. src = tmp_path / "library" / "files" / "multi.3mf"
  2034. src.write_bytes(buf.getvalue())
  2035. threemf = LibraryFile(
  2036. filename="multi.3mf",
  2037. file_path=str(src.relative_to(tmp_path)),
  2038. file_type="3mf",
  2039. file_size=src.stat().st_size,
  2040. )
  2041. db_session.add(threemf)
  2042. slots = []
  2043. for i in range(1, 5):
  2044. p = LocalPreset(
  2045. name=f"slot{i}",
  2046. preset_type="filament",
  2047. source="orcaslicer",
  2048. setting=json.dumps({"name": f"slot{i}", "type": "filament"}),
  2049. )
  2050. db_session.add(p)
  2051. slots.append(p)
  2052. await db_session.commit()
  2053. await db_session.refresh(threemf)
  2054. for p in slots:
  2055. await db_session.refresh(p)
  2056. captured: list[list[str]] = []
  2057. def handler(request: httpx.Request) -> httpx.Response:
  2058. if not _is_slice_post(request):
  2059. return httpx.Response(404)
  2060. captured.append(self._filament_names_sent(request.content))
  2061. return httpx.Response(
  2062. status_code=200,
  2063. content=_make_3mf_with_settings(),
  2064. headers={
  2065. "x-print-time-seconds": "100",
  2066. "x-filament-used-g": "1.0",
  2067. "x-filament-used-mm": "100",
  2068. },
  2069. )
  2070. _install_mock_sidecar(handler)
  2071. response = await async_client.post(
  2072. f"/api/v1/library/files/{threemf.id}/slice",
  2073. json={
  2074. "printer_preset": {"source": "local", "id": str(slice_test_setup["printer_id"])},
  2075. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  2076. "filament_presets": [{"source": "local", "id": str(p.id)} for p in slots],
  2077. "plate": 0,
  2078. },
  2079. )
  2080. assert response.status_code == 202, response.text
  2081. final = await _wait_for_job(async_client, response.json()["job_id"])
  2082. assert final["status"] == "completed", final
  2083. assert captured, "sidecar was never called"
  2084. assert captured[0] == ["slot1", "slot2", "slot3", "slot4"], captured[0]
  2085. class TestFilamentRequirementsFullSlots:
  2086. """#2712: what the slice modal is handed must be positional.
  2087. The modal's filament list maps index 0 to slot 1, and the backend forwards
  2088. it in that order as ``filament_1.json``..``filament_N.json``. A MakerWorld
  2089. source that ships slice_info and paints with slot 4 alone therefore has to
  2090. present four rows — a one-row list binds the user's pick to slot 1, and
  2091. slot 4 slices with whatever the source had baked in. Picking PETG produced
  2092. a PLA print, and the print dialog then correctly refused to match PETG.
  2093. Print-time AMS matching shares this endpoint and needs the opposite: only
  2094. the slots the plate consumes, so it doesn't demand spools for slots the
  2095. G-code never touches. Hence the opt-in flag rather than a shape change.
  2096. """
  2097. @staticmethod
  2098. def _sliced_source_using_only_slot_4() -> bytes:
  2099. buf = io.BytesIO()
  2100. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  2101. zf.writestr("3D/3dmodel.model", "<model/>")
  2102. zf.writestr(
  2103. "Metadata/project_settings.config",
  2104. json.dumps(
  2105. {
  2106. "filament_type": ["PLA", "PLA", "PLA", "PLA"],
  2107. "filament_colour": ["#38CC0A", "#161616", "#898989", "#898989"],
  2108. }
  2109. ),
  2110. )
  2111. # MakerWorld ships slice_info without plate G-code, which is what
  2112. # sends this file down the "already sliced" branch.
  2113. zf.writestr(
  2114. "Metadata/slice_info.config",
  2115. "<?xml version='1.0'?>\n<config><plate>"
  2116. "<metadata key='index' value='1'/>"
  2117. "<filament id='4' tray_info_idx='GFL99' type='PLA' color='#898989'"
  2118. " used_m='35.51' used_g='105.92'/>"
  2119. "</plate></config>",
  2120. )
  2121. return buf.getvalue()
  2122. async def _make_file(self, db_session, tmp_path) -> int:
  2123. src = tmp_path / "library" / "files" / "tunnel.3mf"
  2124. src.write_bytes(self._sliced_source_using_only_slot_4())
  2125. lib = LibraryFile(
  2126. filename="tunnel.3mf",
  2127. file_path=str(src.relative_to(tmp_path)),
  2128. file_type="3mf",
  2129. file_size=src.stat().st_size,
  2130. )
  2131. db_session.add(lib)
  2132. await db_session.commit()
  2133. await db_session.refresh(lib)
  2134. return lib.id
  2135. @pytest.mark.asyncio
  2136. @pytest.mark.integration
  2137. async def test_full_slots_returns_one_row_per_project_slot(
  2138. self, async_client: AsyncClient, db_session, slice_test_setup
  2139. ):
  2140. file_id = await self._make_file(db_session, slice_test_setup["tmp_path"])
  2141. r = await async_client.get(f"/api/v1/library/files/{file_id}/filament-requirements?plate_id=1&full_slots=true")
  2142. assert r.status_code == 200, r.text
  2143. filaments = r.json()["filaments"]
  2144. assert [f["slot_id"] for f in filaments] == [1, 2, 3, 4]
  2145. # Only slot 4 prints, so only its row is selectable in the modal.
  2146. assert [f["used_in_plate"] for f in filaments] == [False, False, False, True]
  2147. # The used row keeps what the slice actually reported.
  2148. assert filaments[3]["used_grams"] == 105.9
  2149. assert filaments[3]["tray_info_idx"] == "GFL99"
  2150. @pytest.mark.asyncio
  2151. @pytest.mark.integration
  2152. async def test_the_print_path_still_gets_only_the_used_slot(
  2153. self, async_client: AsyncClient, db_session, slice_test_setup
  2154. ):
  2155. """Without the flag the response must be byte-for-byte what it was.
  2156. PrintModal drives AMS matching off this; widening it would ask the
  2157. user to load three spools the print never touches.
  2158. """
  2159. file_id = await self._make_file(db_session, slice_test_setup["tmp_path"])
  2160. r = await async_client.get(f"/api/v1/library/files/{file_id}/filament-requirements?plate_id=1")
  2161. assert r.status_code == 200, r.text
  2162. filaments = r.json()["filaments"]
  2163. assert [f["slot_id"] for f in filaments] == [4]
  2164. assert filaments[0]["used_in_plate"] is True
  2165. @pytest.mark.asyncio
  2166. @pytest.mark.integration
  2167. async def test_unsliced_sources_are_unaffected_by_the_flag(
  2168. self, async_client: AsyncClient, db_session, slice_test_setup
  2169. ):
  2170. """Those already returned the full project list; the flag must not
  2171. double-handle them or change what the modal has been getting."""
  2172. tmp_path = slice_test_setup["tmp_path"]
  2173. buf = io.BytesIO()
  2174. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  2175. zf.writestr("3D/3dmodel.model", "<model/>")
  2176. zf.writestr(
  2177. "Metadata/project_settings.config",
  2178. json.dumps({"filament_type": ["PLA", "PETG"], "filament_colour": ["#000000", "#FFFFFF"]}),
  2179. )
  2180. src = tmp_path / "library" / "files" / "raw.3mf"
  2181. src.write_bytes(buf.getvalue())
  2182. lib = LibraryFile(
  2183. filename="raw.3mf",
  2184. file_path=str(src.relative_to(tmp_path)),
  2185. file_type="3mf",
  2186. file_size=src.stat().st_size,
  2187. )
  2188. db_session.add(lib)
  2189. await db_session.commit()
  2190. await db_session.refresh(lib)
  2191. with_flag = await async_client.get(
  2192. f"/api/v1/library/files/{lib.id}/filament-requirements?plate_id=1&full_slots=true"
  2193. )
  2194. without = await async_client.get(f"/api/v1/library/files/{lib.id}/filament-requirements?plate_id=1")
  2195. assert with_flag.status_code == 200 and without.status_code == 200
  2196. assert with_flag.json()["filaments"] == without.json()["filaments"]
  2197. assert [f["slot_id"] for f in with_flag.json()["filaments"]] == [1, 2]