Spaces:
Running on T4

File size: 5,217 Bytes
ff80158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""GPU queue behaviour through a real Gradio server (models mocked).

Separate gradio_client Clients act as separate users:
1. user 1's uncached analysis holds the GPU (analyze_slide blocks),
2. user 2's uncached analysis waits in the GPU queue (not Gradio's queue),
3. user 3's cached analysis returns while user 1 is still computing,
4. user 2 clicks Cancel and leaves the GPU queue without running.
"""

import tempfile
import threading
import time
from pathlib import Path
from unittest.mock import MagicMock, patch

import pandas as pd
import pytest
from gradio_client import Client, handle_file
from PIL import Image

from mosaic.gpu_queue import gpu_queue


def _result():
    mask = Image.new("RGB", (64, 64), color=(200, 100, 100))
    aeon = pd.DataFrame({"Cancer Subtype": ["LUAD"], "Confidence": [0.9]}).set_index(
        "Cancer Subtype"
    )
    paladin = pd.DataFrame(
        {"Cancer Subtype": ["LUAD"], "Biomarker": ["EGFR"], "Prob. Present": [0.4]}
    )
    return mask, aeon, paladin


def _submit(url, slide, client=None):
    client = client or Client(url, verbose=False)  # new client = new session
    return client.submit(
        input_mode_val="Upload Files",
        slides=[handle_file(str(slide))],
        settings_input_val={
            "headers": [
                "Slide",
                "Site Type",
                "Sex",
                "Tissue Site",
                "Cancer Subtype",
                "Segmentation Config",
            ],
            "data": [[slide.name, "Primary", "Male", "Unknown", "Unknown", "Biopsy"]],
        },
        site_type="Primary",
        sex="Male",
        tissue_site="Unknown",
        cancer_subtype="Unknown",
        seg_config="Biopsy",
        session_id=None,
        api_name="/analyze_with_tcga_support",
    )


def _wait_for(predicate, timeout=30):
    end = time.monotonic() + timeout
    while time.monotonic() < end:
        if predicate():
            return True
        time.sleep(0.2)
    return False


@pytest.fixture
def slides(tmp_path):
    out = {}
    for name, color in (
        ("compute.svs", (200, 150, 150)),
        ("cached.svs", (90, 60, 160)),
    ):
        path = tmp_path / name
        Image.new("RGB", (128, 128), color=color).save(path, format="TIFF")
        out[name] = path
    return out


def test_queue_cache_and_cancel_through_real_gradio(gradio_server, slides, monkeypatch):
    monkeypatch.setattr(gpu_queue, "slots", 1)  # one analysis at a time, as on a T4
    upload_root = Path(tempfile.gettempdir()) / "gradio"
    cached_keys = set()
    discovering = {"on": True}

    def load_cached(file_uuid, settings_hash, *args, **kwargs):
        # During discovery every lookup is a hit and its key is remembered;
        # afterwards only those keys hit.
        if discovering["on"]:
            cached_keys.add((file_uuid, settings_hash))
            return _result()
        return _result() if (file_uuid, settings_hash) in cached_keys else None

    release = threading.Event()
    computed = []

    def analyze(**kwargs):
        computed.append(Path(kwargs["slide_path"]).name)
        release.wait(60)
        return _result()

    with (
        patch("mosaic.ui.pipeline.get_tcga_cache_directory", return_value=upload_root),
        patch("mosaic.ui.pipeline.load_analysis_results", side_effect=load_cached),
        patch("mosaic.ui.pipeline.analyze_slide", side_effect=analyze),
        patch("mosaic.ui.pipeline.load_all_models", return_value=MagicMock()),
        patch("mosaic.ui.pipeline.save_analysis_results"),
        patch("mosaic.ui.pipeline.upload_results_to_hf"),
        patch("mosaic.ui.pipeline.slide_read_error", return_value=None),
        patch(
            "mosaic.ui.pipeline.get_oncotree_code_name",
            side_effect=lambda code: f"Mock {code}",
        ),
    ):
        # Learn the cache key of the "cached" slide (served without the GPU).
        _submit(gradio_server["url"], slides["cached.svs"]).result(timeout=60)
        discovering["on"] = False
        assert computed == []

        user1 = _submit(gradio_server["url"], slides["compute.svs"])
        assert _wait_for(lambda: len(gpu_queue.status()["running"]) == 1)

        user2_session = Client(gradio_server["url"], verbose=False)
        user2 = _submit(gradio_server["url"], slides["compute.svs"], user2_session)
        assert _wait_for(
            lambda: gpu_queue.status()["waiting"] == 1
        ), "second analysis should wait in the GPU queue, not Gradio's queue"

        start = time.monotonic()
        _submit(gradio_server["url"], slides["cached.svs"]).result(timeout=30)
        assert time.monotonic() - start < 30
        assert len(gpu_queue.status()["running"]) == 1  # user 1 still computing

        # The Cancel button, from user 2's session.
        user2_session.predict(api_name="/cancel_analysis")
        assert _wait_for(
            lambda: gpu_queue.status()["waiting"] == 0, timeout=20
        ), "Cancel should remove the run from the GPU queue"

        release.set()
        user1.result(timeout=60)
        assert _wait_for(lambda: gpu_queue.status()["running"] == [])
        assert computed == ["compute.svs"]  # user 2 never reached the GPU