File size: 10,346 Bytes
0a6c641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
"""Tests for the per-step + terminal reward function.



This is the most safety-critical module in CERNenv. The test suite is

structured around the same anti-hacking principles called out in the

hackathon FAQ (Q12, Q13, Q42, Q56, Q57):



* the terminal grade should *dominate* total reward,

* shaping rewards must be hard to farm,

* obvious model "cheats" (string-spam, claim-spam, JSON-spam) must

  not produce high reward.

"""

from __future__ import annotations

import pytest

from models import (
    ActionType,
    DiscoveryClaim,
    ExperimentAction,
    IntermediateOutput,
    OutputType,
)
from server.rewards.reward_function import (
    RewardWeights,
    _mass_score,
    _significance_overclaim,
    _significance_score,
    compute_step_reward,
    compute_terminal_reward,
)
from server.rules.engine import RuleResult, ViolationCode
from server.simulator.latent_state import FullLatentState, LatentParticle, ResourceState


# ── helpers ─────────────────────────────────────────────────────────────


def _passing_rule_result() -> RuleResult:
    return RuleResult(allowed=True)


def _failing_rule_result(*violations: ViolationCode) -> RuleResult:
    r = RuleResult(allowed=True)
    for v in violations:
        r.add(v, str(v))
    return r


def _ok_output(action_type: ActionType = ActionType.CONFIGURE_BEAM) -> IntermediateOutput:
    return IntermediateOutput(
        output_type=OutputType.BEAM_CONFIG,
        step_index=0,
        success=True,
        quality_score=0.9,
        summary="ok",
    )


def _fresh_state() -> FullLatentState:
    return FullLatentState(
        particle=LatentParticle(),
        resources=ResourceState(),
    )


# ── _mass_score ─────────────────────────────────────────────────────────


def test_mass_score_perfect_inside_tolerance():
    assert _mass_score(125.0, 125.0, unc=None) == pytest.approx(1.0)


def test_mass_score_decays_outside_tolerance():
    high = _mass_score(125.0, 125.5, unc=None)
    low = _mass_score(125.0, 130.0, unc=None)
    assert 0.0 < low < high <= 1.0


def test_mass_score_zero_when_far_off():
    assert _mass_score(125.0, 200.0, unc=None) == 0.0


def test_mass_score_returns_zero_when_claim_missing():
    assert _mass_score(125.0, None, None) == 0.0


# ── _significance_score and overclaim ───────────────────────────────────


def test_significance_score_uses_measured_value():
    """Under-claiming is fine (we just return the base); over-claiming is

    actively penalised (anti-hacking)."""
    s = _fresh_state()
    s.progress.best_significance_sigma = 5.0
    score_match = _significance_score(s, claim_sigma=5.0)
    score_over = _significance_score(s, claim_sigma=20.0)
    score_none = _significance_score(s, claim_sigma=None)
    assert score_match == pytest.approx(1.0)
    assert score_over < score_match
    assert score_none == 0.0


def test_significance_overclaim_only_above_threshold():
    s = _fresh_state()
    s.progress.best_significance_sigma = 4.0
    assert _significance_overclaim(s, claim_sigma=4.5) == 0.0
    assert _significance_overclaim(s, claim_sigma=10.0) > 0.0


# ── compute_step_reward: tool_fit gating (anti-hacking) ─────────────────


def test_bogus_method_string_is_penalised_not_rewarded():
    state = _fresh_state()
    action = ExperimentAction(
        action_type=ActionType.FIT_RESONANCE,
        method="LITERAL_GIBBERISH_BOGUS_LMAO",
    )
    out = _ok_output()
    result = compute_step_reward(
        action=action,
        output=out,
        state_before=state,
        state_after=state,
        rule_result=_passing_rule_result(),
    )
    assert "tool_fit" not in result.breakdown.components
    assert result.breakdown.components.get("bogus_method", 0.0) < 0.0


def test_real_method_with_correct_category_is_rewarded():
    state = _fresh_state()
    action = ExperimentAction(
        action_type=ActionType.FIT_RESONANCE,
        method="ROOT_RooFit",  # ANALYSIS category, matches FIT_RESONANCE
    )
    out = _ok_output()
    result = compute_step_reward(
        action=action,
        output=out,
        state_before=state,
        state_after=state,
        rule_result=_passing_rule_result(),
    )
    assert result.breakdown.components.get("tool_fit", 0.0) > 0.0


def test_real_method_with_mismatched_category_is_silent():
    state = _fresh_state()
    action = ExperimentAction(
        action_type=ActionType.CALIBRATE_DETECTOR,
        method="BumpHunter",  # STATISTICS, mismatch with CALIBRATION
    )
    out = _ok_output()
    result = compute_step_reward(
        action=action,
        output=out,
        state_before=state,
        state_after=state,
        rule_result=_passing_rule_result(),
    )
    assert "tool_fit" not in result.breakdown.components
    # method IS in the registry → no bogus_method penalty either
    assert "bogus_method" not in result.breakdown.components


# ── compute_step_reward: repeat-action penalty ──────────────────────────


def test_repeat_action_penalty_escalates():
    """Three identical action_types in a row should be penalised."""
    from models import PipelineStepRecord

    state = _fresh_state()
    action_type = ActionType.REQUEST_THEORY_REVIEW
    history = [
        PipelineStepRecord(
            step_index=i,
            action_type=action_type,
            output_type=OutputType.THEORY_REVIEW,
            output_summary="...",
        )
        for i in range(3)
    ]
    action = ExperimentAction(action_type=action_type)
    result = compute_step_reward(
        action=action,
        output=_ok_output(),
        state_before=state,
        state_after=state,
        rule_result=_passing_rule_result(),
        history=history,
    )
    assert result.breakdown.components.get("repeat_action", 0.0) < 0.0


def test_no_repeat_penalty_for_first_use():
    state = _fresh_state()
    action = ExperimentAction(action_type=ActionType.CONFIGURE_BEAM)
    result = compute_step_reward(
        action=action,
        output=_ok_output(),
        state_before=state,
        state_after=state,
        rule_result=_passing_rule_result(),
        history=[],
    )
    assert "repeat_action" not in result.breakdown.components


# ── compute_step_reward: clip ───────────────────────────────────────────


def test_step_reward_is_clipped_above():
    state = _fresh_state()
    weights = RewardWeights(step_reward_clip=0.1)
    action = ExperimentAction(action_type=ActionType.CONFIGURE_BEAM, method="ATLAS_HLT")
    result = compute_step_reward(
        action=action,
        output=_ok_output(),
        state_before=state,
        state_after=state,
        rule_result=_passing_rule_result(),
        weights=weights,
    )
    assert result.reward <= 0.1 + 1e-9


# ── compute_terminal_reward: correctness + overconfidence ───────────────


def test_terminal_reward_high_for_correct_calibrated_claim():
    s = _fresh_state()
    s.particle = LatentParticle(
        mass_gev=125.0, primary_channel="diphoton", spin=0, parity="+", width_gev=0.004,
    )
    s.progress.best_significance_sigma = 5.5
    claim = DiscoveryClaim(
        mass_estimate_gev=125.0,
        mass_uncertainty_gev=0.5,
        significance_sigma=5.5,
        decay_channel="diphoton",
        spin_hypothesis=0,
        parity="+",
        confidence=0.9,
    )
    out = compute_terminal_reward(state=s, claim=claim)
    assert out.discovered
    assert out.correct_mass and out.correct_channel and out.correct_spin
    assert out.reward > 1.0


def test_terminal_reward_overconfident_wrong_is_punished():
    s = _fresh_state()
    s.particle = LatentParticle(mass_gev=125.0, primary_channel="diphoton")
    s.progress.best_significance_sigma = 4.5
    claim = DiscoveryClaim(
        mass_estimate_gev=600.0,  # way off
        decay_channel="dijet",     # wrong
        significance_sigma=5.0,
        confidence=0.95,
    )
    out = compute_terminal_reward(state=s, claim=claim)
    assert not out.discovered
    assert out.reward < 0.0
    assert out.breakdown.components.get("overconfident_wrong", 0.0) < 0.0


def test_significance_overclaim_penalty_fires():
    s = _fresh_state()
    s.particle = LatentParticle(mass_gev=125.0, primary_channel="diphoton")
    s.progress.best_significance_sigma = 1.0  # weak evidence
    claim = DiscoveryClaim(
        mass_estimate_gev=125.0,
        decay_channel="diphoton",
        significance_sigma=20.0,  # absurd over-claim
        confidence=0.5,
    )
    out = compute_terminal_reward(state=s, claim=claim)
    assert out.breakdown.components.get("overclaim_significance", 0.0) < 0.0


def test_no_information_claim_clamped_nonpositive():
    s = _fresh_state()
    claim = DiscoveryClaim()  # everything None / zero
    out = compute_terminal_reward(state=s, claim=claim)
    assert out.reward <= 0.0


# ── Hard / soft / failure penalties ─────────────────────────────────────


def test_hard_violation_dominates_step_reward():
    state = _fresh_state()
    rule = _failing_rule_result(ViolationCode.PREREQ_MISSING)
    action = ExperimentAction(action_type=ActionType.COLLECT_COLLISIONS)
    out = IntermediateOutput(
        output_type=OutputType.FAILURE_REPORT,
        step_index=0,
        success=False,
        quality_score=0.0,
    )
    r = compute_step_reward(
        action=action,
        output=out,
        state_before=state,
        state_after=state,
        rule_result=rule,
    )
    assert r.reward < 0.0