test_library_slice_api.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  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. async def _wait_for_job(client: AsyncClient, job_id: int, timeout: float = 5.0) -> dict:
  59. """Poll `/api/v1/slice-jobs/{id}` until the job hits a terminal state.
  60. The dispatcher runs work as an asyncio task on the same event loop, so
  61. poll-with-sleep here is enough — a few yields and the task finishes.
  62. """
  63. deadline = asyncio.get_event_loop().time() + timeout
  64. while asyncio.get_event_loop().time() < deadline:
  65. r = await client.get(f"/api/v1/slice-jobs/{job_id}")
  66. if r.status_code != 200:
  67. raise AssertionError(f"slice-jobs poll failed: {r.status_code} {r.text}")
  68. body = r.json()
  69. if body["status"] in ("completed", "failed"):
  70. return body
  71. await asyncio.sleep(0.05)
  72. raise AssertionError(f"slice job {job_id} did not finish in {timeout}s")
  73. # ---------------------------------------------------------------------------
  74. # Fixtures
  75. # ---------------------------------------------------------------------------
  76. @pytest.fixture
  77. async def slice_test_setup(db_session, tmp_path, monkeypatch):
  78. """Source LibraryFile + 3 LocalPresets + preferred_slicer=orcaslicer.
  79. ``base_dir`` is patched via ``monkeypatch`` rather than assigned and
  80. restored by hand. ``app_settings`` is a process-wide singleton, and the
  81. hand-rolled version only restored after the ``yield`` — so anything raising
  82. during setup (a commit, a refresh) left ``base_dir`` pointing at a
  83. ``tmp_path`` that pytest then deleted, and every later test in that xdist
  84. worker which reads it failed. That was the cause of intermittent failures
  85. in ``TestLibraryPathHelpers`` and ``TestArchivePlatesDesignOverrides``,
  86. which share nothing with this module but land in the same worker.
  87. """
  88. storage_dir = tmp_path / "library" / "files"
  89. storage_dir.mkdir(parents=True, exist_ok=True)
  90. src_path = storage_dir / "Cube.stl"
  91. src_path.write_bytes(b"solid Cube\nendsolid\n")
  92. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  93. src_file = LibraryFile(
  94. filename="Cube.stl",
  95. file_path=str(src_path.relative_to(tmp_path)),
  96. file_type="stl",
  97. file_size=src_path.stat().st_size,
  98. )
  99. db_session.add(src_file)
  100. presets = {}
  101. for kind in ("printer", "process", "filament"):
  102. p = LocalPreset(
  103. name=f"Test {kind}",
  104. preset_type=kind,
  105. source="orcaslicer",
  106. setting=json.dumps({"name": f"Test {kind}", "type": kind}),
  107. )
  108. db_session.add(p)
  109. presets[kind] = p
  110. db_session.add(SettingsModel(key="preferred_slicer", value="orcaslicer"))
  111. await db_session.commit()
  112. for p in presets.values():
  113. await db_session.refresh(p)
  114. await db_session.refresh(src_file)
  115. yield {
  116. "src_file_id": src_file.id,
  117. "printer_id": presets["printer"].id,
  118. "process_id": presets["process"].id,
  119. "filament_id": presets["filament"].id,
  120. "tmp_path": tmp_path,
  121. }
  122. slicer_api_module.set_shared_http_client(None)
  123. # ---------------------------------------------------------------------------
  124. # POST /library/files/{id}/slice — synchronous validation paths
  125. # ---------------------------------------------------------------------------
  126. class TestSliceValidation:
  127. @pytest.mark.asyncio
  128. @pytest.mark.integration
  129. async def test_returns_404_when_source_missing(self, async_client: AsyncClient, slice_test_setup):
  130. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  131. response = await async_client.post(
  132. "/api/v1/library/files/999999/slice",
  133. json={
  134. "printer_preset_id": slice_test_setup["printer_id"],
  135. "process_preset_id": slice_test_setup["process_id"],
  136. "filament_preset_id": slice_test_setup["filament_id"],
  137. },
  138. )
  139. assert response.status_code == 404
  140. @pytest.mark.asyncio
  141. @pytest.mark.integration
  142. async def test_returns_400_for_wrong_file_type(self, async_client: AsyncClient, db_session, slice_test_setup):
  143. gcode_path = slice_test_setup["tmp_path"] / "library" / "files" / "out.gcode"
  144. gcode_path.write_bytes(b"; gcode\n")
  145. gfile = LibraryFile(
  146. filename="out.gcode",
  147. file_path=str(gcode_path.relative_to(slice_test_setup["tmp_path"])),
  148. file_type="gcode",
  149. file_size=10,
  150. )
  151. db_session.add(gfile)
  152. await db_session.commit()
  153. await db_session.refresh(gfile)
  154. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  155. response = await async_client.post(
  156. f"/api/v1/library/files/{gfile.id}/slice",
  157. json={
  158. "printer_preset_id": slice_test_setup["printer_id"],
  159. "process_preset_id": slice_test_setup["process_id"],
  160. "filament_preset_id": slice_test_setup["filament_id"],
  161. },
  162. )
  163. assert response.status_code == 400
  164. assert "STL, 3MF, or STEP" in response.json()["detail"]
  165. # ---------------------------------------------------------------------------
  166. # POST /library/files/{id}/slice — async dispatch + bg job
  167. # ---------------------------------------------------------------------------
  168. class TestSliceLibraryFile:
  169. @pytest.mark.asyncio
  170. @pytest.mark.integration
  171. async def test_happy_path_returns_202_then_job_completes_with_library_file(
  172. self, async_client: AsyncClient, slice_test_setup
  173. ):
  174. captured: dict = {}
  175. def handler(request: httpx.Request) -> httpx.Response:
  176. captured["url"] = str(request.url)
  177. return httpx.Response(
  178. status_code=200,
  179. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  180. headers={
  181. "x-print-time-seconds": "656",
  182. "x-filament-used-g": "0.94",
  183. "x-filament-used-mm": "302.5",
  184. },
  185. )
  186. _install_mock_sidecar(handler)
  187. response = await async_client.post(
  188. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  189. json={
  190. "printer_preset_id": slice_test_setup["printer_id"],
  191. "process_preset_id": slice_test_setup["process_id"],
  192. "filament_preset_id": slice_test_setup["filament_id"],
  193. },
  194. )
  195. assert response.status_code == 202, response.text
  196. body = response.json()
  197. assert body["status"] == "pending"
  198. assert body["status_url"].startswith("/api/v1/slice-jobs/")
  199. final = await _wait_for_job(async_client, body["job_id"])
  200. assert final["status"] == "completed", final
  201. assert final["result"]["library_file_id"] != slice_test_setup["src_file_id"]
  202. assert final["result"]["print_time_seconds"] == 656
  203. assert captured["url"].endswith("/slice")
  204. @pytest.mark.asyncio
  205. @pytest.mark.integration
  206. async def test_bed_type_override_patches_process_profile(self, async_client: AsyncClient, slice_test_setup):
  207. """#1337: when SliceRequest.bed_type is set, the process JSON sent to
  208. the sidecar must carry curr_bed_type with that exact value. Without
  209. the patch, slicing high-temp filaments on a "Cool Plate" process
  210. preset fails inside the slicer CLI with "does not support filament 1"
  211. and the user has no way to switch plates from the SliceModal."""
  212. captured: dict = {}
  213. def handler(request: httpx.Request) -> httpx.Response:
  214. captured["body"] = bytes(request.content)
  215. return httpx.Response(
  216. status_code=200,
  217. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  218. headers={
  219. "x-print-time-seconds": "10",
  220. "x-filament-used-g": "0.1",
  221. "x-filament-used-mm": "1.0",
  222. },
  223. )
  224. _install_mock_sidecar(handler)
  225. response = await async_client.post(
  226. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  227. json={
  228. "printer_preset_id": slice_test_setup["printer_id"],
  229. "process_preset_id": slice_test_setup["process_id"],
  230. "filament_preset_id": slice_test_setup["filament_id"],
  231. "bed_type": "Textured PEI Plate",
  232. },
  233. )
  234. assert response.status_code == 202
  235. final = await _wait_for_job(async_client, response.json()["job_id"])
  236. assert final["status"] == "completed", final
  237. # The presetProfile part of the multipart upload now carries the
  238. # override. Searching the raw body avoids parsing the multipart by
  239. # hand — the substring is unique enough since we control the JSON
  240. # being patched.
  241. assert b'"curr_bed_type": "Textured PEI Plate"' in captured["body"], (
  242. "bed_type override must appear in the process JSON sent to the sidecar"
  243. )
  244. @pytest.mark.asyncio
  245. @pytest.mark.integration
  246. async def test_bed_type_omitted_leaves_process_profile_untouched(self, async_client: AsyncClient, slice_test_setup):
  247. """Companion to the override test: the patch must NOT fire when the
  248. client omits bed_type, so the process preset's own curr_bed_type
  249. (or absence thereof) is forwarded to the sidecar unchanged."""
  250. captured: dict = {}
  251. def handler(request: httpx.Request) -> httpx.Response:
  252. captured["body"] = bytes(request.content)
  253. return httpx.Response(
  254. status_code=200,
  255. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  256. headers={
  257. "x-print-time-seconds": "10",
  258. "x-filament-used-g": "0.1",
  259. "x-filament-used-mm": "1.0",
  260. },
  261. )
  262. _install_mock_sidecar(handler)
  263. response = await async_client.post(
  264. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  265. json={
  266. "printer_preset_id": slice_test_setup["printer_id"],
  267. "process_preset_id": slice_test_setup["process_id"],
  268. "filament_preset_id": slice_test_setup["filament_id"],
  269. },
  270. )
  271. assert response.status_code == 202
  272. final = await _wait_for_job(async_client, response.json()["job_id"])
  273. assert final["status"] == "completed", final
  274. assert b"curr_bed_type" not in captured["body"], (
  275. "bed_type must stay out of the process JSON when no override is set"
  276. )
  277. @pytest.mark.asyncio
  278. @pytest.mark.integration
  279. async def test_invalid_preset_id_surfaces_as_failed_job_with_status_400(
  280. self, async_client: AsyncClient, slice_test_setup
  281. ):
  282. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  283. response = await async_client.post(
  284. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  285. json={
  286. # Swap printer/filament — both exist but wrong preset_type.
  287. "printer_preset_id": slice_test_setup["filament_id"],
  288. "process_preset_id": slice_test_setup["process_id"],
  289. "filament_preset_id": slice_test_setup["printer_id"],
  290. },
  291. )
  292. assert response.status_code == 202
  293. final = await _wait_for_job(async_client, response.json()["job_id"])
  294. assert final["status"] == "failed"
  295. assert final["error_status"] == 400
  296. assert "preset_type" in (final["error_detail"] or "")
  297. @pytest.mark.asyncio
  298. @pytest.mark.integration
  299. async def test_unknown_preferred_slicer_fails_with_400(
  300. self, async_client: AsyncClient, db_session, slice_test_setup
  301. ):
  302. await db_session.execute(
  303. SettingsModel.__table__.update().where(SettingsModel.key == "preferred_slicer").values(value="prusaslicer")
  304. )
  305. await db_session.commit()
  306. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  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"] == "failed"
  318. assert final["error_status"] == 400
  319. assert "preferred_slicer" in (final["error_detail"] or "")
  320. @pytest.mark.asyncio
  321. @pytest.mark.integration
  322. async def test_sidecar_unreachable_fails_with_502(self, async_client: AsyncClient, slice_test_setup):
  323. def handler(_: httpx.Request) -> httpx.Response:
  324. raise httpx.ConnectError("connection refused")
  325. _install_mock_sidecar(handler)
  326. response = await async_client.post(
  327. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  328. json={
  329. "printer_preset_id": slice_test_setup["printer_id"],
  330. "process_preset_id": slice_test_setup["process_id"],
  331. "filament_preset_id": slice_test_setup["filament_id"],
  332. },
  333. )
  334. assert response.status_code == 202
  335. final = await _wait_for_job(async_client, response.json()["job_id"])
  336. assert final["status"] == "failed"
  337. assert final["error_status"] == 502
  338. assert "unreachable" in (final["error_detail"] or "").lower()
  339. @pytest.mark.asyncio
  340. @pytest.mark.integration
  341. async def test_3mf_falls_back_to_embedded_settings_on_cli_failure(
  342. self, async_client: AsyncClient, db_session, slice_test_setup
  343. ):
  344. # When the slicer CLI fails on the --load-settings path (segfault
  345. # on complex H2D models), Bambuddy retries with no profile triplet
  346. # so the CLI uses the file's embedded settings.
  347. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "complex.3mf"
  348. src_3mf_path.write_bytes(_make_3mf_with_settings({"prime_tower_brim_width": "-1"}))
  349. threemf = LibraryFile(
  350. filename="complex.3mf",
  351. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  352. file_type="3mf",
  353. file_size=src_3mf_path.stat().st_size,
  354. )
  355. db_session.add(threemf)
  356. await db_session.commit()
  357. await db_session.refresh(threemf)
  358. call_count = {"n": 0}
  359. def handler(request: httpx.Request) -> httpx.Response:
  360. call_count["n"] += 1
  361. # First call: profile triplet present → simulate CLI 5xx
  362. if call_count["n"] == 1:
  363. return httpx.Response(
  364. status_code=500,
  365. json={"message": "Failed to slice the model"},
  366. )
  367. # Retry: no profile triplet → succeed with embedded settings
  368. return httpx.Response(
  369. status_code=200,
  370. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  371. headers={
  372. "x-print-time-seconds": "100",
  373. "x-filament-used-g": "1.0",
  374. "x-filament-used-mm": "100",
  375. },
  376. )
  377. _install_mock_sidecar(handler)
  378. response = await async_client.post(
  379. f"/api/v1/library/files/{threemf.id}/slice",
  380. json={
  381. "printer_preset_id": slice_test_setup["printer_id"],
  382. "process_preset_id": slice_test_setup["process_id"],
  383. "filament_preset_id": slice_test_setup["filament_id"],
  384. },
  385. )
  386. assert response.status_code == 202
  387. final = await _wait_for_job(async_client, response.json()["job_id"])
  388. assert final["status"] == "completed", final
  389. assert final["result"]["used_embedded_settings"] is True
  390. assert call_count["n"] == 2 # primary + fallback retry
  391. @pytest.mark.asyncio
  392. @pytest.mark.integration
  393. async def test_stl_does_not_fall_back_on_cli_failure(self, async_client: AsyncClient, slice_test_setup):
  394. # STL has no embedded settings — the CLI 5xx is terminal.
  395. call_count = {"n": 0}
  396. def handler(_: httpx.Request) -> httpx.Response:
  397. call_count["n"] += 1
  398. return httpx.Response(
  399. status_code=500,
  400. json={"message": "Failed to slice the model"},
  401. )
  402. _install_mock_sidecar(handler)
  403. response = await async_client.post(
  404. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  405. json={
  406. "printer_preset_id": slice_test_setup["printer_id"],
  407. "process_preset_id": slice_test_setup["process_id"],
  408. "filament_preset_id": slice_test_setup["filament_id"],
  409. },
  410. )
  411. assert response.status_code == 202
  412. final = await _wait_for_job(async_client, response.json()["job_id"])
  413. assert final["status"] == "failed"
  414. assert final["error_status"] == 502
  415. assert call_count["n"] == 1 # No retry for STL
  416. @pytest.mark.asyncio
  417. @pytest.mark.integration
  418. async def test_3mf_input_forwarded_unmodified_to_sidecar(
  419. self, async_client: AsyncClient, db_session, slice_test_setup
  420. ):
  421. # 3MF input must be forwarded to the sidecar verbatim — every
  422. # Metadata/*.config the source carries (project_settings,
  423. # model_settings, slice_info, cut_information) is needed by the
  424. # CLI to find plate definitions and baseline config; an earlier
  425. # version of this code stripped them and caused the CLI to
  426. # silently exit immediately after "Initializing StaticPrintConfigs"
  427. # for every 3MF slice. --load-settings overrides the specific
  428. # fields the user changed; the rest comes from the embedded data.
  429. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "real.3mf"
  430. src_3mf_path.write_bytes(_make_3mf_with_settings({"prime_tower_brim_width": "-1"}))
  431. threemf = LibraryFile(
  432. filename="real.3mf",
  433. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  434. file_type="3mf",
  435. file_size=src_3mf_path.stat().st_size,
  436. )
  437. db_session.add(threemf)
  438. await db_session.commit()
  439. await db_session.refresh(threemf)
  440. captured: dict = {}
  441. def handler(request: httpx.Request) -> httpx.Response:
  442. captured["body"] = request.content
  443. return httpx.Response(
  444. status_code=200,
  445. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  446. headers={
  447. "x-print-time-seconds": "1",
  448. "x-filament-used-g": "0",
  449. "x-filament-used-mm": "0",
  450. },
  451. )
  452. _install_mock_sidecar(handler)
  453. response = await async_client.post(
  454. f"/api/v1/library/files/{threemf.id}/slice",
  455. json={
  456. "printer_preset_id": slice_test_setup["printer_id"],
  457. "process_preset_id": slice_test_setup["process_id"],
  458. "filament_preset_id": slice_test_setup["filament_id"],
  459. },
  460. )
  461. assert response.status_code == 202
  462. final = await _wait_for_job(async_client, response.json()["job_id"])
  463. assert final["status"] == "completed", final
  464. # Recover the embedded zip from the multipart body and assert ALL
  465. # the source's Metadata/*.config files are still present — the
  466. # opposite of the previous (broken) "strip everything" test.
  467. body = captured["body"]
  468. pk = body.find(b"PK\x03\x04")
  469. assert pk >= 0, "3MF body not found in multipart payload"
  470. with zipfile.ZipFile(io.BytesIO(body[pk:]), "r") as zin:
  471. names = set(zin.namelist())
  472. assert "Metadata/project_settings.config" in names
  473. assert "Metadata/model_settings.config" in names
  474. assert "Metadata/slice_info.config" in names
  475. assert "Metadata/cut_information.xml" in names
  476. assert "3D/3dmodel.model" in names
  477. @pytest.mark.asyncio
  478. @pytest.mark.integration
  479. async def test_use_embedded_settings_skips_profile_triplet(
  480. self, async_client: AsyncClient, db_session, slice_test_setup
  481. ):
  482. # "Slice as designed" (#2611): with use_embedded_settings the 3MF is
  483. # sliced on its own project_settings.config — no --load-settings — so
  484. # the sidecar request carries ONLY the model file, never the
  485. # printer/process/filament profile parts. Succeeds on the first call
  486. # (no crash-fallback), and the result is flagged used_embedded_settings.
  487. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "designed.3mf"
  488. src_3mf_path.write_bytes(_make_3mf_with_settings({"wall_loops": "5"}))
  489. threemf = LibraryFile(
  490. filename="designed.3mf",
  491. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  492. file_type="3mf",
  493. file_size=src_3mf_path.stat().st_size,
  494. )
  495. db_session.add(threemf)
  496. await db_session.commit()
  497. await db_session.refresh(threemf)
  498. captured: dict = {}
  499. call_count = {"n": 0}
  500. def handler(request: httpx.Request) -> httpx.Response:
  501. call_count["n"] += 1
  502. captured["body"] = request.content
  503. return httpx.Response(
  504. status_code=200,
  505. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  506. headers={
  507. "x-print-time-seconds": "100",
  508. "x-filament-used-g": "1.0",
  509. "x-filament-used-mm": "100",
  510. },
  511. )
  512. _install_mock_sidecar(handler)
  513. response = await async_client.post(
  514. f"/api/v1/library/files/{threemf.id}/slice",
  515. json={
  516. "printer_preset_id": slice_test_setup["printer_id"],
  517. "process_preset_id": slice_test_setup["process_id"],
  518. "filament_preset_id": slice_test_setup["filament_id"],
  519. "use_embedded_settings": True,
  520. },
  521. )
  522. assert response.status_code == 202
  523. final = await _wait_for_job(async_client, response.json()["job_id"])
  524. assert final["status"] == "completed", final
  525. assert final["result"]["used_embedded_settings"] is True
  526. assert call_count["n"] == 1 # embedded path taken directly, no fallback retry
  527. # The multipart body must NOT carry any profile part — that is the
  528. # whole point of the mode. Their presence would mean --load-settings
  529. # ran and overrode the designer's embedded settings.
  530. body = captured["body"]
  531. assert b"printerProfile" not in body
  532. assert b"presetProfile" not in body
  533. assert b"filamentProfile" not in body
  534. @pytest.mark.asyncio
  535. @pytest.mark.integration
  536. async def test_use_embedded_settings_ignored_for_stl(self, async_client: AsyncClient, slice_test_setup):
  537. # An STL has no embedded project settings to honour, so the flag is a
  538. # no-op: the normal profile path runs and the triplet is forwarded.
  539. captured: dict = {}
  540. def handler(request: httpx.Request) -> httpx.Response:
  541. captured["body"] = request.content
  542. return httpx.Response(
  543. status_code=200,
  544. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  545. headers={
  546. "x-print-time-seconds": "1",
  547. "x-filament-used-g": "0",
  548. "x-filament-used-mm": "0",
  549. },
  550. )
  551. _install_mock_sidecar(handler)
  552. response = await async_client.post(
  553. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  554. json={
  555. "printer_preset_id": slice_test_setup["printer_id"],
  556. "process_preset_id": slice_test_setup["process_id"],
  557. "filament_preset_id": slice_test_setup["filament_id"],
  558. "use_embedded_settings": True,
  559. },
  560. )
  561. assert response.status_code == 202
  562. final = await _wait_for_job(async_client, response.json()["job_id"])
  563. assert final["status"] == "completed", final
  564. assert final["result"]["used_embedded_settings"] is False
  565. assert b"printerProfile" in captured["body"] # profile path still ran
  566. # ---------------------------------------------------------------------------
  567. # GET /slice-jobs/{id}
  568. # ---------------------------------------------------------------------------
  569. class TestSliceJobs:
  570. @pytest.mark.asyncio
  571. @pytest.mark.integration
  572. async def test_unknown_job_returns_404(self, async_client: AsyncClient):
  573. # Sweep dispatcher state so a fresh ID is unknown.
  574. slice_dispatch._jobs.clear()
  575. r = await async_client.get("/api/v1/slice-jobs/999999")
  576. assert r.status_code == 404
  577. # ---------------------------------------------------------------------------
  578. # POST /archives/{id}/slice — re-sliced archive reflects the target printer
  579. # ---------------------------------------------------------------------------
  580. def _make_sliced_3mf(printer_model_id: str, bed_type: str | None = None) -> bytes:
  581. """A minimal sliced-output 3MF that embeds a printer_model_id in
  582. slice_info.config, the way a real Bambu Studio / OrcaSlicer export does.
  583. ThreeMFParser reads this into metadata['sliced_for_model']. When
  584. ``bed_type`` is set, also embed ``curr_bed_type`` so the parser surfaces
  585. ``metadata['bed_type']`` — needed for the bed-type lift assertion in
  586. TestSliceArchiveReslicedBedType."""
  587. extra_meta = f"<metadata key='curr_bed_type' value='{bed_type}'/>" if bed_type else ""
  588. buf = io.BytesIO()
  589. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  590. zf.writestr("3D/3dmodel.model", "<model/>")
  591. zf.writestr(
  592. "Metadata/slice_info.config",
  593. (
  594. "<config><plate>"
  595. f"<metadata key='printer_model_id' value='{printer_model_id}'/>"
  596. f"{extra_meta}"
  597. "</plate></config>"
  598. ),
  599. )
  600. return buf.getvalue()
  601. class TestCrossClassSliceAllLoop:
  602. """#1493: when the user picks "Slice all plates" on a cross-class source
  603. (X1C → H2D), Bambuddy must NOT send a single ``--slice 0 --arrange 1``
  604. call — that consolidates every plate's objects onto one bed via BS's
  605. project-wide arrange. Instead it loops per plate (``plate=N, arrange=true``)
  606. and merges the N single-plate outputs into one multi-plate 3MF locally.
  607. This test mocks the sidecar to assert (a) N calls happen, one per plate,
  608. each with arrange=true, and (b) the resulting archive's stored 3MF
  609. contains plate_1..plate_N.gcode entries."""
  610. @staticmethod
  611. def _make_multi_plate_x1c_source(plate_count: int = 3) -> bytes:
  612. """Source 3MF: X1C-stamped, N plates declared via model_settings."""
  613. plate_blocks = "\n".join(
  614. f'<plate><metadata key="plater_id" value="{i}"/></plate>' for i in range(1, plate_count + 1)
  615. )
  616. buf = io.BytesIO()
  617. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  618. zf.writestr("3D/3dmodel.model", "<model/>")
  619. zf.writestr(
  620. "Metadata/project_settings.config",
  621. json.dumps({"printer_model": "Bambu Lab X1 Carbon"}),
  622. )
  623. zf.writestr(
  624. "Metadata/model_settings.config",
  625. f"<?xml version='1.0'?>\n<config>\n{plate_blocks}\n</config>\n",
  626. )
  627. return buf.getvalue()
  628. @staticmethod
  629. def _make_single_plate_sliced_output(plate_num: int) -> bytes:
  630. """Mock per-plate output: looks like what BS CLI returns for
  631. --slice N. Carries an H2D project_settings (target), a one-line
  632. slice_info <plate> block, and a per-plate gcode + thumbnail."""
  633. buf = io.BytesIO()
  634. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  635. zf.writestr("3D/3dmodel.model", "<model/>")
  636. zf.writestr(
  637. "Metadata/project_settings.config",
  638. json.dumps({"printer_model": "Bambu Lab H2D"}),
  639. )
  640. zf.writestr("Metadata/model_settings.config", "<config/>")
  641. zf.writestr(
  642. "Metadata/slice_info.config",
  643. f"<config><plate><metadata key='index' value='{plate_num}'/>"
  644. f"<metadata key='printer_model_id' value='O1D'/></plate></config>",
  645. )
  646. zf.writestr(f"Metadata/plate_{plate_num}.gcode", f"G{plate_num}".encode())
  647. zf.writestr(f"Metadata/plate_{plate_num}.gcode.md5", b"deadbeef")
  648. zf.writestr(f"Metadata/plate_{plate_num}.json", b"{}")
  649. zf.writestr(f"Metadata/plate_{plate_num}.png", f"P{plate_num}".encode())
  650. return buf.getvalue()
  651. @pytest.mark.asyncio
  652. @pytest.mark.integration
  653. async def test_loops_per_plate_when_cross_class_with_plate_zero(
  654. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  655. ):
  656. from backend.app.models.archive import PrintArchive
  657. tmp_path = slice_test_setup["tmp_path"]
  658. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  659. src_dir = tmp_path / "archives" / "src"
  660. src_dir.mkdir(parents=True, exist_ok=True)
  661. src_3mf = src_dir / "mewtwo.3mf"
  662. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=3))
  663. printer = await printer_factory()
  664. source = await archive_factory(
  665. printer.id,
  666. filename="mewtwo.3mf",
  667. file_path=str(src_3mf.relative_to(tmp_path)),
  668. sliced_for_model="X1C",
  669. with_run=False,
  670. )
  671. # H2D target preset — the cross-class detector reads the
  672. # ``printer_model`` field off the resolved JSON.
  673. h2d = LocalPreset(
  674. name="# Bambu Lab H2D 0.4 nozzle",
  675. preset_type="printer",
  676. source="orcaslicer",
  677. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  678. )
  679. db_session.add(h2d)
  680. await db_session.commit()
  681. await db_session.refresh(h2d)
  682. # Mock sidecar: capture every request and respond with that
  683. # plate's single-plate output. We expect one request per plate
  684. # in the source (3 here).
  685. captured_requests: list[dict] = []
  686. def handler(request: httpx.Request) -> httpx.Response:
  687. # Multipart bodies aren't trivially parseable here; pull
  688. # the plate field by string search since the helper sends
  689. # ``name="plate"`` immediately followed by the value.
  690. body = request.content
  691. plate = None
  692. marker = b'name="plate"\r\n\r\n'
  693. idx = body.find(marker)
  694. if idx != -1:
  695. # Find the next CRLF after the value start.
  696. start = idx + len(marker)
  697. end = body.find(b"\r\n", start)
  698. try:
  699. plate = int(body[start:end].decode("utf-8"))
  700. except (UnicodeDecodeError, ValueError):
  701. plate = None
  702. arrange_in_body = b'name="arrange"' in body
  703. captured_requests.append({"plate": plate, "arrange": arrange_in_body})
  704. return httpx.Response(
  705. status_code=200,
  706. content=self._make_single_plate_sliced_output(plate or 1),
  707. headers={
  708. "x-print-time-seconds": "600",
  709. "x-filament-used-g": "5.0",
  710. "x-filament-used-mm": "1600.0",
  711. },
  712. )
  713. _install_mock_sidecar(handler)
  714. # plate=0 + cross-class triplet → backend should enter the
  715. # per-plate loop, slice each of the 3 plates with arrange=True,
  716. # and merge into one archive.
  717. resp = await async_client.post(
  718. f"/api/v1/archives/{source.id}/slice",
  719. json={
  720. "printer_preset": {"source": "local", "id": str(h2d.id)},
  721. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  722. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  723. "plate": 0,
  724. },
  725. )
  726. assert resp.status_code == 202, resp.text
  727. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  728. assert final["status"] == "completed", final
  729. # Exactly one sidecar call per plate, in plate order. The
  730. # ``--arrange 1`` flag travels with every per-plate sub-slice
  731. # (it's what fixes the cross-class boundary error).
  732. plates_called = [c["plate"] for c in captured_requests]
  733. arrange_used = [c["arrange"] for c in captured_requests]
  734. assert plates_called == [1, 2, 3], plates_called
  735. assert all(arrange_used), arrange_used
  736. # The merged archive has plate_1..plate_3.gcode inside its one
  737. # output 3MF (single Bambuddy archive, three plates).
  738. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  739. archive_path = tmp_path / new_archive.file_path
  740. with zipfile.ZipFile(archive_path, "r") as zf:
  741. entries = set(zf.namelist())
  742. assert "Metadata/plate_1.gcode" in entries
  743. assert "Metadata/plate_2.gcode" in entries
  744. assert "Metadata/plate_3.gcode" in entries
  745. # Per-plate-result totals are summed onto the merged archive.
  746. assert new_archive.print_time_seconds == 600 * 3
  747. assert new_archive.filament_used_grams == pytest.approx(5.0 * 3)
  748. class TestSliceArchiveResliceModel:
  749. """Re-slicing an archive for a different printer must stamp the new
  750. archive with the printer it was sliced FOR, not the source's printer."""
  751. @pytest.mark.asyncio
  752. @pytest.mark.integration
  753. async def test_reslice_uses_target_model_not_source_model(
  754. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  755. ):
  756. from backend.app.models.archive import PrintArchive
  757. tmp_path = slice_test_setup["tmp_path"]
  758. # archive_dir is a static path off the real data dir; point it under
  759. # base_dir (= tmp_path) so the new archive's file resolves there.
  760. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  761. # Source archive: a 3MF that was sliced for an X1C.
  762. src_dir = tmp_path / "archives" / "src"
  763. src_dir.mkdir(parents=True, exist_ok=True)
  764. src_3mf = src_dir / "cube.3mf"
  765. src_3mf.write_bytes(_make_3mf_with_settings())
  766. printer = await printer_factory()
  767. source = await archive_factory(
  768. printer.id,
  769. filename="cube.3mf",
  770. file_path=str(src_3mf.relative_to(tmp_path)),
  771. sliced_for_model="X1C",
  772. with_run=False,
  773. )
  774. source_id = source.id
  775. # The slicer returns a 3MF whose embedded printer_model_id is O1D (H2D).
  776. def handler(request: httpx.Request) -> httpx.Response:
  777. return httpx.Response(
  778. status_code=200,
  779. content=_make_sliced_3mf("O1D"),
  780. headers={
  781. "x-print-time-seconds": "600",
  782. "x-filament-used-g": "5.0",
  783. "x-filament-used-mm": "1600.0",
  784. },
  785. )
  786. _install_mock_sidecar(handler)
  787. resp = await async_client.post(
  788. f"/api/v1/archives/{source_id}/slice",
  789. json={
  790. "printer_preset_id": slice_test_setup["printer_id"],
  791. "process_preset_id": slice_test_setup["process_id"],
  792. "filament_preset_id": slice_test_setup["filament_id"],
  793. },
  794. )
  795. assert resp.status_code == 202, resp.text
  796. final = await _wait_for_job(async_client, resp.json()["job_id"])
  797. assert final["status"] == "completed", final
  798. new_id = final["result"]["archive_id"]
  799. assert new_id != source_id
  800. new_archive = await db_session.get(PrintArchive, new_id)
  801. # The fix: the re-sliced archive reflects H2D — the printer it was
  802. # sliced for — instead of inheriting X1C from the source archive.
  803. assert new_archive.sliced_for_model == "H2D"
  804. # Source archive is untouched.
  805. source_reloaded = await db_session.get(PrintArchive, source_id)
  806. assert source_reloaded.sliced_for_model == "X1C"
  807. @pytest.mark.asyncio
  808. @pytest.mark.integration
  809. async def test_cross_model_reslice_drops_source_printer_id(
  810. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  811. ):
  812. """A cross-model re-slice (source's X1C → target's H2D) must not carry
  813. over ``source.printer_id``. The archive card and reprint modal both
  814. read ``printer_id`` first and only fall back to ``sliced_for_model``
  815. when it's None, so leaving the inherited id makes the H2D-sliced card
  816. display the source's X1C printer name (the "Workshop H2C" bug)."""
  817. from backend.app.models.archive import PrintArchive
  818. tmp_path = slice_test_setup["tmp_path"]
  819. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  820. src_dir = tmp_path / "archives" / "src"
  821. src_dir.mkdir(parents=True, exist_ok=True)
  822. src_3mf = src_dir / "cube.3mf"
  823. src_3mf.write_bytes(_make_3mf_with_settings())
  824. source_printer = await printer_factory()
  825. source = await archive_factory(
  826. source_printer.id,
  827. filename="cube.3mf",
  828. file_path=str(src_3mf.relative_to(tmp_path)),
  829. sliced_for_model="X1C",
  830. with_run=False,
  831. )
  832. source_id = source.id
  833. source_printer_id = source_printer.id
  834. def handler(request: httpx.Request) -> httpx.Response:
  835. return httpx.Response(
  836. status_code=200,
  837. content=_make_sliced_3mf("O1D"), # H2D
  838. headers={
  839. "x-print-time-seconds": "600",
  840. "x-filament-used-g": "5.0",
  841. "x-filament-used-mm": "1600.0",
  842. },
  843. )
  844. _install_mock_sidecar(handler)
  845. resp = await async_client.post(
  846. f"/api/v1/archives/{source_id}/slice",
  847. json={
  848. "printer_preset_id": slice_test_setup["printer_id"],
  849. "process_preset_id": slice_test_setup["process_id"],
  850. "filament_preset_id": slice_test_setup["filament_id"],
  851. },
  852. )
  853. assert resp.status_code == 202, resp.text
  854. final = await _wait_for_job(async_client, resp.json()["job_id"])
  855. assert final["status"] == "completed", final
  856. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  857. assert new_archive.sliced_for_model == "H2D"
  858. # Card / reprint modal will now fall back to the sliced_for_model
  859. # badge instead of showing the source printer's name.
  860. assert new_archive.printer_id is None
  861. # Source untouched: still bound to its original printer.
  862. source_reloaded = await db_session.get(PrintArchive, source_id)
  863. assert source_reloaded.printer_id == source_printer_id
  864. @pytest.mark.asyncio
  865. @pytest.mark.integration
  866. async def test_same_model_reslice_preserves_source_printer_id(
  867. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  868. ):
  869. """Same-model re-slice (X1C → X1C, e.g. just swapped a process preset)
  870. keeps ``printer_id`` so the reprint modal pre-selects the original
  871. printer. Only cross-model re-slices null it out."""
  872. from backend.app.models.archive import PrintArchive
  873. tmp_path = slice_test_setup["tmp_path"]
  874. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  875. src_dir = tmp_path / "archives" / "src"
  876. src_dir.mkdir(parents=True, exist_ok=True)
  877. src_3mf = src_dir / "cube.3mf"
  878. src_3mf.write_bytes(_make_3mf_with_settings())
  879. source_printer = await printer_factory()
  880. source = await archive_factory(
  881. source_printer.id,
  882. filename="cube.3mf",
  883. file_path=str(src_3mf.relative_to(tmp_path)),
  884. sliced_for_model="X1C",
  885. with_run=False,
  886. )
  887. def handler(request: httpx.Request) -> httpx.Response:
  888. return httpx.Response(
  889. status_code=200,
  890. content=_make_sliced_3mf("C11"), # X1C — same model as source
  891. headers={
  892. "x-print-time-seconds": "600",
  893. "x-filament-used-g": "5.0",
  894. "x-filament-used-mm": "1600.0",
  895. },
  896. )
  897. _install_mock_sidecar(handler)
  898. resp = await async_client.post(
  899. f"/api/v1/archives/{source.id}/slice",
  900. json={
  901. "printer_preset_id": slice_test_setup["printer_id"],
  902. "process_preset_id": slice_test_setup["process_id"],
  903. "filament_preset_id": slice_test_setup["filament_id"],
  904. },
  905. )
  906. assert resp.status_code == 202, resp.text
  907. final = await _wait_for_job(async_client, resp.json()["job_id"])
  908. assert final["status"] == "completed", final
  909. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  910. assert new_archive.sliced_for_model == "X1C"
  911. # Same-model: keep the source's printer assignment so reprint pre-selects it.
  912. assert new_archive.printer_id == source_printer.id
  913. @pytest.mark.asyncio
  914. @pytest.mark.integration
  915. async def test_reslice_with_unknown_source_model_preserves_printer_id(
  916. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  917. ):
  918. """When ``source.sliced_for_model`` is None (older archive that
  919. predates that column being populated), the backend can't tell whether
  920. this is a cross-model re-slice. Fail open and preserve ``printer_id``
  921. rather than spuriously nulling it — current pre-fix behaviour, kept
  922. as a deliberate edge case."""
  923. from backend.app.models.archive import PrintArchive
  924. tmp_path = slice_test_setup["tmp_path"]
  925. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  926. src_dir = tmp_path / "archives" / "src"
  927. src_dir.mkdir(parents=True, exist_ok=True)
  928. src_3mf = src_dir / "cube.3mf"
  929. src_3mf.write_bytes(_make_3mf_with_settings())
  930. source_printer = await printer_factory()
  931. source = await archive_factory(
  932. source_printer.id,
  933. filename="cube.3mf",
  934. file_path=str(src_3mf.relative_to(tmp_path)),
  935. sliced_for_model=None,
  936. with_run=False,
  937. )
  938. def handler(request: httpx.Request) -> httpx.Response:
  939. return httpx.Response(
  940. status_code=200,
  941. content=_make_sliced_3mf("O1D"),
  942. headers={
  943. "x-print-time-seconds": "600",
  944. "x-filament-used-g": "5.0",
  945. "x-filament-used-mm": "1600.0",
  946. },
  947. )
  948. _install_mock_sidecar(handler)
  949. resp = await async_client.post(
  950. f"/api/v1/archives/{source.id}/slice",
  951. json={
  952. "printer_preset_id": slice_test_setup["printer_id"],
  953. "process_preset_id": slice_test_setup["process_id"],
  954. "filament_preset_id": slice_test_setup["filament_id"],
  955. },
  956. )
  957. assert resp.status_code == 202, resp.text
  958. final = await _wait_for_job(async_client, resp.json()["job_id"])
  959. assert final["status"] == "completed", final
  960. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  961. # Insufficient info to decide cross-model → preserve printer_id.
  962. assert new_archive.printer_id == source_printer.id
  963. class TestSliceArchiveReslicedThumbnail:
  964. """#1493 follow-up: the re-sliced archive's cover image preference order is
  965. source's per-plate render > sliced output's per-plate render >
  966. Auxiliaries marketing thumbnail. BS CLI rarely writes a fresh
  967. ``Metadata/plate_N.png`` on the sliced output, so the source's render
  968. of the same plate (closer to what's actually printing) wins over the
  969. project-wide marketing image."""
  970. @staticmethod
  971. def _make_source_with_plate_png(plate_png_bytes: bytes) -> bytes:
  972. buf = io.BytesIO()
  973. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  974. zf.writestr("3D/3dmodel.model", "<model/>")
  975. zf.writestr("Metadata/plate_1.png", plate_png_bytes)
  976. # Project-wide marketing image — the unwanted fallback target.
  977. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"COVER_ART")
  978. return buf.getvalue()
  979. @pytest.mark.asyncio
  980. @pytest.mark.integration
  981. async def test_uses_source_plate_png_when_sliced_output_lacks_one(
  982. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  983. ):
  984. """Sliced output has no per-plate PNG (typical of BS CLI output
  985. with --arrange). The source's plate_1.png must win over the
  986. sliced output's Auxiliaries fallback."""
  987. from backend.app.models.archive import PrintArchive
  988. tmp_path = slice_test_setup["tmp_path"]
  989. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  990. # Source has its own plate_1.png AND a project-wide cover.
  991. source_plate_marker = b"SOURCE_PLATE_RENDER"
  992. src_dir = tmp_path / "archives" / "src"
  993. src_dir.mkdir(parents=True, exist_ok=True)
  994. src_3mf = src_dir / "cube.3mf"
  995. src_3mf.write_bytes(self._make_source_with_plate_png(source_plate_marker))
  996. printer = await printer_factory()
  997. source = await archive_factory(
  998. printer.id,
  999. filename="cube.3mf",
  1000. file_path=str(src_3mf.relative_to(tmp_path)),
  1001. sliced_for_model="X1C",
  1002. with_run=False,
  1003. )
  1004. # Mock slicer returns a 3MF with NO Metadata/plate_1.png — only
  1005. # the Auxiliaries cover, mimicking BS CLI output with --arrange.
  1006. def handler(request: httpx.Request) -> httpx.Response:
  1007. sliced_buf = io.BytesIO()
  1008. with zipfile.ZipFile(sliced_buf, "w") as zf:
  1009. zf.writestr("3D/3dmodel.model", "<model/>")
  1010. zf.writestr("Metadata/slice_info.config", "<config/>")
  1011. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"SLICED_COVER_ART")
  1012. return httpx.Response(
  1013. status_code=200,
  1014. content=sliced_buf.getvalue(),
  1015. headers={"x-print-time-seconds": "60", "x-filament-used-g": "1", "x-filament-used-mm": "100"},
  1016. )
  1017. _install_mock_sidecar(handler)
  1018. resp = await async_client.post(
  1019. f"/api/v1/archives/{source.id}/slice",
  1020. json={
  1021. "printer_preset_id": slice_test_setup["printer_id"],
  1022. "process_preset_id": slice_test_setup["process_id"],
  1023. "filament_preset_id": slice_test_setup["filament_id"],
  1024. },
  1025. )
  1026. assert resp.status_code == 202, resp.text
  1027. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1028. assert final["status"] == "completed", final
  1029. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1030. assert new.thumbnail_path is not None
  1031. thumb_full = tmp_path / new.thumbnail_path
  1032. assert thumb_full.read_bytes() == source_plate_marker, (
  1033. "Re-sliced archive's thumbnail should be the source's per-plate render, not the Auxiliaries cover art."
  1034. )
  1035. @pytest.mark.asyncio
  1036. @pytest.mark.integration
  1037. async def test_falls_back_to_auxiliaries_when_source_lacks_plate_png(
  1038. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1039. ):
  1040. """When the source has no per-plate render (unsliced library upload),
  1041. the Auxiliaries marketing image from the sliced output is the
  1042. next-best preview — better than no card thumbnail at all."""
  1043. from backend.app.models.archive import PrintArchive
  1044. tmp_path = slice_test_setup["tmp_path"]
  1045. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1046. # Source has no Metadata/plate_1.png at all.
  1047. bare_buf = io.BytesIO()
  1048. with zipfile.ZipFile(bare_buf, "w") as zf:
  1049. zf.writestr("3D/3dmodel.model", "<model/>")
  1050. src_dir = tmp_path / "archives" / "src"
  1051. src_dir.mkdir(parents=True, exist_ok=True)
  1052. src_3mf = src_dir / "bare.3mf"
  1053. src_3mf.write_bytes(bare_buf.getvalue())
  1054. printer = await printer_factory()
  1055. source = await archive_factory(
  1056. printer.id,
  1057. filename="bare.3mf",
  1058. file_path=str(src_3mf.relative_to(tmp_path)),
  1059. sliced_for_model="X1C",
  1060. with_run=False,
  1061. )
  1062. def handler(request: httpx.Request) -> httpx.Response:
  1063. sliced_buf = io.BytesIO()
  1064. with zipfile.ZipFile(sliced_buf, "w") as zf:
  1065. zf.writestr("3D/3dmodel.model", "<model/>")
  1066. zf.writestr("Metadata/slice_info.config", "<config/>")
  1067. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"COVER_ART_FALLBACK")
  1068. return httpx.Response(
  1069. status_code=200,
  1070. content=sliced_buf.getvalue(),
  1071. headers={"x-print-time-seconds": "60", "x-filament-used-g": "1", "x-filament-used-mm": "100"},
  1072. )
  1073. _install_mock_sidecar(handler)
  1074. resp = await async_client.post(
  1075. f"/api/v1/archives/{source.id}/slice",
  1076. json={
  1077. "printer_preset_id": slice_test_setup["printer_id"],
  1078. "process_preset_id": slice_test_setup["process_id"],
  1079. "filament_preset_id": slice_test_setup["filament_id"],
  1080. },
  1081. )
  1082. assert resp.status_code == 202, resp.text
  1083. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1084. assert final["status"] == "completed", final
  1085. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1086. assert new.thumbnail_path is not None
  1087. thumb_full = tmp_path / new.thumbnail_path
  1088. assert thumb_full.read_bytes() == b"COVER_ART_FALLBACK"
  1089. class TestSliceArchiveReslicedBedType:
  1090. """#1493 follow-up: the re-sliced archive's ``bed_type`` column must be
  1091. set from the produced 3MF's ``curr_bed_type`` so the frontend's archive
  1092. card shows the right build-plate badge (the card reads the column, not
  1093. extra_data, so the value was previously invisible after a re-slice)."""
  1094. @pytest.mark.asyncio
  1095. @pytest.mark.integration
  1096. async def test_bed_type_lifted_from_sliced_output(
  1097. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1098. ):
  1099. from backend.app.models.archive import PrintArchive
  1100. tmp_path = slice_test_setup["tmp_path"]
  1101. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1102. src_dir = tmp_path / "archives" / "src"
  1103. src_dir.mkdir(parents=True, exist_ok=True)
  1104. src_3mf = src_dir / "cube.3mf"
  1105. src_3mf.write_bytes(_make_3mf_with_settings())
  1106. printer = await printer_factory()
  1107. source = await archive_factory(
  1108. printer.id,
  1109. filename="cube.3mf",
  1110. file_path=str(src_3mf.relative_to(tmp_path)),
  1111. sliced_for_model="X1C",
  1112. bed_type="Cool Plate",
  1113. with_run=False,
  1114. )
  1115. # Mock slicer: produced 3MF declares a different plate type than
  1116. # the source archive's ``Cool Plate``. The new column must reflect
  1117. # the slicer's value (the user picked a different plate in the
  1118. # SliceModal) instead of inheriting the source's.
  1119. def handler(request: httpx.Request) -> httpx.Response:
  1120. return httpx.Response(
  1121. status_code=200,
  1122. content=_make_sliced_3mf("O1D", bed_type="Textured PEI Plate"),
  1123. headers={
  1124. "x-print-time-seconds": "600",
  1125. "x-filament-used-g": "5.0",
  1126. "x-filament-used-mm": "1600.0",
  1127. },
  1128. )
  1129. _install_mock_sidecar(handler)
  1130. resp = await async_client.post(
  1131. f"/api/v1/archives/{source.id}/slice",
  1132. json={
  1133. "printer_preset_id": slice_test_setup["printer_id"],
  1134. "process_preset_id": slice_test_setup["process_id"],
  1135. "filament_preset_id": slice_test_setup["filament_id"],
  1136. },
  1137. )
  1138. assert resp.status_code == 202, resp.text
  1139. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1140. assert final["status"] == "completed", final
  1141. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1142. assert new.bed_type == "Textured PEI Plate"
  1143. @pytest.mark.asyncio
  1144. @pytest.mark.integration
  1145. async def test_bed_type_falls_back_to_source_when_missing_from_output(
  1146. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1147. ):
  1148. """An older sidecar or sparse slice profile may produce a 3MF without
  1149. ``curr_bed_type``. The source archive's ``bed_type`` is the right
  1150. default in that case — better than leaving the badge blank."""
  1151. from backend.app.models.archive import PrintArchive
  1152. tmp_path = slice_test_setup["tmp_path"]
  1153. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1154. src_dir = tmp_path / "archives" / "src"
  1155. src_dir.mkdir(parents=True, exist_ok=True)
  1156. src_3mf = src_dir / "cube.3mf"
  1157. src_3mf.write_bytes(_make_3mf_with_settings())
  1158. printer = await printer_factory()
  1159. source = await archive_factory(
  1160. printer.id,
  1161. filename="cube.3mf",
  1162. file_path=str(src_3mf.relative_to(tmp_path)),
  1163. sliced_for_model="X1C",
  1164. bed_type="Cool Plate",
  1165. with_run=False,
  1166. )
  1167. def handler(request: httpx.Request) -> httpx.Response:
  1168. return httpx.Response(
  1169. status_code=200,
  1170. # No bed_type embedded — simulates a sidecar that drops it.
  1171. content=_make_sliced_3mf("O1D"),
  1172. headers={
  1173. "x-print-time-seconds": "600",
  1174. "x-filament-used-g": "5.0",
  1175. "x-filament-used-mm": "1600.0",
  1176. },
  1177. )
  1178. _install_mock_sidecar(handler)
  1179. resp = await async_client.post(
  1180. f"/api/v1/archives/{source.id}/slice",
  1181. json={
  1182. "printer_preset_id": slice_test_setup["printer_id"],
  1183. "process_preset_id": slice_test_setup["process_id"],
  1184. "filament_preset_id": slice_test_setup["filament_id"],
  1185. },
  1186. )
  1187. assert resp.status_code == 202, resp.text
  1188. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1189. assert final["status"] == "completed", final
  1190. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1191. assert new.bed_type == "Cool Plate"
  1192. # ---------------------------------------------------------------------------
  1193. # Slicer content rejections surface instead of silently falling back
  1194. # ---------------------------------------------------------------------------
  1195. class TestSlicerRejectionMessage:
  1196. """_slicer_rejection_message distinguishes a real slicer content rejection
  1197. (surface it to the user) from a CLI crash (fall back to embedded)."""
  1198. def test_extracts_bed_boundary_reason(self):
  1199. text = (
  1200. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1201. "Some objects are located over the boundary of the heated bed.: "
  1202. "Slicer process failed (exit code 204)\nstdout: trace ..."
  1203. )
  1204. assert _slicer_rejection_message(text) == "Some objects are located over the boundary of the heated bed."
  1205. def test_extracts_filament_temp_reason(self):
  1206. text = (
  1207. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1208. "The temperature difference of the filaments used is too large.: "
  1209. "Slicer process failed (exit code 194)"
  1210. )
  1211. assert _slicer_rejection_message(text) == "The temperature difference of the filaments used is too large."
  1212. def test_generic_cli_failure_is_not_a_rejection(self):
  1213. # The #1201 CLI-crash signature carries no slicer error_string, so it
  1214. # must still fall through to the embedded-settings fallback.
  1215. assert _slicer_rejection_message("Slicer CLI failed (500): Failed to slice the model") is None
  1216. def test_empty_or_unrelated_text(self):
  1217. assert _slicer_rejection_message("") is None
  1218. assert _slicer_rejection_message("Slicer sidecar unreachable: connection reset") is None
  1219. def test_replaces_input_preset_invalid_placeholder_with_cli_error_line(self):
  1220. # #1851: the CLI emits its catch-all "input preset file is invalid"
  1221. # placeholder for every -5 exit, including real preset-vs-printer
  1222. # compatibility rejections. The actual diagnostic only appears in the
  1223. # stdout `[error] run NNNN:` line; the function must prefer that.
  1224. text = (
  1225. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1226. "The input preset file is invalid and can not be parsed.: "
  1227. "Slicer process failed (exit code 251)\n"
  1228. "stdout: [2026-06-29 04:12:11.952784] [trace] Initializing StaticPrintConfigs\n"
  1229. "[2026-06-29 04:12:12.175810] [error] run 3008: filament preset "
  1230. "Generic PLA @BBL H2C (slot 1) is not compatible with printer "
  1231. "Bambu Lab A1 0.4 nozzle.\n"
  1232. "run found error, return -5, exit..."
  1233. )
  1234. assert (
  1235. _slicer_rejection_message(text) == "filament preset Generic PLA @BBL H2C (slot 1) is not compatible with "
  1236. "printer Bambu Lab A1 0.4 nozzle."
  1237. )
  1238. def test_keeps_meaningful_reason_even_when_cli_error_line_present(self):
  1239. # When the headline error_string is already a useful reason (here:
  1240. # the bed-boundary rejection), don't override it with a generic
  1241. # `[error]` line that may just be the same message restated. Avoids
  1242. # double-text duplication in the user-facing detail.
  1243. text = (
  1244. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1245. "Some objects are located over the boundary of the heated bed.: "
  1246. "Slicer process failed (exit code 204)\n"
  1247. "stdout: [error] some unrelated stdout chatter"
  1248. )
  1249. assert _slicer_rejection_message(text) == "Some objects are located over the boundary of the heated bed."
  1250. def test_cli_error_line_without_run_prefix(self):
  1251. # The CLI sometimes logs `[error] <msg>` without the `run NNNN:`
  1252. # prefix (different code paths). The regex must still pick it up.
  1253. text = (
  1254. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1255. "The input preset file is invalid and can not be parsed.: "
  1256. "Slicer process failed (exit code 251)\n"
  1257. "stdout: [2026-06-29 12:00:00.000000] [error] Configuration parse failed: missing key 'printer_settings_id'"
  1258. )
  1259. assert _slicer_rejection_message(text) == "Configuration parse failed: missing key 'printer_settings_id'"
  1260. class TestSliceSlicerRejection:
  1261. @pytest.mark.asyncio
  1262. @pytest.mark.integration
  1263. async def test_3mf_surfaces_slicer_rejection_instead_of_falling_back(
  1264. self, async_client: AsyncClient, db_session, slice_test_setup
  1265. ):
  1266. """A real slicer content rejection (e.g. re-slicing for a printer with
  1267. a smaller bed) must surface as a 400 — not silently fall back to the
  1268. source 3MF's embedded settings, which would re-slice for the original
  1269. printer and hide the problem."""
  1270. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "toobig.3mf"
  1271. src_3mf_path.write_bytes(_make_3mf_with_settings())
  1272. threemf = LibraryFile(
  1273. filename="toobig.3mf",
  1274. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  1275. file_type="3mf",
  1276. file_size=src_3mf_path.stat().st_size,
  1277. )
  1278. db_session.add(threemf)
  1279. await db_session.commit()
  1280. await db_session.refresh(threemf)
  1281. call_count = {"n": 0}
  1282. def handler(request: httpx.Request) -> httpx.Response:
  1283. call_count["n"] += 1
  1284. return httpx.Response(
  1285. status_code=500,
  1286. json={
  1287. "message": (
  1288. "Slicing failed with error from slicer: Some objects are "
  1289. "located over the boundary of the heated bed."
  1290. ),
  1291. "details": "Slicer process failed (exit code 204)",
  1292. },
  1293. )
  1294. _install_mock_sidecar(handler)
  1295. response = await async_client.post(
  1296. f"/api/v1/library/files/{threemf.id}/slice",
  1297. json={
  1298. "printer_preset_id": slice_test_setup["printer_id"],
  1299. "process_preset_id": slice_test_setup["process_id"],
  1300. "filament_preset_id": slice_test_setup["filament_id"],
  1301. },
  1302. )
  1303. assert response.status_code == 202
  1304. final = await _wait_for_job(async_client, response.json()["job_id"])
  1305. assert final["status"] == "failed", final
  1306. assert final["error_status"] == 400
  1307. assert "boundary of the heated bed" in (final["error_detail"] or "")
  1308. # The slicer rejection must NOT trigger the embedded-settings retry.
  1309. assert call_count["n"] == 1
  1310. # ---------------------------------------------------------------------------
  1311. # Nozzle-class re-slice guard — single-nozzle <-> dual-nozzle (H2D) is blocked
  1312. # ---------------------------------------------------------------------------
  1313. from fastapi import HTTPException # noqa: E402
  1314. from backend.app.api.routes.library import ( # noqa: E402
  1315. _canonical_printer_model,
  1316. guard_nozzle_class_reslice,
  1317. )
  1318. class TestCanonicalPrinterModel:
  1319. """_canonical_printer_model strips the '# ' clone prefix and the
  1320. ' 0.4 nozzle' variant suffix so preset names resolve to a model code."""
  1321. def test_strips_nozzle_suffix(self):
  1322. assert _canonical_printer_model("Bambu Lab H2D 0.4 nozzle") == "H2D"
  1323. def test_strips_clone_prefix_and_suffix(self):
  1324. assert _canonical_printer_model("# Bambu Lab X1 Carbon 0.4 nozzle") == "X1C"
  1325. def test_bare_model_and_empty(self):
  1326. assert _canonical_printer_model("Bambu Lab H2D") == "H2D"
  1327. assert _canonical_printer_model(None) is None
  1328. assert _canonical_printer_model("") is None
  1329. class TestNozzleClassGuard:
  1330. """guard_nozzle_class_reslice is now a no-op (#1493). Cross-class re-slicing
  1331. is handled by the two-pass conversion in _run_slicer_with_fallback — so the
  1332. guard never blocks. The function is kept (and these tests with it) so
  1333. external forks / pinned versions that call it still link, and so a future
  1334. regression that re-introduces a raise inside the helper gets caught here."""
  1335. @staticmethod
  1336. def _request() -> object:
  1337. return type("_Req", (), {})()
  1338. @pytest.mark.asyncio
  1339. async def test_single_to_dual_is_allowed(self, monkeypatch):
  1340. """Cross-class re-slice: handled by the two-pass converter, so the
  1341. guard does NOT raise."""
  1342. import backend.app.api.routes.library as lib
  1343. async def _target(_db, _user, _request):
  1344. return "H2D"
  1345. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1346. # No raise — the converter handles this case now.
  1347. await guard_nozzle_class_reslice(None, None, self._request(), "X1C")
  1348. @pytest.mark.asyncio
  1349. async def test_dual_to_single_is_allowed(self, monkeypatch):
  1350. import backend.app.api.routes.library as lib
  1351. async def _target(_db, _user, _request):
  1352. return "X1C"
  1353. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1354. await guard_nozzle_class_reslice(None, None, self._request(), "H2D")
  1355. @pytest.mark.asyncio
  1356. async def test_same_nozzle_class_is_allowed(self, monkeypatch):
  1357. import backend.app.api.routes.library as lib
  1358. async def _target(_db, _user, _request):
  1359. return "P1S"
  1360. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1361. await guard_nozzle_class_reslice(None, None, self._request(), "X1C")
  1362. @pytest.mark.asyncio
  1363. async def test_no_source_model_is_a_noop(self, monkeypatch):
  1364. import backend.app.api.routes.library as lib
  1365. async def _target(_db, _user, _request):
  1366. return "H2D"
  1367. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1368. await guard_nozzle_class_reslice(None, None, self._request(), None)
  1369. @pytest.mark.asyncio
  1370. async def test_null_request_is_a_noop(self):
  1371. await guard_nozzle_class_reslice(None, None, None, "X1C")
  1372. @pytest.mark.asyncio
  1373. @pytest.mark.integration
  1374. async def test_archive_reslice_x1c_to_h2d_preset_path_is_not_400(
  1375. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1376. ):
  1377. """End to end: the preset-driven archive re-slice from X1C to H2D no
  1378. longer gets a synchronous 400 from the guard. It may still fail
  1379. downstream (no sidecar in test env), but it must not be rejected by
  1380. the nozzle-class guard's old "isn't supported yet" message."""
  1381. tmp_path = slice_test_setup["tmp_path"]
  1382. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1383. src_dir = tmp_path / "archives" / "src"
  1384. src_dir.mkdir(parents=True, exist_ok=True)
  1385. src_3mf = src_dir / "cube.3mf"
  1386. src_3mf.write_bytes(_make_3mf_with_settings())
  1387. printer = await printer_factory()
  1388. source = await archive_factory(
  1389. printer.id,
  1390. filename="cube.3mf",
  1391. file_path=str(src_3mf.relative_to(tmp_path)),
  1392. sliced_for_model="X1C",
  1393. with_run=False,
  1394. )
  1395. h2d = LocalPreset(
  1396. name="# Bambu Lab H2D 0.4 nozzle",
  1397. preset_type="printer",
  1398. source="orcaslicer",
  1399. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  1400. )
  1401. db_session.add(h2d)
  1402. await db_session.commit()
  1403. await db_session.refresh(h2d)
  1404. resp = await async_client.post(
  1405. f"/api/v1/archives/{source.id}/slice",
  1406. json={
  1407. "printer_preset": {"source": "local", "id": str(h2d.id)},
  1408. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1409. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1410. },
  1411. )
  1412. if resp.status_code == 400:
  1413. detail = resp.json().get("detail", "")
  1414. assert "isn't supported" not in detail, f"guard still firing on preset path: {detail!r}"
  1415. class TestUnusedSlotSubstitutionOnSinglePlateSource:
  1416. """#2711: a single-plate 3MF must still get its unused slots substituted.
  1417. The SliceModal omits ``plate`` entirely for single-plate and STL sources —
  1418. it skips the plate picker, so ``selectedPlate`` stays null and the field
  1419. never reaches the body. The schema documents an absent plate as "plate 1",
  1420. but the substitution used to read it as "unknown plate" and skip, so every
  1421. single-plate project reached the CLI with the dropdown values of slots the
  1422. plate never paints with.
  1423. In the reported case that was a MakerWorld project declaring four filaments
  1424. while plate 1 paints with one, the other three carrying presets baked into
  1425. the source for a different printer. The CLI rejected the whole slice with
  1426. "filament preset ... (slot 1) is not compatible with printer ...", and the
  1427. modal disables unused rows so there was no way to correct it by hand.
  1428. """
  1429. @staticmethod
  1430. def _single_plate_using_only_slot_3() -> bytes:
  1431. """One plate, one object, painted with slot 3 — slots 1, 2 and 4 are
  1432. declared by the project but unused. Mirrors the reported file."""
  1433. buf = io.BytesIO()
  1434. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1435. zf.writestr("3D/3dmodel.model", "<model/>")
  1436. zf.writestr(
  1437. "Metadata/project_settings.config",
  1438. json.dumps({"filament_type": ["PLA", "PLA", "PLA", "TPU"]}),
  1439. )
  1440. zf.writestr(
  1441. "Metadata/model_settings.config",
  1442. "<?xml version='1.0'?>\n<config>"
  1443. '<object id="1"><metadata key="extruder" value="3"/></object>'
  1444. '<plate><metadata key="plater_id" value="1"/>'
  1445. '<model_instance><metadata key="object_id" value="1"/>'
  1446. '<metadata key="instance_id" value="0"/></model_instance>'
  1447. "</plate></config>",
  1448. )
  1449. return buf.getvalue()
  1450. @staticmethod
  1451. def _filament_names_sent(body: bytes) -> list[str]:
  1452. """Pull the ``name`` of each ``filamentProfile`` part, in slot order.
  1453. ``slice_model`` sends one repeated ``filamentProfile`` part per slot as
  1454. ``filament_N.json``; the parts stay in submission order, so a plain
  1455. scan preserves the slot mapping.
  1456. """
  1457. names: list[str] = []
  1458. marker = b'name="filamentProfile"; filename="filament_'
  1459. pos = body.find(marker)
  1460. while pos != -1:
  1461. start = body.find(b"{", pos)
  1462. end = body.find(b"\r\n", start)
  1463. names.append(json.loads(body[start:end].decode("utf-8"))["name"])
  1464. pos = body.find(marker, end)
  1465. return names
  1466. @pytest.mark.asyncio
  1467. @pytest.mark.integration
  1468. async def test_unused_slots_are_substituted_when_the_body_omits_plate(
  1469. self, async_client: AsyncClient, db_session, slice_test_setup
  1470. ):
  1471. tmp_path = slice_test_setup["tmp_path"]
  1472. src = tmp_path / "library" / "files" / "train.3mf"
  1473. src.write_bytes(self._single_plate_using_only_slot_3())
  1474. threemf = LibraryFile(
  1475. filename="train.3mf",
  1476. file_path=str(src.relative_to(tmp_path)),
  1477. file_type="3mf",
  1478. file_size=src.stat().st_size,
  1479. )
  1480. db_session.add(threemf)
  1481. # Four distinguishable filament presets, one per project slot. Only
  1482. # slot 3's is compatible with the target in the reported scenario.
  1483. slots = []
  1484. for i in range(1, 5):
  1485. p = LocalPreset(
  1486. name=f"slot{i}",
  1487. preset_type="filament",
  1488. source="orcaslicer",
  1489. setting=json.dumps({"name": f"slot{i}", "type": "filament"}),
  1490. )
  1491. db_session.add(p)
  1492. slots.append(p)
  1493. await db_session.commit()
  1494. await db_session.refresh(threemf)
  1495. for p in slots:
  1496. await db_session.refresh(p)
  1497. captured: list[list[str]] = []
  1498. def handler(request: httpx.Request) -> httpx.Response:
  1499. captured.append(self._filament_names_sent(request.content))
  1500. return httpx.Response(
  1501. status_code=200,
  1502. content=_make_3mf_with_settings(),
  1503. headers={
  1504. "x-print-time-seconds": "100",
  1505. "x-filament-used-g": "1.0",
  1506. "x-filament-used-mm": "100",
  1507. },
  1508. )
  1509. _install_mock_sidecar(handler)
  1510. response = await async_client.post(
  1511. f"/api/v1/library/files/{threemf.id}/slice",
  1512. json={
  1513. "printer_preset": {"source": "local", "id": str(slice_test_setup["printer_id"])},
  1514. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1515. "filament_presets": [{"source": "local", "id": str(p.id)} for p in slots],
  1516. # No "plate" — exactly what the modal sends for a single-plate
  1517. # source. This is the whole point of the test.
  1518. },
  1519. )
  1520. assert response.status_code == 202, response.text
  1521. final = await _wait_for_job(async_client, response.json()["job_id"])
  1522. assert final["status"] == "completed", final
  1523. assert captured, "sidecar was never called"
  1524. # Every slot carries slot 3's profile: the array length stays intact
  1525. # (the source's per-slot references depend on it) while nothing the
  1526. # plate doesn't print with can fail the CLI's validators.
  1527. assert captured[0] == ["slot3", "slot3", "slot3", "slot3"], captured[0]
  1528. @pytest.mark.asyncio
  1529. @pytest.mark.integration
  1530. async def test_slice_all_keeps_every_slot(self, async_client: AsyncClient, db_session, slice_test_setup):
  1531. """``plate=0`` is the all-plates sentinel, so nothing is unused.
  1532. It reaches the same call site, and plate ids are 1-indexed — the
  1533. geometry lookup for plate 0 matches nothing. Without an explicit
  1534. exclusion the project's support-filament slot would be the only
  1535. member of the used set and would be copied over every colour.
  1536. """
  1537. tmp_path = slice_test_setup["tmp_path"]
  1538. buf = io.BytesIO()
  1539. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1540. zf.writestr("3D/3dmodel.model", "<model/>")
  1541. zf.writestr(
  1542. "Metadata/project_settings.config",
  1543. json.dumps(
  1544. {
  1545. "enable_support": "1",
  1546. "support_filament": "4",
  1547. "support_interface_filament": "4",
  1548. "filament_type": ["PLA", "PLA", "PLA", "PVA"],
  1549. }
  1550. ),
  1551. )
  1552. zf.writestr(
  1553. "Metadata/model_settings.config",
  1554. "<?xml version='1.0'?>\n<config>"
  1555. '<object id="1"><metadata key="extruder" value="1"/></object>'
  1556. '<object id="2"><metadata key="extruder" value="2"/></object>'
  1557. '<plate><metadata key="plater_id" value="1"/>'
  1558. '<model_instance><metadata key="object_id" value="1"/></model_instance></plate>'
  1559. '<plate><metadata key="plater_id" value="2"/>'
  1560. '<model_instance><metadata key="object_id" value="2"/></model_instance></plate>'
  1561. "</config>",
  1562. )
  1563. src = tmp_path / "library" / "files" / "multi.3mf"
  1564. src.write_bytes(buf.getvalue())
  1565. threemf = LibraryFile(
  1566. filename="multi.3mf",
  1567. file_path=str(src.relative_to(tmp_path)),
  1568. file_type="3mf",
  1569. file_size=src.stat().st_size,
  1570. )
  1571. db_session.add(threemf)
  1572. slots = []
  1573. for i in range(1, 5):
  1574. p = LocalPreset(
  1575. name=f"slot{i}",
  1576. preset_type="filament",
  1577. source="orcaslicer",
  1578. setting=json.dumps({"name": f"slot{i}", "type": "filament"}),
  1579. )
  1580. db_session.add(p)
  1581. slots.append(p)
  1582. await db_session.commit()
  1583. await db_session.refresh(threemf)
  1584. for p in slots:
  1585. await db_session.refresh(p)
  1586. captured: list[list[str]] = []
  1587. def handler(request: httpx.Request) -> httpx.Response:
  1588. captured.append(self._filament_names_sent(request.content))
  1589. return httpx.Response(
  1590. status_code=200,
  1591. content=_make_3mf_with_settings(),
  1592. headers={
  1593. "x-print-time-seconds": "100",
  1594. "x-filament-used-g": "1.0",
  1595. "x-filament-used-mm": "100",
  1596. },
  1597. )
  1598. _install_mock_sidecar(handler)
  1599. response = await async_client.post(
  1600. f"/api/v1/library/files/{threemf.id}/slice",
  1601. json={
  1602. "printer_preset": {"source": "local", "id": str(slice_test_setup["printer_id"])},
  1603. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1604. "filament_presets": [{"source": "local", "id": str(p.id)} for p in slots],
  1605. "plate": 0,
  1606. },
  1607. )
  1608. assert response.status_code == 202, response.text
  1609. final = await _wait_for_job(async_client, response.json()["job_id"])
  1610. assert final["status"] == "completed", final
  1611. assert captured, "sidecar was never called"
  1612. assert captured[0] == ["slot1", "slot2", "slot3", "slot4"], captured[0]
  1613. class TestFilamentRequirementsFullSlots:
  1614. """#2712: what the slice modal is handed must be positional.
  1615. The modal's filament list maps index 0 to slot 1, and the backend forwards
  1616. it in that order as ``filament_1.json``..``filament_N.json``. A MakerWorld
  1617. source that ships slice_info and paints with slot 4 alone therefore has to
  1618. present four rows — a one-row list binds the user's pick to slot 1, and
  1619. slot 4 slices with whatever the source had baked in. Picking PETG produced
  1620. a PLA print, and the print dialog then correctly refused to match PETG.
  1621. Print-time AMS matching shares this endpoint and needs the opposite: only
  1622. the slots the plate consumes, so it doesn't demand spools for slots the
  1623. G-code never touches. Hence the opt-in flag rather than a shape change.
  1624. """
  1625. @staticmethod
  1626. def _sliced_source_using_only_slot_4() -> bytes:
  1627. buf = io.BytesIO()
  1628. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1629. zf.writestr("3D/3dmodel.model", "<model/>")
  1630. zf.writestr(
  1631. "Metadata/project_settings.config",
  1632. json.dumps(
  1633. {
  1634. "filament_type": ["PLA", "PLA", "PLA", "PLA"],
  1635. "filament_colour": ["#38CC0A", "#161616", "#898989", "#898989"],
  1636. }
  1637. ),
  1638. )
  1639. # MakerWorld ships slice_info without plate G-code, which is what
  1640. # sends this file down the "already sliced" branch.
  1641. zf.writestr(
  1642. "Metadata/slice_info.config",
  1643. "<?xml version='1.0'?>\n<config><plate>"
  1644. "<metadata key='index' value='1'/>"
  1645. "<filament id='4' tray_info_idx='GFL99' type='PLA' color='#898989'"
  1646. " used_m='35.51' used_g='105.92'/>"
  1647. "</plate></config>",
  1648. )
  1649. return buf.getvalue()
  1650. async def _make_file(self, db_session, tmp_path) -> int:
  1651. src = tmp_path / "library" / "files" / "tunnel.3mf"
  1652. src.write_bytes(self._sliced_source_using_only_slot_4())
  1653. lib = LibraryFile(
  1654. filename="tunnel.3mf",
  1655. file_path=str(src.relative_to(tmp_path)),
  1656. file_type="3mf",
  1657. file_size=src.stat().st_size,
  1658. )
  1659. db_session.add(lib)
  1660. await db_session.commit()
  1661. await db_session.refresh(lib)
  1662. return lib.id
  1663. @pytest.mark.asyncio
  1664. @pytest.mark.integration
  1665. async def test_full_slots_returns_one_row_per_project_slot(
  1666. self, async_client: AsyncClient, db_session, slice_test_setup
  1667. ):
  1668. file_id = await self._make_file(db_session, slice_test_setup["tmp_path"])
  1669. r = await async_client.get(f"/api/v1/library/files/{file_id}/filament-requirements?plate_id=1&full_slots=true")
  1670. assert r.status_code == 200, r.text
  1671. filaments = r.json()["filaments"]
  1672. assert [f["slot_id"] for f in filaments] == [1, 2, 3, 4]
  1673. # Only slot 4 prints, so only its row is selectable in the modal.
  1674. assert [f["used_in_plate"] for f in filaments] == [False, False, False, True]
  1675. # The used row keeps what the slice actually reported.
  1676. assert filaments[3]["used_grams"] == 105.9
  1677. assert filaments[3]["tray_info_idx"] == "GFL99"
  1678. @pytest.mark.asyncio
  1679. @pytest.mark.integration
  1680. async def test_the_print_path_still_gets_only_the_used_slot(
  1681. self, async_client: AsyncClient, db_session, slice_test_setup
  1682. ):
  1683. """Without the flag the response must be byte-for-byte what it was.
  1684. PrintModal drives AMS matching off this; widening it would ask the
  1685. user to load three spools the print never touches.
  1686. """
  1687. file_id = await self._make_file(db_session, slice_test_setup["tmp_path"])
  1688. r = await async_client.get(f"/api/v1/library/files/{file_id}/filament-requirements?plate_id=1")
  1689. assert r.status_code == 200, r.text
  1690. filaments = r.json()["filaments"]
  1691. assert [f["slot_id"] for f in filaments] == [4]
  1692. assert filaments[0]["used_in_plate"] is True
  1693. @pytest.mark.asyncio
  1694. @pytest.mark.integration
  1695. async def test_unsliced_sources_are_unaffected_by_the_flag(
  1696. self, async_client: AsyncClient, db_session, slice_test_setup
  1697. ):
  1698. """Those already returned the full project list; the flag must not
  1699. double-handle them or change what the modal has been getting."""
  1700. tmp_path = slice_test_setup["tmp_path"]
  1701. buf = io.BytesIO()
  1702. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1703. zf.writestr("3D/3dmodel.model", "<model/>")
  1704. zf.writestr(
  1705. "Metadata/project_settings.config",
  1706. json.dumps({"filament_type": ["PLA", "PETG"], "filament_colour": ["#000000", "#FFFFFF"]}),
  1707. )
  1708. src = tmp_path / "library" / "files" / "raw.3mf"
  1709. src.write_bytes(buf.getvalue())
  1710. lib = LibraryFile(
  1711. filename="raw.3mf",
  1712. file_path=str(src.relative_to(tmp_path)),
  1713. file_type="3mf",
  1714. file_size=src.stat().st_size,
  1715. )
  1716. db_session.add(lib)
  1717. await db_session.commit()
  1718. await db_session.refresh(lib)
  1719. with_flag = await async_client.get(
  1720. f"/api/v1/library/files/{lib.id}/filament-requirements?plate_id=1&full_slots=true"
  1721. )
  1722. without = await async_client.get(f"/api/v1/library/files/{lib.id}/filament-requirements?plate_id=1")
  1723. assert with_flag.status_code == 200 and without.status_code == 200
  1724. assert with_flag.json()["filaments"] == without.json()["filaments"]
  1725. assert [f["slot_id"] for f in with_flag.json()["filaments"]] == [1, 2]