File size: 9,210 Bytes
498f80b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Example use cases for the reward validity gate and code extraction.

These cover two failure modes found by rescoring real traces from
``qwen3.5:0.8b`` and ``lfm3``:

1. Unparseable output used to earn a *positive* reward, because every rule
   rewards the absence of a violation it cannot find. Garbage therefore
   outranked real, working code -- the exact opposite of the training signal.
2. Truncated generations leaking their opening ```python fence into the
   extracted code, so a mostly-fine sample failed to parse.
"""

import ast
import json

import pytest

from guac_coder.decision_judge import (
    DecisionJudgeConfig,
    combined_decision_reward,
    compute_decision_rewards,
)
from guac_coder.grpo_rewards import (
    VALIDITY_FLOOR,
    combined_grpo_reward,
    compute_grpo_rewards,
    is_valid_python,
)
from guac_coder.trace import extract_code

UNPARSEABLE = {
    "unterminated_call": "import pandas as pd\n\ndf = pd.DataFrame(",
    "truncated_def": "def f(\n    x = ",
    "prose": "this is not python at all!!! 12345",
    "empty": "",
    "whitespace": "   \n\t\n",
    "stray_fence": "```python\n",
}

WORKING_SCRIPT = '''import logging

logger = logging.getLogger(__name__)


def normalize(values, peak):
    """Scale each value by the peak, guarding the zero case."""
    if peak == 0:
        return [0.0 for _ in values]
    return [v / peak for v in values]


if __name__ == "__main__":
    logger.info("%s", normalize([1, 2], 2))
'''


@pytest.mark.parametrize("name,code", sorted(UNPARSEABLE.items()))
def test_unparseable_code_is_rejected(name, code):
    """Anything we cannot inspect is not valid Python."""
    assert is_valid_python(code) is False, name


@pytest.mark.parametrize(
    "prose",
    [
        "this is not python",  # a legal comparison of three names
        "data is loaded",  # a legal comparison
    ],
)
def test_prose_that_parses_is_still_rejected(prose):
    """Syntax alone is too weak: some model prose parses as an expression.

    ``"this is not python"`` is a valid comparison of three names, so a bare
    ``ast.parse`` check would happily accept it and then hand it the rules'
    "no violation found" bonus.
    """
    ast.parse(prose)  # does not raise: it is syntactically valid
    assert is_valid_python(prose) is False


@pytest.mark.parametrize(
    "prose",
    ["load the data", "please print the data", "return the result", "plot the data"],
)
def test_prose_that_does_not_parse_is_rejected(prose):
    """Most prose fails to parse outright; these are the other half."""
    with pytest.raises(SyntaxError):
        ast.parse(prose)
    assert is_valid_python(prose) is False


def test_working_script_is_valid():
    """A normal, well-formed script passes the gate."""
    assert is_valid_python(WORKING_SCRIPT) is True


@pytest.mark.parametrize("name,code", sorted(UNPARSEABLE.items()))
def test_unparseable_code_scores_at_the_floor(name, code):
    """Every rule reports the floor, not the 'no violation found' bonus."""
    rules = compute_grpo_rewards(code)
    assert set(rules.values()) == {VALIDITY_FLOOR}, name


def test_garbage_never_outranks_working_code():
    """The regression that motivated the gate.

    Before the gate, ``"this is not python"`` scored +0.077 while a real
    script scored +0.192: only a 0.115 gap, with garbage on the positive side.
    """
    garbage = combined_grpo_reward("this is not python at all!!! 12345")
    working = combined_grpo_reward(WORKING_SCRIPT)
    assert garbage < 0 < working
    assert working - garbage > 0.5


def test_empty_completion_is_not_rewarded():
    """An empty string used to score +0.077 because the AST was empty but valid."""
    assert combined_grpo_reward("") < 0
    assert combined_grpo_reward("") == VALIDITY_FLOOR


def test_decision_rater_applies_the_same_floor():
    """The decision rater shares the gate, so both raters agree on non-code.

    ``judge_fn`` is never called: the gate rejects the sample first, which also
    means a garbage completion costs no HTTP round-trip.
    """
    calls = []

    def never_called(code, cfg=None):
        calls.append(code)
        return {}

    rewards = compute_decision_rewards("not python at all", judge_fn=never_called)
    assert set(rewards.values()) == {VALIDITY_FLOOR}
    assert calls == []


def test_decision_rater_still_calls_model_for_valid_code():
    """The gate must not block legitimate scoring."""
    calls = []

    def fake_judge(code, cfg=None):
        calls.append(code)
        return {name: 0.0 for name in compute_grpo_rewards(WORKING_SCRIPT)}

    compute_decision_rewards(WORKING_SCRIPT, judge_fn=fake_judge)
    assert calls == [WORKING_SCRIPT]


TRUNCATED_RESPONSES = {
    "unterminated_fence": "```python\nimport logging\nlogger = logging.getLogger()\n",
    "unterminated_fence_with_prose": "Here you go:\n```python\ndef add(a, b):\n    return a + b\n",
    "closed_fence": "```python\ndef add(a, b):\n    return a + b\n```\n",
}


@pytest.mark.parametrize("name,text", sorted(TRUNCATED_RESPONSES.items()))
def test_extract_code_strips_fences(name, text):
    """Extracted code must not begin with a markdown fence."""
    code, source = extract_code(text)
    assert not code.lstrip().startswith("```"), (name, source)
    assert "import logging" in code or "def add" in code


def test_unterminated_fence_is_labelled_and_parses():
    """A truncated fence yields parseable code plus a distinct source label."""
    code, source = extract_code("```python\ndef add(a, b):\n    return a + b\n")
    assert source == "fence_unterminated"
    assert not code.lstrip().startswith("```")
    ast.parse(code)


def test_closed_fence_still_wins_over_whole_text():
    """Normal fenced output is unaffected by the unterminated-fence fix."""
    code, source = extract_code("```python\ndef add(a, b):\n    return a + b\n```")
    assert source == "fence"
    assert code == "def add(a, b):\n    return a + b"


def test_empty_response_is_reported_as_empty():
    """No text yields no code and no reward, not a floor-scored empty string."""
    assert extract_code("") == ("", "empty")
    assert extract_code("   \n\n") == ("", "empty")


def test_thinking_only_response_yields_no_code():
    """A response with only prose is not mistaken for code."""
    code, source = extract_code("I will now write the program. It will load a CSV.")
    assert code == ""
    assert source == "empty"


def test_decision_rater_floors_real_truncated_sample():
    """Rescoring a real truncated trace: previously +0.269, now at the floor.

    The stored reward came from an early run whose extraction kept the fence.
    """
    truncated = "```python\nimport logging\n\ndef f(\n"
    code, _ = extract_code(truncated)
    assert not is_valid_python(code)
    cfg = DecisionJudgeConfig(model="clef:cloud")
    assert combined_decision_reward(code, cfg=cfg) == VALIDITY_FLOOR


# ---------------------------------------------------------------------------
# Exports must never emit unparseable code as a training target
# ---------------------------------------------------------------------------

from guac_coder.trace_export import export_grpo, export_sft  # noqa: E402


def _trace(code, reward, task_id=0, model="tiny", source="fence"):
    return {
        "trace_id": f"t{task_id}-{abs(hash(code)) % 9999}",
        "model": model,
        "task_id": task_id,
        "sample_index": 0,
        "task": "normalize values",
        "code": code,
        "code_source": source,
        "total_reward": reward,
    }


def test_export_sft_skips_unparseable_best_trace(tmp_path):
    """A truncated sample with a high reward must not become the SFT target.

    This mirrors the real corpus: a truncated generation scored +0.346, above
    the best parseable sample, so ranking alone would have selected it.
    """
    traces = [
        _trace("def broken(\n    x = ", 0.346, task_id=0),
        _trace(WORKING_SCRIPT, 0.192, task_id=0),
    ]
    out = tmp_path / "sft.jsonl"
    written = export_sft(traces, str(out))
    assert written == 1
    record = json.loads(out.read_text().strip())
    assert "def broken(" not in record["messages"][-1]["content"]
    assert "normalize" in record["messages"][-1]["content"]


def test_export_sft_skips_task_with_only_unparseable_traces(tmp_path):
    """If every sample for a task is garbage, the task is dropped entirely."""
    traces = [
        _trace("def broken(\n    x = ", 0.4, task_id=0),
        _trace("this is not python", 0.3, task_id=0),
    ]
    out = tmp_path / "sft.jsonl"
    assert export_sft(traces, str(out)) == 0
    assert out.read_text() == ""


def test_export_grpo_omits_unparseable_traces(tmp_path):
    """GRPO records are the reward-modelling view; garbage must not appear."""
    traces = [
        _trace(WORKING_SCRIPT, 0.192, task_id=0),
        _trace("import pandas as pd\ndf = pd.DataFrame(", -1.0, task_id=1),
    ]
    out = tmp_path / "grpo.jsonl"
    written = export_grpo(traces, str(out))
    assert written == 1
    rows = [json.loads(line) for line in out.read_text().splitlines() if line.strip()]
    assert len(rows) == 1
    assert all(is_valid_python(r["completion"]) for r in rows)