from __future__ import annotations import pytest from backend.services.queue_service import QueueService from core.audit_service import AuditService from core.identity import RequestContext from database.db_helper import Database, DatabaseSettings, SqliteSettings from database.repositories.job_repository import JobRepository @pytest.fixture() def queue(tmp_path): database = Database( DatabaseSettings( backend="sqlite", sqlite=SqliteSettings(path=str(tmp_path / "queue.sqlite3")), ) ) database.initialize() return QueueService(JobRepository(database), AuditService(database)) def _ctx() -> RequestContext: return RequestContext.system("test") def _enqueue(queue: QueueService, task_id: str) -> None: queue.create_task( { "task_id": task_id, "task_type": "generation", "status": "queued", "request": {}, "metadata": {}, }, _ctx(), ) def test_claim_order_is_fifo(queue: QueueService) -> None: """Regression: workers consumed the newest-first display listing (LIFO). With a backlog deeper than the claim batch, the oldest task never came back into the window and was starved forever. """ for index in range(6): _enqueue(queue, f"task-{index:02d}") claimable = queue.list_claimable_jobs(status="queued", limit=3) assert [task.task_id for task in claimable] == ["task-00", "task-01", "task-02"] def test_claim_window_reaches_the_oldest_task_under_backlog(queue: QueueService) -> None: """The starvation symptom itself: oldest must be inside a small window.""" for index in range(40): _enqueue(queue, f"task-{index:02d}") window = queue.list_claimable_jobs(status="queued", limit=5) assert window[0].task_id == "task-00" def test_display_listing_stays_newest_first(queue: QueueService) -> None: """The UI ordering must not regress — the two listings are distinct.""" for index in range(3): _enqueue(queue, f"task-{index:02d}") shown = queue.list_jobs(status="queued", page=1, page_size=10).items assert [task.task_id for task in shown][0] == "task-02" def test_cas_write_refuses_to_overwrite_a_cancelled_task(queue: QueueService) -> None: """The TOCTOU the worker had: cancel landing between read and write.""" _enqueue(queue, "task-cas") queue.claim_queued_task("task-cas", _ctx(), worker_id="worker-1") # The user cancels while the provider call is still in flight. queue.update_task("task-cas", {"status": "cancelled"}, _ctx()) # The worker now tries to record success against the status it saw. result = queue.update_task_if_status( "task-cas", {"running"}, {"status": "succeeded"}, _ctx() ) assert result is None, "CAS must refuse the write" assert queue.get_job("task-cas").status == "cancelled" def test_cas_write_succeeds_when_the_task_is_still_running(queue: QueueService) -> None: """The happy path must be unaffected.""" _enqueue(queue, "task-ok") queue.claim_queued_task("task-ok", _ctx(), worker_id="worker-1") result = queue.update_task_if_status( "task-ok", {"running"}, {"status": "succeeded"}, _ctx() ) assert result is not None assert queue.get_job("task-ok").status == "succeeded"