"""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)