File size: 8,926 Bytes
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
580f4e5
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
49442cb
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
 
 
 
49442cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
49442cb
b78ff28
 
 
49442cb
 
 
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
 
 
 
 
 
 
b78ff28
49442cb
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f4e5
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""End-to-end tests for the Submit tab's handler.

The Hub and Hugging Face's profile pages are patched out; everything else —
validation, scoring, the cooldown, the ordering of stores — is the real code
path a participant hits.
"""

from datetime import timedelta
from pathlib import Path

import pandas as pd
import pytest

import submission as submit_module
from plug_challenge import aggregate
from plug_challenge.benchmarks import BENCHMARKS, ID_COLUMN, get, select_track

from .conftest import write_bundle


class FakeStore:
    """Records what a submission would have written, instead of writing it."""

    def __init__(self, truth):
        self.truth = truth
        self.bundles: list[str] = []
        self.scores: list[dict] = []
        self.entries: list[dict] = []
        self.last_submission: dict = {}
        self.fail_on_upload = False

    def configured(self):
        return True

    def available_ground_truth(self, track):
        return {name: select_track(frame, track) for name, frame in self.truth.items()}

    def expected_ids(self, truth):
        return {name: set(frame[ID_COLUMN].astype(str)) for name, frame in truth.items()}

    def upload_submission(self, safe_username, submission_id, bundle_path, metadata):
        if self.fail_on_upload:
            raise RuntimeError("hub is down")
        self.bundles.append(submission_id)
        return f"submissions/{safe_username}/{submission_id}/bundle.zip"

    def save_scores(self, safe_username, submission_id, scores):
        self.scores.append(scores)

    def append_leaderboard_entry(self, entry):
        self.entries.append(entry)

    def last_submission_at(self, safe_username, track):
        return self.last_submission.get(track)

    def now(self):
        return pd.Timestamp("2026-05-01T12:00:00Z").to_pydatetime()


@pytest.fixture
def fake_store(monkeypatch, truth):
    store = FakeStore(truth)
    monkeypatch.setattr(submit_module, "store", store)
    monkeypatch.setattr(submit_module, "validate_hf_username", lambda username: True)
    monkeypatch.setattr(submit_module, "validate_model_details", lambda tag: str(tag or "").strip())
    monkeypatch.setattr(submit_module, "CURRENT_PHASE", 1)
    return store


def _submit(bundle: Path | None, **overrides):
    kwargs = {
        "username": "someone",
        "track": "unsupervised",
        "user_alias": "Team Alias",
        "anonymous": False,
        "participant_name": "Jane Smith",
        "discord_username": "jane",
        "email": "jane@example.com",
        "affiliation": "Somewhere",
        "model_tag": "https://example.org/report",
        "used_proprietary_data": False,
        "open_source_code": False,
        "file_input": None if bundle is None else str(bundle),
    }
    kwargs.update(overrides)
    return submit_module.submit_bundle(**kwargs)


def _text(update: dict) -> str:
    return update["value"]


def test_a_valid_bundle_is_stored_and_scored(fake_store, bundle):
    result = _text(_submit(bundle))
    assert "Submission accepted" in result
    assert "PLUG Score" in result
    assert len(fake_store.bundles) == 1
    assert len(fake_store.entries) == 1
    entry = fake_store.entries[0]
    assert entry["track"] == "unsupervised"
    assert 0.0 < entry["plug_score"] <= 1.0
    for spec in BENCHMARKS:
        assert f"{spec.name}__{spec.primary.key}_mean" in entry


def test_a_supervised_bundle_is_scored_on_the_test_rows(fake_store, supervised_bundle):
    result = _text(_submit(supervised_bundle, track="supervised"))
    assert "Submission accepted" in result
    assert "supervised leaderboard" in result
    entry = fake_store.entries[0]
    assert entry["track"] == "supervised"
    # Three in four synthetic datapoints are test rows (conftest._splits).
    assert entry["megascale__n"] == 30


def test_the_supervised_track_rejects_predictions_for_training_rows(fake_store, bundle):
    result = _text(_submit(bundle, track="supervised"))
    assert "not accepted" in result
    assert "not scored in this track" in result
    assert fake_store.bundles == []


def test_the_unsupervised_track_needs_every_row(fake_store, supervised_bundle):
    result = _text(_submit(supervised_bundle, track="unsupervised"))
    assert "not accepted" in result
    assert "have no prediction" in result


def test_an_unknown_track_is_rejected(fake_store, bundle):
    assert "Choose a track" in _text(_submit(bundle, track="semi-supervised"))


def test_the_response_shows_every_benchmark(fake_store, bundle):
    result = _text(_submit(bundle))
    for spec in BENCHMARKS:
        assert spec.label in result


def test_an_invalid_bundle_stores_nothing_and_starts_no_cooldown(fake_store, predictions, tmp_path):
    predictions["megascale"]["pred"] = 1.0  # constant column
    result = _text(_submit(write_bundle(predictions, tmp_path / "bad.zip")))
    assert "not accepted" in result
    assert "constant" in result
    assert "cooldown has not started" in result
    assert fake_store.bundles == []
    assert fake_store.entries == []


def test_the_cooldown_blocks_a_quick_resubmission(fake_store, bundle):
    fake_store.last_submission["unsupervised"] = fake_store.now() - timedelta(hours=1)
    result = _text(_submit(bundle))
    assert "Please wait" in result
    assert fake_store.bundles == []


def test_the_cooldown_expires(fake_store, bundle):
    fake_store.last_submission["unsupervised"] = fake_store.now() - timedelta(hours=48)
    assert "accepted" in _text(_submit(bundle))


def test_the_cooldown_is_per_track(fake_store, supervised_bundle):
    fake_store.last_submission["unsupervised"] = fake_store.now() - timedelta(hours=1)
    assert "accepted" in _text(_submit(supervised_bundle, track="supervised"))


def test_anonymous_submission_requires_an_alias(fake_store, bundle):
    result = _text(_submit(bundle, anonymous=True, user_alias="  "))
    assert "alias is required" in result
    assert fake_store.bundles == []


def test_anonymous_submission_records_the_alias_not_the_username(fake_store, bundle):
    _submit(bundle, anonymous=True, user_alias="Team Alias")
    entry = fake_store.entries[0]
    assert entry["username"] == "Team Alias"
    # The real account is still kept as the (non-displayed) dedup/cooldown key.
    assert entry["safe_username"] == "someone"


def test_a_missing_file_is_rejected(fake_store):
    assert "upload your submission bundle" in _text(_submit(None))


def test_an_unknown_username_is_rejected(fake_store, bundle, monkeypatch):
    monkeypatch.setattr(submit_module, "validate_hf_username", lambda username: False)
    result = _text(_submit(bundle))
    assert "could not be found" in result
    assert fake_store.bundles == []


def test_a_banned_username_is_rejected(fake_store, bundle, monkeypatch):
    monkeypatch.setattr(submit_module, "BANNED_USERNAMES", {"someone": "Multiple accounts"})
    result = _text(_submit(bundle))
    assert "blocked" in result
    assert "Multiple accounts" in result


def test_a_bad_email_is_rejected(fake_store, bundle):
    assert "valid email" in _text(_submit(bundle, email="not-an-email"))


def test_a_method_report_link_is_required(fake_store, bundle, monkeypatch):
    monkeypatch.setattr(submit_module, "validate_model_details", lambda tag: "Not submitted")
    result = _text(_submit(bundle, model_tag="", open_source_code=False))
    assert "method report link is required" in result
    assert fake_store.bundles == []


def test_an_unreachable_report_link_is_rejected(fake_store, bundle, monkeypatch):
    monkeypatch.setattr(submit_module, "validate_model_details", lambda tag: "Invalid link")
    result = _text(_submit(bundle, open_source_code=False))
    assert "Could not open the method report link" in result
    assert fake_store.bundles == []


def test_submissions_are_refused_outside_the_open_phase(fake_store, bundle, monkeypatch):
    monkeypatch.setattr(submit_module, "CURRENT_PHASE", 2)
    assert "not open" in _text(_submit(bundle))


def test_a_storage_failure_is_reported_with_the_submission_id(fake_store, bundle):
    fake_store.fail_on_upload = True
    result = _text(_submit(bundle))
    assert "storing it failed" in result
    assert fake_store.entries == []


def test_a_missing_ground_truth_blocks_submissions(fake_store, bundle):
    fake_store.truth = {}
    assert "No ground truth" in _text(_submit(bundle))


def test_a_single_benchmark_bundle_is_accepted_and_the_rest_count_as_chance(
    fake_store, predictions, tmp_path
):
    one = write_bundle({"megascale": predictions["megascale"]}, tmp_path / "one.zip")
    result = _text(_submit(one))
    assert "Submission accepted" in result
    entry = fake_store.entries[0]
    spec = get("megascale")
    covered = aggregate.normalise(entry[f"megascale__{spec.primary.key}_mean"], spec.primary)
    assert entry["plug_score"] == pytest.approx(covered / len(BENCHMARKS))
    assert "ppi__auroc_mean" not in entry