"""Lightweight cache integrity tests; predictions here are explicit synthetic fixtures.""" import copy import hashlib import io import json from pathlib import Path import pydicom import pytest from fastapi.testclient import TestClient from pydicom.uid import generate_uid from service.api import create_app from service.example_cache import read_cache, classifier_provenance from service.storage import InputError from test_service import FakeEngine, dicom, wait @pytest.fixture def cache_fixture(tmp_path, monkeypatch): import huggingface_hub manifest = json.loads((Path(__file__).parents[1] / 'engine' / 'manifest.json').read_text()) uid = generate_uid() files, paths, ordered = [], {}, {'left': [], 'right': []} for side in ('left', 'right'): payload = dicom(uid) ds = pydicom.dcmread(io.BytesIO(payload), stop_before_pixels=True) name = side + '.dcm' path = tmp_path / name path.write_bytes(payload) paths[name] = str(path) files.append({'path': name, 'sop_uid': str(ds.SOPInstanceUID), 'artery': side, 'sha256': hashlib.sha256(payload).hexdigest()}) ordered[side].append({'sop_uid': str(ds.SOPInstanceUID), 'series_uid': str(ds.SeriesInstanceUID), 'frames': 12}) left, right = [1., 2., 3., 4., 5.], [2., 3., 4., 5., 6.] folds = [{'fold': index, 'left': l, 'right': r, 'raw': l + r, 'calibrated': coeff['a'] * (l + r) + coeff['b'], **coeff} for index, (l, r, coeff) in enumerate(zip(left, right, manifest['calibration']['folds']))] result = {'raw': 7., 'calibrated': sum(f['calibrated'] for f in folds) / 5, 'complete': True, 'study_uid': uid, 'per_fold': folds, 'projection_count': 2, 'left': {'raw': 3., 'per_fold': left, 'projections': 1}, 'right': {'raw': 4., 'per_fold': right, 'projections': 1}, 'provenance': {'repo_id': manifest['repo_id'], 'revision': manifest['revision'], 'weights': [{key: record[key] for key in ('path', 'sha256')} for record in manifest['score_weights']], 'calibration_source': {key: manifest['calibration'][key] for key in ('path', 'sha256', 'folds')}, 'ordered_inputs': ordered, 'device': 'synthetic-test'}} example = {'id': 'synthetic', 'study_uid': uid, 'repository': 'public/test', 'revision': 'fixed-revision', 'files': [{key: item[key] for key in ('path', 'sop_uid', 'artery')} for item in files], 'reference_score': 0., 'cache_file': 'example_results/synthetic.json'} payload = {'schema_version': 1, 'example_id': example['id'], 'dataset': {'repo_id': example['repository'], 'revision': example['revision']}, 'files': files, 'result': result, 'classification': classifier_provenance([{'sop_uid': f['sop_uid'], 'frames': 12, 'artery': f['artery'], 'probability_right': 0. if f['artery'] == 'left' else 1., 'reason': None} for f in files], manifest)} folder = tmp_path / 'example_results'; folder.mkdir() cache_path = folder / 'synthetic.json' cache_path.write_text(json.dumps(payload)) examples_path = tmp_path / 'examples.json'; examples_path.write_text(json.dumps([example])) monkeypatch.setattr(huggingface_hub, 'hf_hub_download', lambda **kwargs: paths[kwargs['filename']]) return example, payload, cache_path, examples_path, paths def test_verified_cache_load_has_result_without_inference(cache_fixture, tmp_path): example, payload, _, examples_path, _ = cache_fixture engine = FakeEngine() app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path) with TestClient(app) as client: card = client.get('/api/examples').json()['examples'][0] assert card['reference_score'] == 0. and card['cached_result_available'] assert card['prediction']['calibrated'] == payload['result']['calibrated'] loaded = wait(client, client.post('/api/examples/synthetic/load').json()) assert loaded['status'] == 'completed' cached = loaded['result']['cached_job'] study = loaded['result']['studies'][0] assert study['classification_complete'] is True assert study['classification_source'] == 'verified_cached_classifier' assert cached['study_id'] == study['id'] assert client.get('/api/jobs/' + cached['id']).json()['result']['calibrated'] == payload['result']['calibrated'] assert client.get('/api/studies/' + study['id']).json()['cached_result_job_id'] == cached['id'] assert cached['result']['input_assignments'] == [{'id': p['id'], 'artery': p['artery']} for p in study['projections']] assert cached['result']['source']['type'] == 'precomputed_example' assert 'PRIVATE' not in json.dumps(cached) assert engine.calls == [] classify = client.post('/api/studies/' + study['id'] + '/classify').json() assert wait(client, classify)['status'] == 'completed' assert client.get('/api/studies/' + study['id']).json()['cached_result_job_id'] is None assert client.delete('/api/studies/' + study['id']).status_code == 200 assert client.get('/api/jobs/' + cached['id']).status_code == 404 @pytest.mark.parametrize('change', ['model', 'weights', 'order', 'arithmetic', 'file_manifest', 'calibration', 'private_metadata', 'missing_classifier', 'classifier_weight', 'classifier_confidence']) def test_cache_integrity_failures_never_expose_score(cache_fixture, tmp_path, change): example, original, cache_path, examples_path, _ = cache_fixture payload = copy.deepcopy(original) result = payload['result'] if change == 'model': result['provenance']['revision'] = 'wrong' elif change == 'weights': result['provenance']['weights'][0]['sha256'] = '0' * 64 elif change == 'order': result['provenance']['ordered_inputs']['left'][0]['sop_uid'] = '1.2.3' elif change == 'arithmetic': result['calibrated'] += 1 elif change == 'file_manifest': payload['files'].reverse() elif change == 'calibration': result['provenance']['calibration_source']['folds'][0]['a'] += 1 elif change == 'missing_classifier': payload.pop('classification') elif change == 'classifier_weight': payload['classification']['weight']['sha256'] = '0' * 64 elif change == 'classifier_confidence': payload['classification']['outputs'][0]['probability_right'] = .5 else: result['PatientName'] = 'must never be exposed' cache_path.write_text(json.dumps(payload)) with pytest.raises(InputError): read_cache(example, base=examples_path.parent) app = create_app(data_root=tmp_path / 'uploads', engine=FakeEngine(), examples_path=examples_path) with TestClient(app) as client: card = client.get('/api/examples').json()['examples'][0] assert not card['cached_result_available'] and card['prediction'] is None job = wait(client, client.post('/api/examples/synthetic/load').json()) assert job['status'] == 'failed' and job['result'] is None assert not app.state.store.studies def test_download_checksum_mismatch_discards_precomputed_result(cache_fixture, tmp_path): _, _, _, examples_path, paths = cache_fixture changed = pydicom.dcmread(paths['left.dcm']) pixels = bytearray(changed.PixelData) pixels[0] ^= 1 changed.PixelData = bytes(pixels) changed.save_as(paths['left.dcm'], enforce_file_format=True) app = create_app(data_root=tmp_path / 'uploads', engine=FakeEngine(), examples_path=examples_path) with TestClient(app) as client: job = wait(client, client.post('/api/examples/synthetic/load').json()) assert job['status'] == 'failed' and job['result'] is None assert 'checksum' in job['error'] assert not app.state.store.studies and not app.state.store.workspaces def test_missing_optional_cache_is_not_fabricated(cache_fixture, tmp_path): example, _, _, examples_path, _ = cache_fixture example.pop('cache_file') examples_path.write_text(json.dumps([example])) engine = FakeEngine() app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path) with TestClient(app) as client: card = client.get('/api/examples').json()['examples'][0] assert card['prediction'] is None and not card['cached_result_available'] result = wait(client, client.post('/api/examples/synthetic/load').json()) assert result['status'] == 'completed' and result['result']['cached_job'] is None assert engine.calls == [] def test_cache_file_must_stay_in_curated_results_directory(cache_fixture): example, _, _, examples_path, _ = cache_fixture example['cache_file'] = '../outside.json' with pytest.raises(InputError, match='invalid cache path'): read_cache(example, base=examples_path.parent) def add_packaged_previews(example, payload, examples_path, paths): static = examples_path.parent / 'static' destination = static / 'examples' / example['id'] destination.mkdir(parents=True) example['vendor'] = 'Synthetic' example['default_projection_index'] = 1 for item in example['files']: ds = pydicom.dcmread(paths[item['path']], stop_before_pixels=True) preview = {'frames': int(ds.NumberOfFrames), 'rows': int(ds.Rows), 'columns': int(ds.Columns), 'series_uid': str(ds.SeriesInstanceUID)} for kind, suffix in (('video', '.mp4'), ('poster', '.png')): # Media decode is separately tested with real FFmpeg; here only immutable asset binding is relevant. target = destination / (item['artery'] + suffix) target.write_bytes(b'fixture-public-preview-' + kind.encode()) preview[kind] = target.relative_to(static).as_posix() preview[kind + '_sha256'] = hashlib.sha256(target.read_bytes()).hexdigest() item['preview'] = preview examples_path.write_text(json.dumps([example])) return static def test_packaged_example_is_instant_and_hydrates_only_on_rerun(cache_fixture, tmp_path, monkeypatch): import huggingface_hub example, payload, _, examples_path, paths = cache_fixture static = add_packaged_previews(example, payload, examples_path, paths) downloads = [] def download(**kwargs): downloads.append(kwargs['filename']) return paths[kwargs['filename']] monkeypatch.setattr(huggingface_hub, 'hf_hub_download', download) engine = FakeEngine() app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path, static_root=static) with TestClient(app) as client: assert client.get('/api/examples').json()['examples'][0]['vendor'] == 'Synthetic' # A metadata-only open succeeds even when the compute queue has no free slots. for index in range(3): app.state.jobs.items['busy-fixture-' + str(index)] = {'status': 'running', 'updated_at': 0} job = client.post('/api/examples/synthetic/load').json() assert job['status'] == 'completed' study = job['result']['studies'][0] assert study['source_type'] == 'precomputed_example' and study['hydrated'] is False assert study['default_projection_id'] == study['projections'][1]['id'] assert [p['artery'] for p in study['projections']] == ['left', 'right'] assert downloads == [] and engine.calls == [] assert not list(app.state.store.studies[study['id']].directory.iterdir()) for projection in study['projections']: assert projection['video_url'].startswith('/static/examples/') assert client.get(projection['preview_url']).status_code == 200 for index in range(3): app.state.jobs.items.pop('busy-fixture-' + str(index)) assignments = [{'id': p['id'], 'artery': p['artery']} for p in study['projections']] run = client.post('/api/studies/' + study['id'] + '/run', json={}).json() result = wait(client, run) assert result['status'] == 'completed' assert len(downloads) == 2 and len(engine.calls) == 1 current = client.get('/api/studies/' + study['id']).json() assert current['hydrated'] is True assert current['default_projection_id'] == study['default_projection_id'] assert [{'id': p['id'], 'artery': p['artery']} for p in current['projections']] == assignments assert result['result']['input_assignments'] == assignments assert 'source' not in result['result'] # A new model run is not labelled precomputed. def test_lazy_hydration_rejects_changed_dicom_before_model(cache_fixture, tmp_path): example, payload, _, examples_path, paths = cache_fixture static = add_packaged_previews(example, payload, examples_path, paths) changed = pydicom.dcmread(paths['left.dcm']) pixels = bytearray(changed.PixelData); pixels[0] ^= 1 changed.PixelData = bytes(pixels) changed.save_as(paths['left.dcm'], enforce_file_format=True) engine = FakeEngine() app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path, static_root=static) with TestClient(app) as client: loaded = client.post('/api/examples/synthetic/load').json() assert loaded['status'] == 'completed' study = loaded['result']['studies'][0] job = client.post('/api/studies/' + study['id'] + '/run', json={}).json() failed = wait(client, job) assert failed['status'] == 'failed' and 'checksum' in failed['error'] assert engine.calls == [] assert not app.state.store.workspaces assert not list(app.state.store.studies[study['id']].directory.iterdir()) def test_changed_packaged_preview_never_loads_as_verified(cache_fixture, tmp_path): example, payload, _, examples_path, paths = cache_fixture static = add_packaged_previews(example, payload, examples_path, paths) (static / example['files'][0]['preview']['video']).write_bytes(b'changed') app = create_app(data_root=tmp_path / 'uploads', engine=FakeEngine(), examples_path=examples_path, static_root=static) with TestClient(app) as client: job = client.post('/api/examples/synthetic/load').json() assert job['status'] == 'failed' and 'preview checksum' in job['error'] assert not app.state.store.studies @pytest.mark.parametrize('operation', ['run', 'classify']) def test_hydration_and_engine_progress_count_completed_work_monotonically(cache_fixture, tmp_path, operation): example, payload, _, examples_path, paths = cache_fixture static = add_packaged_previews(example, payload, examples_path, paths) engine = FakeEngine() app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path, static_root=static) snapshots = [] original_hydrate = app.state.jobs._hydrate def current_progress(): return next(job['progress'] for job in app.state.jobs.items.values() if job['status'] == 'running') def monitored_hydrate(study, callback): def observed(stage, detail=None): callback(stage, detail) snapshots.append(('hydrate', current_progress())) original_hydrate(study, observed) app.state.jobs._hydrate = monitored_hydrate engine_units = 10 if operation == 'run' else 2 original = engine.infer if operation == 'run' else engine.classify def report_engine(callback): # Weight downloads only update the message; they do not invent progress. callback('download', {'message': 'Downloading verified model weights.'}) snapshots.append(('weights', current_progress())) for current in range(1, engine_units + 1): callback('infer' if operation == 'run' else 'classify', {'current': current, 'total': engine_units}) snapshots.append(('engine', current_progress())) def infer(left, right, callback): report_engine(callback) return original(left, right, callback) def classify(paths, callback): report_engine(callback) return original(paths, callback) if operation == 'run': engine.infer = infer else: engine.classify = classify with TestClient(app) as client: study = client.post('/api/examples/synthetic/load').json()['result']['studies'][0] response = client.post('/api/studies/' + study['id'] + '/' + operation, **({'json': {}} if operation == 'run' else {})) finished = wait(client, response.json()) assert finished['status'] == 'completed' and finished['progress'] == 1. values = [value for _, value in snapshots] assert values == sorted(values) hydration_end = [value for stage, value in snapshots if stage == 'hydrate'][-1] assert hydration_end == pytest.approx(2 / (2 + engine_units)) assert next(value for stage, value in snapshots if stage == 'weights') == hydration_end assert next(value for stage, value in snapshots if stage == 'engine') == pytest.approx(3 / (2 + engine_units)) if operation == 'run': assert finished['result']['calibrated'] == 10. def test_valid_cache_preserves_automatic_low_confidence_and_short_exclusions(cache_fixture, tmp_path): example, payload, cache_path, examples_path, paths = cache_fixture for frames, probability, reason in ( (12, .5, 'Low-confidence artery classification; automatically excluded.'), (5, None, 'Fewer than 10 frames; automatically excluded.'), ): data = dicom(example['study_uid'], frames=frames) ds = pydicom.dcmread(io.BytesIO(data), stop_before_pixels=True) filename = f'excluded-{frames}.dcm' path = tmp_path / filename path.write_bytes(data) paths[filename] = str(path) entry = {'path': filename, 'sop_uid': str(ds.SOPInstanceUID), 'artery': 'exclude'} example['files'].append(entry) payload['files'].append({**entry, 'sha256': hashlib.sha256(data).hexdigest()}) payload['classification']['outputs'].append({'sop_uid': entry['sop_uid'], 'frames': frames, 'artery': 'exclude', 'probability_right': probability, 'reason': reason}) cache_path.write_text(json.dumps(payload)) examples_path.write_text(json.dumps([example])) engine = FakeEngine() app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path) with TestClient(app) as client: loaded = wait(client, client.post('/api/examples/synthetic/load').json()) assert loaded['status'] == 'completed' study = loaded['result']['studies'][0] assert study['classification_complete'] is True assert [p['artery'] for p in study['projections']] == ['left', 'right', 'exclude', 'exclude'] assert study['projections'][2]['probability'] == .5 assert study['projections'][3]['probability'] is None scored = wait(client, client.post('/api/studies/' + study['id'] + '/run', json={}).json()) assert scored['status'] == 'completed' assert [len(p) for p in engine.calls[-1]] == [1, 1]