from pathlib import Path from threading import Event from types import SimpleNamespace import pytest from dx_productivity.trial_task_center.errors import TaskCenterError from dx_productivity.trial_task_center.task_queue import execute_task_queue class Service: def __init__(self, root, outcomes=None): self._logging = SimpleNamespace(root=root) self.calls = [] self.outcomes = outcomes or {} self.current = None self._batch_feedback = None def for_project_task(self, task_id): parent = self class Child: def get_task(self, task_id): return SimpleNamespace(primary_project_id=task_id, copy_part_number_to_value=False) def projects(self, task_id): return (SimpleNamespace(path=Path('C:/') / task_id / 'board.prj', selected=True, available=True),) def rules(self, task_id): return (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True),) def target_plan(self, task_id): return () def has_interrupted_quick_run(self, task_id): return False def quick_run_progress(self, task_id): return SimpleNamespace(queue_complete=False, next_project_path=self.projects(task_id)[0].path, next_old_part_number='OLD', next_new_part_number='NEW') def execute_quick_run_queue(self, task_id, *, expected_item, stop_event): parent.calls.append(('start', task_id)) outcome = parent.outcomes.get(task_id) if isinstance(outcome, Exception): raise outcome if callable(outcome): outcome(stop_event) parent.calls.append(('end', task_id)) return SimpleNamespace(paused=stop_event.is_set(), progress=SimpleNamespace(failed_items=int(outcome == 'failed'), queue_complete=True), last_result=SimpleNamespace(state='saved_ok')) return Child() def test_tasks_execute_in_confirmed_order_and_finished_queue_does_not_repeat(tmp_path): service = Service(tmp_path) result = execute_task_queue(service, ('B', 'A'), stop_event=Event()) assert service.calls == [('start', 'B'), ('end', 'B'), ('start', 'A'), ('end', 'A')] assert [entry.state for entry in result.entries] == ['completed', 'completed'] execute_task_queue(service, ('B', 'A'), stop_event=Event(), queue_id=result.queue_id) assert len(service.calls) == 4 def test_changed_confirmed_plan_is_rejected_before_any_executor(tmp_path): service = Service(tmp_path) with pytest.raises(TaskCenterError, match='assistant_stale'): execute_task_queue(service, ('A',), stop_event=Event(), expected_plan_hashes={'A': 'stale'}) assert not service.calls def test_dispatched_error_isolates_the_project_after_its_owned_resources_exit(tmp_path): service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')}) result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) assert not result.paused and result.entries[0].state == 'blocked' assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')] def test_actual_read_phase_failure_allows_next_project(tmp_path): service = Service(tmp_path) original = service.for_project_task def child_for(task_id): child = original(task_id) if task_id == 'A': def read_failure(_task_id): raise TaskCenterError('new_read_error', 'read failed before dispatch') child.quick_run_progress = read_failure return child service.for_project_task = child_for result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) assert [entry.state for entry in result.entries] == ['failed', 'completed'] assert service.calls == [('start', 'B'), ('end', 'B')] def test_uncertain_result_is_quarantined_without_replaying_before_next_independent_task(tmp_path): service = Service(tmp_path, {'A': TaskCenterError('quick_run_uncertain', 'unknown')}) result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) assert not result.paused assert result.entries[0].state == 'blocked' assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')] def test_pause_finishes_current_item_and_does_not_start_next_task(tmp_path): service = Service(tmp_path, {'A': lambda stop: stop.set()}) result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) assert result.paused assert service.calls == [('start', 'A'), ('end', 'A')] def test_pause_between_problem_tasks_preserves_resumable_batch(tmp_path, monkeypatch): from dx_productivity.trial_task_center import problem_pass service = Service(tmp_path, {'A': 'failed'}) service.reserve_problem_retry = lambda *a, **k: () stop = Event() def interrupted_pass(*args, **kwargs): # A completed retry can reach the next loop boundary before stop is observed. stop.set() return problem_pass.ProblemPassResult({}) monkeypatch.setattr(problem_pass, 'run_problem_pass', interrupted_pass) result = execute_task_queue(service, ('A', 'B'), stop_event=stop) assert result.paused and result.current_task_id in {'A', 'B'} assert [entry.state for entry in result.entries] == ['failed', 'completed'] import json checkpoint = json.loads((tmp_path / 'task-queues' / (result.queue_id + '.json')).read_text(encoding='utf-8')) assert checkpoint['phase'] == 'problems' def test_duplicate_tasks_and_projects_rejected_before_dispatch(tmp_path): service = Service(tmp_path) with pytest.raises(TaskCenterError): execute_task_queue(service, ('A', 'A'), stop_event=Event()) assert service.calls == [] def test_resume_rejects_another_task_order(tmp_path): service = Service(tmp_path) result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) with pytest.raises(TaskCenterError): execute_task_queue(service, ('B', 'A'), stop_event=Event(), queue_id=result.queue_id) def test_pending_bom_is_resolved_per_project_and_read_failure_does_not_stop_others(tmp_path): service = Service(tmp_path) original = service.for_project_task pending = {'A': ('source-A',), 'B': ('source-B',)} def child_for(task_id): child = original(task_id) child.pending_bom = lambda _: pending[task_id] child.bom_resolution = lambda _: None def resolve(_, **controls): service.calls.append(('resolve', task_id)) if task_id == 'A': raise TaskCenterError('native_inventory', 'CLI cannot read project A') pending[task_id] = () return (SimpleNamespace(enabled=True),) child.resolve_pending_bom = resolve return child service.for_project_task = child_for result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) assert [entry.state for entry in result.entries] == ['failed', 'completed'] assert not result.paused assert service.calls == [('resolve', 'A'), ('resolve', 'B'), ('start', 'B'), ('end', 'B')] def test_pending_request_participates_in_plan_hash_and_materialization_keeps_confirmation(tmp_path): from dx_productivity.trial_task_center.task_queue import _plan_hash service = Service(tmp_path) child = service.for_project_task('A') pending = ['old request'] binding = {} child.pending_bom = lambda _: tuple(pending) child.bom_resolution = lambda _: binding or None confirmed = _plan_hash(child, 'A') pending[:] = ['changed request'] assert _plan_hash(child, 'A') != confirmed pending.clear() binding.update(confirmed_hash=confirmed, resolved_hash=_plan_hash(child, 'A', resolve_alias=False)) assert _plan_hash(child, 'A') == confirmed child.rules = lambda _: (SimpleNamespace(old_part_number='OLD', new_part_number='OTHER', enabled=True),) assert _plan_hash(child, 'A') != confirmed