test_scheduler_dispatch_order_2915.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. """The order an "Any model" job picks its printer in is a setting (#2915).
  2. Fewest print hours stays the default (#3480). The setting adds the most hours
  3. (use up the machines near replacement), the printer idle the longest, and the
  4. printers' own priority.
  5. """
  6. from datetime import datetime
  7. from types import SimpleNamespace
  8. from unittest.mock import MagicMock, patch
  9. import pytest
  10. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  11. import backend.app.models # noqa: F401 - populate Base.metadata
  12. from backend.app.core.database import Base
  13. from backend.app.models.print_log import PrintLogEntry
  14. from backend.app.models.printer import Printer
  15. from backend.app.models.settings import Settings
  16. from backend.app.services.print_scheduler import PrintScheduler, _order_printers
  17. HOUR = 3600
  18. def _p(pid, hours=0.0, priority=None):
  19. return SimpleNamespace(
  20. id=pid, runtime_seconds=int(hours * HOUR), print_hours_offset=0.0, dispatch_priority=priority
  21. )
  22. def _ids(printers):
  23. return [p.id for p in printers]
  24. class TestOrdering:
  25. def test_fewest_hours_is_the_default_and_an_unknown_value(self):
  26. printers = [_p(1, 900), _p(2, 100), _p(3, 20)]
  27. assert _ids(_order_printers(printers, "fewest_hours")) == [3, 2, 1]
  28. assert _ids(_order_printers(printers, "nonsense")) == [3, 2, 1]
  29. def test_most_hours_puts_the_most_worn_first_and_ties_go_by_id(self):
  30. printers = [_p(1, 20), _p(2, 900), _p(3, 20), _p(4, 100)]
  31. assert _ids(_order_printers(printers, "most_hours")) == [2, 4, 1, 3]
  32. def test_the_baseline_offset_counts_as_hours(self):
  33. old = SimpleNamespace(id=1, runtime_seconds=0, print_hours_offset=500.0, dispatch_priority=None)
  34. assert _ids(_order_printers([_p(2, 10), old], "most_hours")) == [1, 2]
  35. def test_least_recently_used_takes_the_longest_idle_and_never_used_first(self):
  36. printers = [_p(1), _p(2), _p(3), _p(4)]
  37. finished = {1: datetime(2026, 5, 3), 2: datetime(2026, 5, 1), 4: datetime(2026, 5, 2)}
  38. # 3 never printed; then 2 (May 1), 4 (May 2), 1 (May 3).
  39. assert _ids(_order_printers(printers, "least_recently_used", finished)) == [3, 2, 4, 1]
  40. def test_least_recently_used_without_any_history_goes_by_id(self):
  41. assert _ids(_order_printers([_p(3), _p(1), _p(2)], "least_recently_used", {})) == [1, 2, 3]
  42. def test_priority_is_lowest_first_empty_last_and_ties_by_id(self):
  43. printers = [_p(1, priority=None), _p(2, priority=5), _p(3, priority=1), _p(4, priority=5), _p(5, priority=0)]
  44. # 0 is a real priority (first), not "none".
  45. assert _ids(_order_printers(printers, "priority")) == [5, 3, 2, 4, 1]
  46. async def _farm(setting: str | None, **printers):
  47. """X1Cs by id with (runtime hours, priority); the setting row is written when given."""
  48. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  49. async with engine.begin() as conn:
  50. await conn.run_sync(Base.metadata.create_all)
  51. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  52. async with session_maker() as db:
  53. for key, (hours, priority) in printers.items():
  54. pid = int(key.removeprefix("p"))
  55. db.add(
  56. Printer(
  57. id=pid,
  58. name=f"X1C-{pid}",
  59. serial_number=f"X1C000{pid}",
  60. ip_address=f"192.0.2.{pid}",
  61. access_code="x",
  62. model="X1C",
  63. is_active=True,
  64. runtime_seconds=int(hours * HOUR),
  65. dispatch_priority=priority,
  66. )
  67. )
  68. if setting is not None:
  69. db.add(Settings(key="model_dispatch_order", value=setting))
  70. await db.commit()
  71. return engine, SimpleNamespace(session_maker=session_maker)
  72. async def _find(ctx, exclude=frozenset()):
  73. scheduler = PrintScheduler()
  74. with (
  75. patch("backend.app.services.print_scheduler.printer_manager.is_connected", MagicMock(return_value=True)),
  76. patch.object(scheduler, "_is_printer_idle", MagicMock(return_value=True)),
  77. ):
  78. async with ctx.session_maker() as db:
  79. return await scheduler._find_idle_printer_for_model(db, "X1C", set(exclude))
  80. # Printer 1 is the most worn, 3 the least; priority puts 2 first, then 1, and 3 has none.
  81. PRINTERS = {"p1": (900, 2), "p2": (100, 1), "p3": (20, None)}
  82. class TestTheSettingDecidesWhoGetsTheJob:
  83. @pytest.mark.asyncio
  84. @pytest.mark.parametrize(
  85. ("setting", "expected"),
  86. [
  87. (None, 3), # not set: fewest hours, as before
  88. ("fewest_hours", 3),
  89. ("most_hours", 1),
  90. ("priority", 2),
  91. ("garbage", 3), # a bad row never stops the queue
  92. ],
  93. )
  94. async def test_first_pick(self, setting, expected):
  95. engine, ctx = await _farm(setting, **PRINTERS)
  96. try:
  97. assert await _find(ctx) == (expected, None)
  98. finally:
  99. await engine.dispose()
  100. @pytest.mark.asyncio
  101. async def test_a_busy_first_choice_passes_the_job_down_the_order(self):
  102. engine, ctx = await _farm("priority", **PRINTERS)
  103. try:
  104. assert await _find(ctx, exclude={2}) == (1, None)
  105. assert await _find(ctx, exclude={2, 1}) == (3, None)
  106. finally:
  107. await engine.dispose()
  108. @pytest.mark.asyncio
  109. async def test_least_recently_used_follows_the_print_log(self):
  110. engine, ctx = await _farm("least_recently_used", **PRINTERS)
  111. try:
  112. async with ctx.session_maker() as db:
  113. db.add_all(
  114. [
  115. PrintLogEntry(printer_id=3, status="completed", completed_at=datetime(2026, 5, 3)),
  116. PrintLogEntry(printer_id=3, status="completed", completed_at=datetime(2026, 4, 1)),
  117. PrintLogEntry(printer_id=1, status="completed", completed_at=datetime(2026, 5, 1)),
  118. PrintLogEntry(printer_id=2, status="completed", completed_at=datetime(2026, 5, 2)),
  119. ]
  120. )
  121. await db.commit()
  122. # Each printer counts by its latest finish: 1 (May 1) is idle longest.
  123. assert await _find(ctx) == (1, None)
  124. finally:
  125. await engine.dispose()
  126. @pytest.mark.asyncio
  127. async def test_a_printer_that_never_printed_is_the_least_recently_used(self):
  128. engine, ctx = await _farm("least_recently_used", **PRINTERS)
  129. try:
  130. async with ctx.session_maker() as db:
  131. db.add_all(
  132. [
  133. PrintLogEntry(printer_id=1, status="completed", completed_at=datetime(2026, 5, 1)),
  134. PrintLogEntry(printer_id=2, status="completed", completed_at=datetime(2026, 5, 2)),
  135. ]
  136. )
  137. await db.commit()
  138. assert await _find(ctx) == (3, None)
  139. finally:
  140. await engine.dispose()
  141. @pytest.mark.asyncio
  142. async def test_the_wake_step_and_the_matcher_share_the_order(self):
  143. """Both read _printers_for_model, so a printer is woken in the order it would be picked."""
  144. engine, ctx = await _farm("most_hours", **PRINTERS)
  145. try:
  146. async with ctx.session_maker() as db:
  147. printers = await PrintScheduler()._printers_for_model(db, "X1C")
  148. assert [p.id for p in printers] == [1, 2, 3]
  149. finally:
  150. await engine.dispose()
  151. class TestApi:
  152. @pytest.mark.asyncio
  153. @pytest.mark.integration
  154. async def test_the_order_setting_defaults_saves_and_rejects_others(self, async_client):
  155. default = await async_client.get("/api/v1/settings/")
  156. assert default.json()["model_dispatch_order"] == "fewest_hours"
  157. saved = await async_client.put("/api/v1/settings/", json={"model_dispatch_order": "priority"})
  158. assert saved.status_code == 200, saved.text
  159. assert (await async_client.get("/api/v1/settings/")).json()["model_dispatch_order"] == "priority"
  160. refused = await async_client.put("/api/v1/settings/", json={"model_dispatch_order": "alphabetical"})
  161. assert refused.status_code == 422
  162. @pytest.mark.asyncio
  163. @pytest.mark.integration
  164. async def test_a_printer_priority_round_trips_and_clears(self, async_client, printer_factory):
  165. printer = await printer_factory()
  166. set_ = await async_client.patch(f"/api/v1/printers/{printer.id}", json={"dispatch_priority": 3})
  167. assert set_.status_code == 200, set_.text
  168. assert set_.json()["dispatch_priority"] == 3
  169. cleared = await async_client.patch(f"/api/v1/printers/{printer.id}", json={"dispatch_priority": None})
  170. assert cleared.json()["dispatch_priority"] is None
  171. negative = await async_client.patch(f"/api/v1/printers/{printer.id}", json={"dispatch_priority": -1})
  172. assert negative.status_code == 422
  173. @pytest.mark.asyncio
  174. @pytest.mark.integration
  175. async def test_a_patch_without_it_leaves_the_priority_alone(self, async_client, printer_factory):
  176. printer = await printer_factory()
  177. await async_client.patch(f"/api/v1/printers/{printer.id}", json={"dispatch_priority": 2})
  178. resp = await async_client.patch(f"/api/v1/printers/{printer.id}", json={"name": "Renamed"})
  179. assert resp.json()["dispatch_priority"] == 2