"""push_tags.fetch_many — the thread-parallel QID fetch every prompt builder (AI Tagging / LO / Verify / Solutions prep) now runs on. The network is mocked at pt.fetch so these tests exercise the executor wiring (input-order output under out-of-order completion, per-QID error isolation, and progress reported from the collector thread) without touching the CMS. """ import sys import threading import time from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'backend' / 'ai_tagger')) @pytest.fixture(scope='module') def pt(): import push_tags return push_tags def test_fetch_many_returns_results_in_input_order(pt, monkeypatch): """Workers finish out of order (ILQ-1 is fastest); output must still be the input order so prompts built from it are stable.""" def fake_fetch(h, qid): time.sleep(0.02 * int(qid[-1])) return {'question_id': qid, 'question': {'question_text': f'q{qid}'}} monkeypatch.setattr(pt, 'fetch', fake_fetch) out = pt.fetch_many({'h': 1}, ['ILQ-3', 'ILQ-1', 'ILQ-2'], workers=3) assert [o['qid'] for o in out] == ['ILQ-3', 'ILQ-1', 'ILQ-2'] assert all('data' in o and 'error' not in o for o in out) def test_fetch_many_isolates_per_qid_errors(pt, monkeypatch): def fake_fetch(h, qid): if qid == 'ILQ-BAD': raise RuntimeError('boom') return {'question_id': qid} monkeypatch.setattr(pt, 'fetch', fake_fetch) out = pt.fetch_many({'h': 1}, ['ILQ-1', 'ILQ-BAD', 'ILQ-2'], workers=3) assert [o['qid'] for o in out] == ['ILQ-1', 'ILQ-BAD', 'ILQ-2'] assert out[1] == {'qid': 'ILQ-BAD', 'error': 'boom'} assert 'data' in out[0] and 'data' in out[2] def test_fetch_many_reports_progress_from_the_caller_thread(pt, monkeypatch): """progress(done, total) fires on the collector (caller) thread only — the app's progress handlers write to a job dict under TAG_LOCK, so they must not be invoked from worker threads.""" monkeypatch.setattr(pt, 'fetch', lambda h, qid: {'question_id': qid}) seen, who = [], set() def prog(done, total): seen.append(done) who.add(threading.current_thread().name) pt.fetch_many({'h': 1}, ['ILQ-1', 'ILQ-2', 'ILQ-3'], workers=3, progress=prog) assert seen == [1, 2, 3] assert who == {'MainThread'} def test_fetch_many_single_worker_and_empty(pt, monkeypatch): monkeypatch.setattr(pt, 'fetch', lambda h, qid: {'question_id': qid}) assert pt.fetch_many({'h': 1}, ['ILQ-1', 'ILQ-2'], workers=1) == [ {'qid': 'ILQ-1', 'data': {'question_id': 'ILQ-1'}}, {'qid': 'ILQ-2', 'data': {'question_id': 'ILQ-2'}}, ] assert pt.fetch_many({'h': 1}, []) == []