test_library_slice_api.py 86 KB

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