scalingX commited on
Commit
d8261e7
·
verified ·
1 Parent(s): bf202b2

Add 10000 GitHub Trending pr_diff environments (part 98)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/sp00nznet__ps3recomp-478/tests/test.sh +25 -0
  2. tasks/sp00nznet__ps3recomp-478/tests/verifier.py +737 -0
  3. tasks/sp00nznet__ps3recomp-482/environment/Dockerfile +37 -0
  4. tasks/sp00nznet__ps3recomp-482/instruction.md +22 -0
  5. tasks/sp00nznet__ps3recomp-482/solution/patch.diff +186 -0
  6. tasks/sp00nznet__ps3recomp-482/solution/solve.sh +6 -0
  7. tasks/sp00nznet__ps3recomp-482/task.toml +72 -0
  8. tasks/sp00nznet__ps3recomp-482/tests/capture.py +96 -0
  9. tasks/sp00nznet__ps3recomp-482/tests/instruction.md +22 -0
  10. tasks/sp00nznet__ps3recomp-482/tests/oracle.patch +186 -0
  11. tasks/sp00nznet__ps3recomp-482/tests/test.sh +25 -0
  12. tasks/sp00nznet__ps3recomp-482/tests/verifier.py +737 -0
  13. tasks/sp00nznet__ps3recomp-484/environment/Dockerfile +37 -0
  14. tasks/sp00nznet__ps3recomp-484/instruction.md +43 -0
  15. tasks/sp00nznet__ps3recomp-484/solution/patch.diff +110 -0
  16. tasks/sp00nznet__ps3recomp-484/solution/solve.sh +6 -0
  17. tasks/sp00nznet__ps3recomp-484/task.toml +69 -0
  18. tasks/sp00nznet__ps3recomp-484/tests/capture.py +96 -0
  19. tasks/sp00nznet__ps3recomp-484/tests/instruction.md +43 -0
  20. tasks/sp00nznet__ps3recomp-484/tests/oracle.patch +110 -0
  21. tasks/sp00nznet__ps3recomp-484/tests/test.sh +25 -0
  22. tasks/sp00nznet__ps3recomp-484/tests/verifier.py +737 -0
  23. tasks/sp00nznet__ps3recomp-485/environment/Dockerfile +37 -0
  24. tasks/sp00nznet__ps3recomp-485/instruction.md +26 -0
  25. tasks/sp00nznet__ps3recomp-485/solution/patch.diff +256 -0
  26. tasks/sp00nznet__ps3recomp-485/solution/solve.sh +6 -0
  27. tasks/sp00nznet__ps3recomp-485/task.toml +72 -0
  28. tasks/sp00nznet__ps3recomp-485/tests/capture.py +96 -0
  29. tasks/sp00nznet__ps3recomp-485/tests/instruction.md +26 -0
  30. tasks/sp00nznet__ps3recomp-485/tests/oracle.patch +256 -0
  31. tasks/sp00nznet__ps3recomp-485/tests/test.sh +25 -0
  32. tasks/sp00nznet__ps3recomp-485/tests/verifier.py +737 -0
  33. tasks/sp00nznet__ps3recomp-490/environment/Dockerfile +37 -0
  34. tasks/sp00nznet__ps3recomp-490/instruction.md +37 -0
  35. tasks/sp00nznet__ps3recomp-490/solution/patch.diff +235 -0
  36. tasks/sp00nznet__ps3recomp-490/solution/solve.sh +6 -0
  37. tasks/sp00nznet__ps3recomp-490/task.toml +72 -0
  38. tasks/sp00nznet__ps3recomp-490/tests/capture.py +96 -0
  39. tasks/sp00nznet__ps3recomp-490/tests/instruction.md +37 -0
  40. tasks/sp00nznet__ps3recomp-490/tests/oracle.patch +235 -0
  41. tasks/sp00nznet__ps3recomp-490/tests/test.sh +25 -0
  42. tasks/sp00nznet__ps3recomp-490/tests/verifier.py +737 -0
  43. tasks/sp00nznet__ps3recomp-494/environment/Dockerfile +37 -0
  44. tasks/sp00nznet__ps3recomp-494/instruction.md +69 -0
  45. tasks/sp00nznet__ps3recomp-494/solution/patch.diff +108 -0
  46. tasks/sp00nznet__ps3recomp-494/solution/solve.sh +6 -0
  47. tasks/sp00nznet__ps3recomp-494/task.toml +69 -0
  48. tasks/sp00nznet__ps3recomp-494/tests/capture.py +96 -0
  49. tasks/sp00nznet__ps3recomp-494/tests/instruction.md +69 -0
  50. tasks/sp00nznet__ps3recomp-494/tests/oracle.patch +108 -0
tasks/sp00nznet__ps3recomp-478/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/sp00nznet__ps3recomp-478/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/sp00nznet__ps3recomp-482/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/sp00nznet__ps3recomp-482/instruction.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** rsx_fp_decompiler: divide texel coordinates of a 3D texture by its depth
4
+
5
+ ## Description
6
+
7
+ `rsx_fp_apply_unnorm_scale` appends ` * float2(1/w, 1/h)` to every Sample on an unnormalised (texel-addressed) unit. A volume unit is declared `Texture3D` and sampled with a float3, so a program that reads a 3D texture with texel coordinates fails with `'__BI_Sample' : no matching overloaded function found`. The engine then drops the pipeline and those draws are silently skipped.
8
+
9
+ I hit this with an SSAO pass that samples a 32x32x32 volume in texel coordinates. With the pass gone, the AO filter after it read whatever was left at that address (a shadow map's bytes) as its input, and the whole scene came out almost black.
10
+
11
+ The fix gives `rsx_fp_apply_unnorm_scale` a volume mask and a depth per unit. A volume unit gets `float3(1/w, 1/h, 1/depth)`, which matches how RPCS3's texture cache scales r by 1/depth for 3D textures. The draw engine passes its volume mask and the texture depth. `rsx_live_draw` has no 3D textures, so it passes an empty mask and its output doesn't change. 2D and cube units produce the same HLSL as before.
12
+
13
+ Tests:
14
+ - `test_shader_msl`: new case, a TEX on an unnormalised 3D unit gets the float3 scale and translates to MSL with a `texture3d`. 121/121 pass.
15
+ - `test_fp_decompiler` (74/74), `test_rsx_draw_engine`, `test_color_feedback_engine` (45/45) and `test_shadow_engine` pass, and CTest is 15/15 on macOS arm64.
16
+ - In the game where I found it, on Metal, the SSAO pass runs again and the scene is lit: mean frame brightness goes from 7/255 to 19, close to the console.
17
+
18
+ No game data or program bytes are included.
19
+
20
+ ## Task
21
+
22
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-482/solution/patch.diff ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c
2
+ index f99986b3..995c2cc2 100644
3
+ --- a/libs/video/rsx_draw_engine.c
4
+ +++ b/libs/video/rsx_draw_engine.c
5
+ @@ -1369,18 +1369,19 @@ static u32 eng_vtex_mask(void)
6
+ * dim. No host sampling mode is unnormalised for these, so the fragment
7
+ * program divides the coordinates instead, and the divisor makes the sizes
8
+ * pipeline identity (rsx_live_draw.c keys them the same way). */
9
+ -static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][2])
10
+ +static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][3])
11
+ {
12
+ u32 mask = 0;
13
+ for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++) {
14
+ rsx_dsp_texture t;
15
+ rsx_dsp_get_texture(&g.rsx, u, &t);
16
+ - dim[u][0] = dim[u][1] = 0;
17
+ + dim[u][0] = dim[u][1] = dim[u][2] = 0;
18
+ if (!t.enabled || !(t.format & RSX_TEX_FMT_UNNORM) || !t.width || !t.height)
19
+ continue;
20
+ mask |= 1u << u;
21
+ dim[u][0] = t.width;
22
+ dim[u][1] = t.height;
23
+ + dim[u][2] = t.depth;
24
+ }
25
+ return mask;
26
+ }
27
+ @@ -1662,14 +1663,14 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
28
+ for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; ++u)
29
+ if (!(expand_units & (1u << u))) expand_masks[u] = 0;
30
+
31
+ - u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][2];
32
+ + u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][3];
33
+ /* Shadow helpers normalize against the bound resource themselves. Only
34
+ * sampled ordinary UN units need baked dimensions or cache identity. */
35
+ const u32 unnorm_mask = eng_unnorm_units(unnorm_dim) &
36
+ (fixed ? 0xFFFFu : sampled_units) & ~shadow_mask;
37
+ for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++)
38
+ if (!(unnorm_mask & (1u << u)))
39
+ - unnorm_dim[u][0] = unnorm_dim[u][1] = 0;
40
+ + unnorm_dim[u][0] = unnorm_dim[u][1] = unnorm_dim[u][2] = 0;
41
+
42
+ memset(&g.fp_constants, 0, sizeof g.fp_constants);
43
+ if (!fixed && rsx_fp_collect_constants(fp_uc, fp_size, &g.fp_constants) < 0)
44
+ @@ -1735,7 +1736,8 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
45
+ s_ps_hlsl, sizeof s_ps_hlsl, &nconst);
46
+ if (fi > 0 && nconst != g.fp_constants.count) fi = -1;
47
+ if (fi > 0 && rsx_fp_apply_unnorm_scale(s_ps_hlsl, sizeof s_ps_hlsl, unnorm_mask,
48
+ - (const u32 (*)[2])unnorm_dim, cube_mask) < 0)
49
+ + (const u32 (*)[3])unnorm_dim, cube_mask,
50
+ + vol_mask) < 0)
51
+ fi = -1;
52
+ if (fi > 0 && srgb_output &&
53
+ rsx_fp_apply_srgb_output(s_ps_hlsl, sizeof s_ps_hlsl) < 0)
54
+ diff --git a/libs/video/rsx_fp_decompiler.c b/libs/video/rsx_fp_decompiler.c
55
+ index 5ce72ef6..ebdd14c0 100644
56
+ --- a/libs/video/rsx_fp_decompiler.c
57
+ +++ b/libs/video/rsx_fp_decompiler.c
58
+ @@ -1655,10 +1655,12 @@ u32 rsx_fp_code_hash(const u8* ucode, u32 max_bytes)
59
+ * works this way, and leaves every non-UNNORM program byte-identical.
60
+ *
61
+ * Cube units are skipped: their coordinate is a float3 direction, and
62
+ - * RSX_TEX_FMT_UNNORM has no meaning for one.
63
+ + * RSX_TEX_FMT_UNNORM has no meaning for one. A volume unit (Texture3D) is
64
+ + * sampled with three coordinates, all in texels, so it is divided by its depth
65
+ + * too (RPCS3's texture cache scales a 3D texture's r by 1/depth the same way).
66
+ */
67
+ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
68
+ - const u32 dim[][2], u32 cube_mask)
69
+ + const u32 dim[][3], u32 cube_mask, u32 volume_mask)
70
+ {
71
+ if (!hlsl || !unnorm_mask) return 0;
72
+ int patched = 0;
73
+ @@ -1666,8 +1668,9 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
74
+ for (u32 u = 0; u < 16; u++) {
75
+ if (!((unnorm_mask >> u) & 1u)) continue;
76
+ if ((cube_mask >> u) & 1u) continue;
77
+ - const u32 w = dim[u][0], h = dim[u][1];
78
+ - if (!w || !h) continue;
79
+ + const u32 w = dim[u][0], h = dim[u][1], d = dim[u][2];
80
+ + const int volume = (volume_mask >> u) & 1u;
81
+ + if (!w || !h || (volume && !d)) continue;
82
+
83
+ /* Both spellings the emitter produces for a 2D unit. */
84
+ char needles[2][40];
85
+ @@ -1693,8 +1696,12 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
86
+ if (*p != ')') break;
87
+
88
+ char scale[80];
89
+ - snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)",
90
+ - 1.0 / (double)w, 1.0 / (double)h);
91
+ + if (volume)
92
+ + snprintf(scale, sizeof scale, " * float3(%.9g, %.9g, %.9g)",
93
+ + 1.0 / (double)w, 1.0 / (double)h, 1.0 / (double)d);
94
+ + else
95
+ + snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)",
96
+ + 1.0 / (double)w, 1.0 / (double)h);
97
+ const u32 slen = (u32)strlen(scale);
98
+ const u32 used = (u32)strlen(hlsl);
99
+ if (used + slen + 1 > hlsl_size) return -1;
100
+ diff --git a/libs/video/rsx_fp_decompiler.h b/libs/video/rsx_fp_decompiler.h
101
+ index 670e8863..b39968e7 100644
102
+ --- a/libs/video/rsx_fp_decompiler.h
103
+ +++ b/libs/video/rsx_fp_decompiler.h
104
+ @@ -86,11 +86,12 @@ int rsx_fp_apply_alpha_test(char* hlsl, u32 out_size, u32 func, float ref);
105
+ float rsx_fp_alpha_ref(u32 raw, u32 surface_color_format);
106
+
107
+ /* Scale texel-space (RSX_TEX_FMT_UNNORM) coordinates into HLSL's 0..1 range.
108
+ - * unnorm_mask selects the units; dim[u] gives that unit's {width, height};
109
+ - * cube units are skipped. Returns the number of Sample sites patched, or -1 if
110
+ + * unnorm_mask selects the units; dim[u] gives that unit's {width, height,
111
+ + * depth}; cube units are skipped and volume_mask units (Texture3D) are divided
112
+ + * by their depth as well. Returns the number of Sample sites patched, or -1 if
113
+ * the buffer would overflow. A no-op when unnorm_mask is 0. */
114
+ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
115
+ - const u32 dim[][2], u32 cube_mask);
116
+ + const u32 dim[][3], u32 cube_mask, u32 volume_mask);
117
+
118
+ /* Decode NV4097_SET_ALPHA_REF for the active surface color format. Ordinary
119
+ * integer render targets use the low 8 bits as UNORM8; W16Z16Y16X16 uses a
120
+ diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c
121
+ index 2e65b8ee..3b7f0151 100644
122
+ --- a/libs/video/rsx_live_draw.c
123
+ +++ b/libs/video/rsx_live_draw.c
124
+ @@ -4771,7 +4771,7 @@ static ID3D12PipelineState* get_pso(
125
+ * mode. The divisor is baked into the HLSL, so the sizes are part of the
126
+ * PSO identity and must be in the key. */
127
+ u32 unnorm_mask = 0;
128
+ - u32 unnorm_dim[16][2] = {{0}};
129
+ + u32 unnorm_dim[16][3] = {{0}};
130
+ for (u32 uu = 0; uu < 16; uu++) {
131
+ rsx_dsp_texture ut; rsx_dsp_get_texture(&g.rsx, uu, &ut);
132
+ if (!ut.enabled || !(ut.format & TEX_FMT_UNNORM)) continue;
133
+ @@ -4901,7 +4901,7 @@ static ID3D12PipelineState* get_pso(
134
+ fi = -1;
135
+ if (fi > 0) {
136
+ const int np = rsx_fp_apply_unnorm_scale(
137
+ - ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask);
138
+ + ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask, 0u);
139
+ { static int n = 0;
140
+ if (PS3_LOG_FIRST(n, 8))
141
+ fprintf(stderr, "[unnorm] mask=0x%X cube=0x%X dim0=%ux%u"
142
+ @@ -4921,7 +4921,7 @@ static ID3D12PipelineState* get_pso(
143
+ fi = -1;
144
+ if (fi > 0 && rsx_fp_apply_unnorm_scale(
145
+ ps_hlsl, sizeof(ps_hlsl), unnorm_mask,
146
+ - unnorm_dim, cube_mask) < 0)
147
+ + unnorm_dim, cube_mask, 0u) < 0)
148
+ fi = -1;
149
+ }
150
+ #if defined(YZ_PERF_PROFILE)
151
+ diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c
152
+ index de2a6dc6..017e9ddd 100644
153
+ --- a/libs/video/tests/test_shader_msl.c
154
+ +++ b/libs/video/tests/test_shader_msl.c
155
+ @@ -19,6 +19,7 @@
156
+ * what a character material does
157
+ * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0
158
+ * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map
159
+ + * FP TEX r0, TC0 unit 0, 3D UN (END) ... a volume addressed in texels
160
+ * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16
161
+ * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs
162
+ *
163
+ @@ -364,6 +365,23 @@ int main(int argc, char** argv)
164
+ check("3D TEX FP MSL", g_msl, "texture3d");
165
+ }
166
+
167
+ + /* ---- the same, with unnormalised (texel) coordinates ------------------
168
+ + * All three coordinates are texels and are divided by width, height and
169
+ + * depth. A float2 scale on the float3 coordinate does not compile, and
170
+ + * the pipeline was dropped: Resistance 3's 32x32x32 volume lookups. */
171
+ + {
172
+ + u8 fp[16];
173
+ + rsx_test_fp_tex_r0_tc0(fp, 0);
174
+ + rsx_fp_decompile_buffered_shadow_color_expand_vol_ex(fp, sizeof fp, 0x40u, 0, 1u,
175
+ + NULL, NULL, NULL, g_hlsl, sizeof g_hlsl, NULL);
176
+ + const u32 dim[16][3] = { { 8, 4, 2 } };
177
+ + check_count("3D UN TEX FP scale sites",
178
+ + rsx_fp_apply_unnorm_scale(g_hlsl, sizeof g_hlsl, 1u, dim, 0, 1u), 1);
179
+ + check("3D UN TEX FP HLSL", g_hlsl, ".xyz * float3(0.125, 0.25, 0.5))");
180
+ + if (translate("3D UN TEX FP", RSX_SHADER_STAGE_FRAGMENT) == 0)
181
+ + check("3D UN TEX FP MSL", g_msl, "texture3d");
182
+ + }
183
+ +
184
+ /* ---- fragment program: TEX r0, TC0 with EXP_TEX on a biased unit -----
185
+ * The _bx2 fetch: the lanes the unit's biased remap names come back as
186
+ * x*2-1. The helper must survive glslang/spirv-cross intact. */
tasks/sp00nznet__ps3recomp-482/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/sp00nznet__ps3recomp-482/task.toml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/sp00nznet__ps3recomp-482"
5
+ description = "rsx_fp_decompiler: divide texel coordinates of a 3D texture by its depth"
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "ps3recomp",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "sp00nznet/ps3recomp"
19
+ ref = "a6d76c895f77eb30b90a806c830544e61821b77f"
20
+ reference = "https://github.com/sp00nznet/ps3recomp/pull/482"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:59.867927+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:1de209523f7c5ddf164253e0a9c67f985fddd6a058e41b81c5acee68b0aa4559"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-26T15:32:55Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "libs/video/rsx_draw_engine.c",
34
+ "libs/video/rsx_fp_decompiler.c",
35
+ "libs/video/rsx_fp_decompiler.h",
36
+ "libs/video/rsx_live_draw.c",
37
+ "libs/video/tests/test_shader_msl.c",
38
+ ]
39
+ bootstrap_image = "python:3.12-slim"
40
+
41
+ [metadata.repo2env.reward_calibration]
42
+ baseline_reward = 0.0
43
+ loc_changed = 62
44
+ difficulty = "medium"
45
+
46
+ [metadata.repo2env.evaluation]
47
+ schema_version = "1"
48
+ status = "unverified"
49
+ stage = "generation"
50
+ reason_codes = [
51
+ "validation_not_run",
52
+ ]
53
+ detail = "Generated task; validation has not been established."
54
+ provenance = "unknown"
55
+ evidence = []
56
+
57
+ [metadata.repo2env.reproducibility]
58
+ mode = "inline_dockerfile"
59
+ image_ref = "python:3.12-slim"
60
+ image_tag = "python:3.12-slim"
61
+ image_visibility = "public"
62
+ pushed_at = "2026-11-16T16:20:03.115301+00:00"
63
+ pushed_by = "scalingX"
64
+ inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1"
65
+ inline_recipe_lines = 37
66
+ inline_recipe_source = "user_dockerfile"
67
+
68
+ [agent]
69
+ timeout_sec = 1800.0
70
+
71
+ [verifier]
72
+ timeout_sec = 300.0
tasks/sp00nznet__ps3recomp-482/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/sp00nznet__ps3recomp-482/tests/instruction.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** rsx_fp_decompiler: divide texel coordinates of a 3D texture by its depth
4
+
5
+ ## Description
6
+
7
+ `rsx_fp_apply_unnorm_scale` appends ` * float2(1/w, 1/h)` to every Sample on an unnormalised (texel-addressed) unit. A volume unit is declared `Texture3D` and sampled with a float3, so a program that reads a 3D texture with texel coordinates fails with `'__BI_Sample' : no matching overloaded function found`. The engine then drops the pipeline and those draws are silently skipped.
8
+
9
+ I hit this with an SSAO pass that samples a 32x32x32 volume in texel coordinates. With the pass gone, the AO filter after it read whatever was left at that address (a shadow map's bytes) as its input, and the whole scene came out almost black.
10
+
11
+ The fix gives `rsx_fp_apply_unnorm_scale` a volume mask and a depth per unit. A volume unit gets `float3(1/w, 1/h, 1/depth)`, which matches how RPCS3's texture cache scales r by 1/depth for 3D textures. The draw engine passes its volume mask and the texture depth. `rsx_live_draw` has no 3D textures, so it passes an empty mask and its output doesn't change. 2D and cube units produce the same HLSL as before.
12
+
13
+ Tests:
14
+ - `test_shader_msl`: new case, a TEX on an unnormalised 3D unit gets the float3 scale and translates to MSL with a `texture3d`. 121/121 pass.
15
+ - `test_fp_decompiler` (74/74), `test_rsx_draw_engine`, `test_color_feedback_engine` (45/45) and `test_shadow_engine` pass, and CTest is 15/15 on macOS arm64.
16
+ - In the game where I found it, on Metal, the SSAO pass runs again and the scene is lit: mean frame brightness goes from 7/255 to 19, close to the console.
17
+
18
+ No game data or program bytes are included.
19
+
20
+ ## Task
21
+
22
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-482/tests/oracle.patch ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c
2
+ index f99986b3..995c2cc2 100644
3
+ --- a/libs/video/rsx_draw_engine.c
4
+ +++ b/libs/video/rsx_draw_engine.c
5
+ @@ -1369,18 +1369,19 @@ static u32 eng_vtex_mask(void)
6
+ * dim. No host sampling mode is unnormalised for these, so the fragment
7
+ * program divides the coordinates instead, and the divisor makes the sizes
8
+ * pipeline identity (rsx_live_draw.c keys them the same way). */
9
+ -static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][2])
10
+ +static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][3])
11
+ {
12
+ u32 mask = 0;
13
+ for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++) {
14
+ rsx_dsp_texture t;
15
+ rsx_dsp_get_texture(&g.rsx, u, &t);
16
+ - dim[u][0] = dim[u][1] = 0;
17
+ + dim[u][0] = dim[u][1] = dim[u][2] = 0;
18
+ if (!t.enabled || !(t.format & RSX_TEX_FMT_UNNORM) || !t.width || !t.height)
19
+ continue;
20
+ mask |= 1u << u;
21
+ dim[u][0] = t.width;
22
+ dim[u][1] = t.height;
23
+ + dim[u][2] = t.depth;
24
+ }
25
+ return mask;
26
+ }
27
+ @@ -1662,14 +1663,14 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
28
+ for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; ++u)
29
+ if (!(expand_units & (1u << u))) expand_masks[u] = 0;
30
+
31
+ - u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][2];
32
+ + u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][3];
33
+ /* Shadow helpers normalize against the bound resource themselves. Only
34
+ * sampled ordinary UN units need baked dimensions or cache identity. */
35
+ const u32 unnorm_mask = eng_unnorm_units(unnorm_dim) &
36
+ (fixed ? 0xFFFFu : sampled_units) & ~shadow_mask;
37
+ for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++)
38
+ if (!(unnorm_mask & (1u << u)))
39
+ - unnorm_dim[u][0] = unnorm_dim[u][1] = 0;
40
+ + unnorm_dim[u][0] = unnorm_dim[u][1] = unnorm_dim[u][2] = 0;
41
+
42
+ memset(&g.fp_constants, 0, sizeof g.fp_constants);
43
+ if (!fixed && rsx_fp_collect_constants(fp_uc, fp_size, &g.fp_constants) < 0)
44
+ @@ -1735,7 +1736,8 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
45
+ s_ps_hlsl, sizeof s_ps_hlsl, &nconst);
46
+ if (fi > 0 && nconst != g.fp_constants.count) fi = -1;
47
+ if (fi > 0 && rsx_fp_apply_unnorm_scale(s_ps_hlsl, sizeof s_ps_hlsl, unnorm_mask,
48
+ - (const u32 (*)[2])unnorm_dim, cube_mask) < 0)
49
+ + (const u32 (*)[3])unnorm_dim, cube_mask,
50
+ + vol_mask) < 0)
51
+ fi = -1;
52
+ if (fi > 0 && srgb_output &&
53
+ rsx_fp_apply_srgb_output(s_ps_hlsl, sizeof s_ps_hlsl) < 0)
54
+ diff --git a/libs/video/rsx_fp_decompiler.c b/libs/video/rsx_fp_decompiler.c
55
+ index 5ce72ef6..ebdd14c0 100644
56
+ --- a/libs/video/rsx_fp_decompiler.c
57
+ +++ b/libs/video/rsx_fp_decompiler.c
58
+ @@ -1655,10 +1655,12 @@ u32 rsx_fp_code_hash(const u8* ucode, u32 max_bytes)
59
+ * works this way, and leaves every non-UNNORM program byte-identical.
60
+ *
61
+ * Cube units are skipped: their coordinate is a float3 direction, and
62
+ - * RSX_TEX_FMT_UNNORM has no meaning for one.
63
+ + * RSX_TEX_FMT_UNNORM has no meaning for one. A volume unit (Texture3D) is
64
+ + * sampled with three coordinates, all in texels, so it is divided by its depth
65
+ + * too (RPCS3's texture cache scales a 3D texture's r by 1/depth the same way).
66
+ */
67
+ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
68
+ - const u32 dim[][2], u32 cube_mask)
69
+ + const u32 dim[][3], u32 cube_mask, u32 volume_mask)
70
+ {
71
+ if (!hlsl || !unnorm_mask) return 0;
72
+ int patched = 0;
73
+ @@ -1666,8 +1668,9 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
74
+ for (u32 u = 0; u < 16; u++) {
75
+ if (!((unnorm_mask >> u) & 1u)) continue;
76
+ if ((cube_mask >> u) & 1u) continue;
77
+ - const u32 w = dim[u][0], h = dim[u][1];
78
+ - if (!w || !h) continue;
79
+ + const u32 w = dim[u][0], h = dim[u][1], d = dim[u][2];
80
+ + const int volume = (volume_mask >> u) & 1u;
81
+ + if (!w || !h || (volume && !d)) continue;
82
+
83
+ /* Both spellings the emitter produces for a 2D unit. */
84
+ char needles[2][40];
85
+ @@ -1693,8 +1696,12 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
86
+ if (*p != ')') break;
87
+
88
+ char scale[80];
89
+ - snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)",
90
+ - 1.0 / (double)w, 1.0 / (double)h);
91
+ + if (volume)
92
+ + snprintf(scale, sizeof scale, " * float3(%.9g, %.9g, %.9g)",
93
+ + 1.0 / (double)w, 1.0 / (double)h, 1.0 / (double)d);
94
+ + else
95
+ + snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)",
96
+ + 1.0 / (double)w, 1.0 / (double)h);
97
+ const u32 slen = (u32)strlen(scale);
98
+ const u32 used = (u32)strlen(hlsl);
99
+ if (used + slen + 1 > hlsl_size) return -1;
100
+ diff --git a/libs/video/rsx_fp_decompiler.h b/libs/video/rsx_fp_decompiler.h
101
+ index 670e8863..b39968e7 100644
102
+ --- a/libs/video/rsx_fp_decompiler.h
103
+ +++ b/libs/video/rsx_fp_decompiler.h
104
+ @@ -86,11 +86,12 @@ int rsx_fp_apply_alpha_test(char* hlsl, u32 out_size, u32 func, float ref);
105
+ float rsx_fp_alpha_ref(u32 raw, u32 surface_color_format);
106
+
107
+ /* Scale texel-space (RSX_TEX_FMT_UNNORM) coordinates into HLSL's 0..1 range.
108
+ - * unnorm_mask selects the units; dim[u] gives that unit's {width, height};
109
+ - * cube units are skipped. Returns the number of Sample sites patched, or -1 if
110
+ + * unnorm_mask selects the units; dim[u] gives that unit's {width, height,
111
+ + * depth}; cube units are skipped and volume_mask units (Texture3D) are divided
112
+ + * by their depth as well. Returns the number of Sample sites patched, or -1 if
113
+ * the buffer would overflow. A no-op when unnorm_mask is 0. */
114
+ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask,
115
+ - const u32 dim[][2], u32 cube_mask);
116
+ + const u32 dim[][3], u32 cube_mask, u32 volume_mask);
117
+
118
+ /* Decode NV4097_SET_ALPHA_REF for the active surface color format. Ordinary
119
+ * integer render targets use the low 8 bits as UNORM8; W16Z16Y16X16 uses a
120
+ diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c
121
+ index 2e65b8ee..3b7f0151 100644
122
+ --- a/libs/video/rsx_live_draw.c
123
+ +++ b/libs/video/rsx_live_draw.c
124
+ @@ -4771,7 +4771,7 @@ static ID3D12PipelineState* get_pso(
125
+ * mode. The divisor is baked into the HLSL, so the sizes are part of the
126
+ * PSO identity and must be in the key. */
127
+ u32 unnorm_mask = 0;
128
+ - u32 unnorm_dim[16][2] = {{0}};
129
+ + u32 unnorm_dim[16][3] = {{0}};
130
+ for (u32 uu = 0; uu < 16; uu++) {
131
+ rsx_dsp_texture ut; rsx_dsp_get_texture(&g.rsx, uu, &ut);
132
+ if (!ut.enabled || !(ut.format & TEX_FMT_UNNORM)) continue;
133
+ @@ -4901,7 +4901,7 @@ static ID3D12PipelineState* get_pso(
134
+ fi = -1;
135
+ if (fi > 0) {
136
+ const int np = rsx_fp_apply_unnorm_scale(
137
+ - ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask);
138
+ + ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask, 0u);
139
+ { static int n = 0;
140
+ if (PS3_LOG_FIRST(n, 8))
141
+ fprintf(stderr, "[unnorm] mask=0x%X cube=0x%X dim0=%ux%u"
142
+ @@ -4921,7 +4921,7 @@ static ID3D12PipelineState* get_pso(
143
+ fi = -1;
144
+ if (fi > 0 && rsx_fp_apply_unnorm_scale(
145
+ ps_hlsl, sizeof(ps_hlsl), unnorm_mask,
146
+ - unnorm_dim, cube_mask) < 0)
147
+ + unnorm_dim, cube_mask, 0u) < 0)
148
+ fi = -1;
149
+ }
150
+ #if defined(YZ_PERF_PROFILE)
151
+ diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c
152
+ index de2a6dc6..017e9ddd 100644
153
+ --- a/libs/video/tests/test_shader_msl.c
154
+ +++ b/libs/video/tests/test_shader_msl.c
155
+ @@ -19,6 +19,7 @@
156
+ * what a character material does
157
+ * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0
158
+ * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map
159
+ + * FP TEX r0, TC0 unit 0, 3D UN (END) ... a volume addressed in texels
160
+ * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16
161
+ * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs
162
+ *
163
+ @@ -364,6 +365,23 @@ int main(int argc, char** argv)
164
+ check("3D TEX FP MSL", g_msl, "texture3d");
165
+ }
166
+
167
+ + /* ---- the same, with unnormalised (texel) coordinates ------------------
168
+ + * All three coordinates are texels and are divided by width, height and
169
+ + * depth. A float2 scale on the float3 coordinate does not compile, and
170
+ + * the pipeline was dropped: Resistance 3's 32x32x32 volume lookups. */
171
+ + {
172
+ + u8 fp[16];
173
+ + rsx_test_fp_tex_r0_tc0(fp, 0);
174
+ + rsx_fp_decompile_buffered_shadow_color_expand_vol_ex(fp, sizeof fp, 0x40u, 0, 1u,
175
+ + NULL, NULL, NULL, g_hlsl, sizeof g_hlsl, NULL);
176
+ + const u32 dim[16][3] = { { 8, 4, 2 } };
177
+ + check_count("3D UN TEX FP scale sites",
178
+ + rsx_fp_apply_unnorm_scale(g_hlsl, sizeof g_hlsl, 1u, dim, 0, 1u), 1);
179
+ + check("3D UN TEX FP HLSL", g_hlsl, ".xyz * float3(0.125, 0.25, 0.5))");
180
+ + if (translate("3D UN TEX FP", RSX_SHADER_STAGE_FRAGMENT) == 0)
181
+ + check("3D UN TEX FP MSL", g_msl, "texture3d");
182
+ + }
183
+ +
184
+ /* ---- fragment program: TEX r0, TC0 with EXP_TEX on a biased unit -----
185
+ * The _bx2 fetch: the lanes the unit's biased remap names come back as
186
+ * x*2-1. The helper must survive glslang/spirv-cross intact. */
tasks/sp00nznet__ps3recomp-482/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/sp00nznet__ps3recomp-482/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/sp00nznet__ps3recomp-484/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/sp00nznet__ps3recomp-484/instruction.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** spu: copy only the reserved lines of a PUT under the lock-line lock
4
+
5
+ ## Description
6
+
7
+ A plain DMA PUT whose span touches a reserved 128-byte line ran the whole copy, and the notifies, inside the global lock-line lock. That keeps every other SPU's GETLLAR/PUTLLC (and every coherent PPU store) waiting behind a multi-line `memcpy`, though only the reserved lines can be inside a peer's compare-and-commit window.
8
+
9
+ This PR, for a span of two or more lines that touches a reserved line:
10
+
11
+ - **Copies the unreserved lines first, without the lock**, exactly as the existing unreserved path copies a whole span, and records which lines it skipped (a 16 KiB transfer spans at most 129 lines; a longer span keeps the old path).
12
+ - **Then, under the lock, copies the skipped lines and notifies every reserved one**: the skipped lines, and any line that became reserved after its unlocked copy. The bitmap is never cleared, so a line reserved at the first scan is still reserved in the locked pass.
13
+ - **Does not copy a late-reserved line a second time.** Between the passes a peer can reserve that line, read our bytes and commit with PUTLLC. A second copy would write that commit back over with older data. The peer is notified and loses its reservation, as on the unreserved path.
14
+
15
+ A single-line span keeps the single locked copy.
16
+
17
+ ### Ordering
18
+
19
+ - Each reserved line still gets its copy and notify in one critical section, which is the guarantee the PPU store path and the PUTLLC commit rely on.
20
+ - An unreserved line is treated as the unreserved path treats it. A peer that reserves it during the copy may take a torn snapshot, and the locked pass then raises `SPU_EVENT_LR` for it.
21
+ - A PUT was never atomic across lines, so other SPUs and the PPU can now see the unreserved part of the span before the reserved part lands. That is the same visibility a span with no reserved line already has.
22
+
23
+ ### Test
24
+
25
+ `test_spu_lockline_peer` gets an unaligned PUT (`+0x40`, `0x100` bytes) over three lines with the middle one reserved by a peer. It checks that `SPU_EVENT_LR` is raised exactly once, that the span lands, partial first and last lines included, and that the bytes on either side of the span don't move. If the partial-line offsets are broken, the test fails. The existing four-line `test_wide_put_finds_the_reserved_line` runs the new path too. The between-passes race isn't driven deterministically by the fixture.
26
+
27
+ ### Measurements
28
+
29
+ Retail title, mission scene. macOS, M4 Pro, downstream integration build. **No measured gain**: the frame median was unchanged within run-to-run spread (about ±4 ms around 50–51 ms), measured together with two other coherence changes. The change is offered because it shortens lock-line hold time for wide PUTs, and I don't make a performance claim for it.
30
+
31
+ ### Validation (macOS ARM64, base `a6d76c895f77eb30b90a806c830544e61821b77f`)
32
+
33
+ - Release SDK build with `PS3RECOMP_BUILD_TESTS=ON`: CTest 15/15 on both base and branch; `tools/test_*.py` 75/75 on both. Same warning count as base.
34
+ - CI-style builds: `test_spu_lockline_peer` 51/51 on base and 56/56 on the branch (the five new checks); `test_spu_coherency` 195/195 on both.
35
+ - Merges cleanly with the open PRs that touch `spu_dma.h` or `test_spu_lockline_peer.c` (#418, #441, #448, #453, #454). None of them changes the PUT copy block.
36
+
37
+ The patch contains no original program bytes or application-specific data.
38
+
39
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
40
+
41
+ ## Task
42
+
43
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-484/solution/patch.diff ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/runtime/spu/spu_dma.h b/runtime/spu/spu_dma.h
2
+ index 7b0debec..ba238440 100644
3
+ --- a/runtime/spu/spu_dma.h
4
+ +++ b/runtime/spu/spu_dma.h
5
+ @@ -652,10 +652,18 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea,
6
+ * snapshot against a line this copy has already replaced and commits
7
+ * over it, and a peer parked on RdEventStat sleeps through the write.
8
+ *
9
+ - * So when the span touches a reserved line the copy and the notify run
10
+ - * as ONE critical section under the lock-line lock -- the same contract
11
+ - * the PPU store path and the PUTLLC commit keep, and the only way the
12
+ - * copy cannot land inside a peer's compare-and-commit window. Spans
13
+ + * So a reserved line's copy and its notify run as ONE critical section
14
+ + * under the lock-line lock -- the same contract the PPU store path and
15
+ + * the PUTLLC commit keep, and the only way the copy cannot land inside
16
+ + * a peer's compare-and-commit window. Only the reserved lines need it:
17
+ + * in a multi-line span the others are copied first, without the lock,
18
+ + * exactly as an unreserved span is, and the locked pass then copies the
19
+ + * lines it skipped and notifies every reserved one. A line reserved
20
+ + * after its unlocked copy is notified there but NOT copied again: a
21
+ + * peer may already have reserved and committed it on top of our bytes,
22
+ + * and a second copy would write that commit back over. A wide PUT that
23
+ + * touches one queue line no longer holds every other SPU's atomics off
24
+ + * for the whole copy. Spans
25
+ * that touch no reserved line keep the lock-free copy: bulk asset PUTs
26
+ * are large and hot, and the scan is a bitmap bit per 128 bytes against
27
+ * a global that stays zero until an SPU reserves its first line.
28
+ @@ -679,7 +687,34 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea,
29
+ if (spu_coh_is_reserved(a)) { span_reserved = 1; break; }
30
+ if (a == a1) break;
31
+ }
32
+ - if (span_reserved) {
33
+ + /* Lines the unlocked pass left for the locked one: a 16 KiB
34
+ + * transfer spans at most 129 lines. */
35
+ + uint64_t locked_lines[3] = {0, 0, 0};
36
+ + if (span_reserved && a0 != a1 && ((a1 - a0) >> 7) < 64u * 3u) {
37
+ + const uint32_t ea32 = (uint32_t)ea;
38
+ + uint32_t i = 0;
39
+ + for (uint32_t a = a0; ; a += 128u, i++) {
40
+ + const uint32_t lo = a > ea32 ? a - ea32 : 0u;
41
+ + const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size;
42
+ + if (spu_coh_is_reserved(a)) locked_lines[i >> 6] |= 1ull << (i & 63u);
43
+ + else memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo);
44
+ + if (a == a1) break;
45
+ + }
46
+ + spu_lockline_lock();
47
+ + i = 0;
48
+ + for (uint32_t a = a0; ; a += 128u, i++) {
49
+ + const uint32_t lo = a > ea32 ? a - ea32 : 0u;
50
+ + const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size;
51
+ + if ((locked_lines[i >> 6] >> (i & 63u)) & 1u) {
52
+ + memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo);
53
+ + spu_coh_notify_write_except(a, spu);
54
+ + } else if (spu_coh_is_reserved(a)) {
55
+ + spu_coh_notify_write_except(a, spu); /* reserved after its copy */
56
+ + }
57
+ + if (a == a1) break;
58
+ + }
59
+ + spu_lockline_unlock();
60
+ + } else if (span_reserved) {
61
+ spu_lockline_lock();
62
+ memcpy(ea_ptr, ls_ptr, size);
63
+ for (uint32_t a = a0; ; a += 128u) {
64
+ diff --git a/runtime/spu/tests/test_spu_lockline_peer.c b/runtime/spu/tests/test_spu_lockline_peer.c
65
+ index 4bf08693..f945ab0b 100644
66
+ --- a/runtime/spu/tests/test_spu_lockline_peer.c
67
+ +++ b/runtime/spu/tests/test_spu_lockline_peer.c
68
+ @@ -347,6 +347,34 @@ static void test_wide_put_finds_the_reserved_line(void)
69
+ CHECK(mem_is(LINE_D, 0xB0, 0x200));
70
+ }
71
+
72
+ +/* The reserved line is copied under the lock and the rest of the span outside
73
+ + * it, so the partial first and last lines are their own pieces: each has to
74
+ + * land exactly, and nothing either side of the span may move. */
75
+ +static void test_unaligned_wide_put_around_a_reserved_line(void)
76
+ +{
77
+ + reset_pair();
78
+ + memset(g_guest_mem + LINE_D, 0xEE, 0x200);
79
+ + unsigned long raised = g_spu_lr_raise;
80
+ +
81
+ + spu_atomic(&g_a, LSA_A, LINE_D + 0x80, MFC_GETLLAR_CMD); /* the middle line */
82
+ +
83
+ + TEST("an unaligned PUT over a reserved line raises once");
84
+ + stage(&g_b, LSA_B, 0xC0, 0x100);
85
+ + spu_put(&g_b, LSA_B, LINE_D + 0x40, 0x100);
86
+ + CHECK_EQ_U32(g_a.event_status & SPU_EVENT_LR, SPU_EVENT_LR);
87
+ + CHECK(g_a.resv_valid == 0);
88
+ + CHECK(g_spu_lr_raise == raised + 1);
89
+ +
90
+ + TEST("...the span landed, partial lines included");
91
+ + CHECK(mem_is(LINE_D + 0x40, 0xC0, 0x100));
92
+ +
93
+ + TEST("...and the bytes either side of it did not move");
94
+ + int untouched = 1;
95
+ + for (uint32_t i = 0; i < 0x40; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE;
96
+ + for (uint32_t i = 0x140; i < 0x200; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE;
97
+ + CHECK(untouched);
98
+ +}
99
+ +
100
+ /* ===========================================================================
101
+ * The event acknowledge against a concurrent raise
102
+ *
103
+ @@ -426,6 +454,7 @@ int main(void)
104
+ test_plain_put_breaks_peer();
105
+ test_plain_put_elsewhere_is_quiet();
106
+ test_wide_put_finds_the_reserved_line();
107
+ + test_unaligned_wide_put_around_a_reserved_line();
108
+ test_ack_keeps_a_concurrent_raise();
109
+
110
+ printf("\nSPU-to-SPU lock-line coherence tests: %d passed, %d failed\n",
tasks/sp00nznet__ps3recomp-484/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/sp00nznet__ps3recomp-484/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/sp00nznet__ps3recomp-484"
5
+ description = "spu: copy only the reserved lines of a PUT under the lock-line lock"
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "ps3recomp",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "sp00nznet/ps3recomp"
19
+ ref = "a6d76c895f77eb30b90a806c830544e61821b77f"
20
+ reference = "https://github.com/sp00nznet/ps3recomp/pull/484"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:59.866082+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:26a2d0ba86766d15592e7870890b4e7ea99502098f1a6141bfeea33830ecd057"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-26T15:32:55Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "runtime/spu/spu_dma.h",
34
+ "runtime/spu/tests/test_spu_lockline_peer.c",
35
+ ]
36
+ bootstrap_image = "python:3.12-slim"
37
+
38
+ [metadata.repo2env.reward_calibration]
39
+ baseline_reward = 0.0
40
+ loc_changed = 74
41
+ difficulty = "medium"
42
+
43
+ [metadata.repo2env.evaluation]
44
+ schema_version = "1"
45
+ status = "unverified"
46
+ stage = "generation"
47
+ reason_codes = [
48
+ "validation_not_run",
49
+ ]
50
+ detail = "Generated task; validation has not been established."
51
+ provenance = "unknown"
52
+ evidence = []
53
+
54
+ [metadata.repo2env.reproducibility]
55
+ mode = "inline_dockerfile"
56
+ image_ref = "python:3.12-slim"
57
+ image_tag = "python:3.12-slim"
58
+ image_visibility = "public"
59
+ pushed_at = "2026-11-16T16:20:03.115843+00:00"
60
+ pushed_by = "scalingX"
61
+ inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1"
62
+ inline_recipe_lines = 37
63
+ inline_recipe_source = "user_dockerfile"
64
+
65
+ [agent]
66
+ timeout_sec = 1800.0
67
+
68
+ [verifier]
69
+ timeout_sec = 300.0
tasks/sp00nznet__ps3recomp-484/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/sp00nznet__ps3recomp-484/tests/instruction.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** spu: copy only the reserved lines of a PUT under the lock-line lock
4
+
5
+ ## Description
6
+
7
+ A plain DMA PUT whose span touches a reserved 128-byte line ran the whole copy, and the notifies, inside the global lock-line lock. That keeps every other SPU's GETLLAR/PUTLLC (and every coherent PPU store) waiting behind a multi-line `memcpy`, though only the reserved lines can be inside a peer's compare-and-commit window.
8
+
9
+ This PR, for a span of two or more lines that touches a reserved line:
10
+
11
+ - **Copies the unreserved lines first, without the lock**, exactly as the existing unreserved path copies a whole span, and records which lines it skipped (a 16 KiB transfer spans at most 129 lines; a longer span keeps the old path).
12
+ - **Then, under the lock, copies the skipped lines and notifies every reserved one**: the skipped lines, and any line that became reserved after its unlocked copy. The bitmap is never cleared, so a line reserved at the first scan is still reserved in the locked pass.
13
+ - **Does not copy a late-reserved line a second time.** Between the passes a peer can reserve that line, read our bytes and commit with PUTLLC. A second copy would write that commit back over with older data. The peer is notified and loses its reservation, as on the unreserved path.
14
+
15
+ A single-line span keeps the single locked copy.
16
+
17
+ ### Ordering
18
+
19
+ - Each reserved line still gets its copy and notify in one critical section, which is the guarantee the PPU store path and the PUTLLC commit rely on.
20
+ - An unreserved line is treated as the unreserved path treats it. A peer that reserves it during the copy may take a torn snapshot, and the locked pass then raises `SPU_EVENT_LR` for it.
21
+ - A PUT was never atomic across lines, so other SPUs and the PPU can now see the unreserved part of the span before the reserved part lands. That is the same visibility a span with no reserved line already has.
22
+
23
+ ### Test
24
+
25
+ `test_spu_lockline_peer` gets an unaligned PUT (`+0x40`, `0x100` bytes) over three lines with the middle one reserved by a peer. It checks that `SPU_EVENT_LR` is raised exactly once, that the span lands, partial first and last lines included, and that the bytes on either side of the span don't move. If the partial-line offsets are broken, the test fails. The existing four-line `test_wide_put_finds_the_reserved_line` runs the new path too. The between-passes race isn't driven deterministically by the fixture.
26
+
27
+ ### Measurements
28
+
29
+ Retail title, mission scene. macOS, M4 Pro, downstream integration build. **No measured gain**: the frame median was unchanged within run-to-run spread (about ±4 ms around 50–51 ms), measured together with two other coherence changes. The change is offered because it shortens lock-line hold time for wide PUTs, and I don't make a performance claim for it.
30
+
31
+ ### Validation (macOS ARM64, base `a6d76c895f77eb30b90a806c830544e61821b77f`)
32
+
33
+ - Release SDK build with `PS3RECOMP_BUILD_TESTS=ON`: CTest 15/15 on both base and branch; `tools/test_*.py` 75/75 on both. Same warning count as base.
34
+ - CI-style builds: `test_spu_lockline_peer` 51/51 on base and 56/56 on the branch (the five new checks); `test_spu_coherency` 195/195 on both.
35
+ - Merges cleanly with the open PRs that touch `spu_dma.h` or `test_spu_lockline_peer.c` (#418, #441, #448, #453, #454). None of them changes the PUT copy block.
36
+
37
+ The patch contains no original program bytes or application-specific data.
38
+
39
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
40
+
41
+ ## Task
42
+
43
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-484/tests/oracle.patch ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/runtime/spu/spu_dma.h b/runtime/spu/spu_dma.h
2
+ index 7b0debec..ba238440 100644
3
+ --- a/runtime/spu/spu_dma.h
4
+ +++ b/runtime/spu/spu_dma.h
5
+ @@ -652,10 +652,18 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea,
6
+ * snapshot against a line this copy has already replaced and commits
7
+ * over it, and a peer parked on RdEventStat sleeps through the write.
8
+ *
9
+ - * So when the span touches a reserved line the copy and the notify run
10
+ - * as ONE critical section under the lock-line lock -- the same contract
11
+ - * the PPU store path and the PUTLLC commit keep, and the only way the
12
+ - * copy cannot land inside a peer's compare-and-commit window. Spans
13
+ + * So a reserved line's copy and its notify run as ONE critical section
14
+ + * under the lock-line lock -- the same contract the PPU store path and
15
+ + * the PUTLLC commit keep, and the only way the copy cannot land inside
16
+ + * a peer's compare-and-commit window. Only the reserved lines need it:
17
+ + * in a multi-line span the others are copied first, without the lock,
18
+ + * exactly as an unreserved span is, and the locked pass then copies the
19
+ + * lines it skipped and notifies every reserved one. A line reserved
20
+ + * after its unlocked copy is notified there but NOT copied again: a
21
+ + * peer may already have reserved and committed it on top of our bytes,
22
+ + * and a second copy would write that commit back over. A wide PUT that
23
+ + * touches one queue line no longer holds every other SPU's atomics off
24
+ + * for the whole copy. Spans
25
+ * that touch no reserved line keep the lock-free copy: bulk asset PUTs
26
+ * are large and hot, and the scan is a bitmap bit per 128 bytes against
27
+ * a global that stays zero until an SPU reserves its first line.
28
+ @@ -679,7 +687,34 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea,
29
+ if (spu_coh_is_reserved(a)) { span_reserved = 1; break; }
30
+ if (a == a1) break;
31
+ }
32
+ - if (span_reserved) {
33
+ + /* Lines the unlocked pass left for the locked one: a 16 KiB
34
+ + * transfer spans at most 129 lines. */
35
+ + uint64_t locked_lines[3] = {0, 0, 0};
36
+ + if (span_reserved && a0 != a1 && ((a1 - a0) >> 7) < 64u * 3u) {
37
+ + const uint32_t ea32 = (uint32_t)ea;
38
+ + uint32_t i = 0;
39
+ + for (uint32_t a = a0; ; a += 128u, i++) {
40
+ + const uint32_t lo = a > ea32 ? a - ea32 : 0u;
41
+ + const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size;
42
+ + if (spu_coh_is_reserved(a)) locked_lines[i >> 6] |= 1ull << (i & 63u);
43
+ + else memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo);
44
+ + if (a == a1) break;
45
+ + }
46
+ + spu_lockline_lock();
47
+ + i = 0;
48
+ + for (uint32_t a = a0; ; a += 128u, i++) {
49
+ + const uint32_t lo = a > ea32 ? a - ea32 : 0u;
50
+ + const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size;
51
+ + if ((locked_lines[i >> 6] >> (i & 63u)) & 1u) {
52
+ + memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo);
53
+ + spu_coh_notify_write_except(a, spu);
54
+ + } else if (spu_coh_is_reserved(a)) {
55
+ + spu_coh_notify_write_except(a, spu); /* reserved after its copy */
56
+ + }
57
+ + if (a == a1) break;
58
+ + }
59
+ + spu_lockline_unlock();
60
+ + } else if (span_reserved) {
61
+ spu_lockline_lock();
62
+ memcpy(ea_ptr, ls_ptr, size);
63
+ for (uint32_t a = a0; ; a += 128u) {
64
+ diff --git a/runtime/spu/tests/test_spu_lockline_peer.c b/runtime/spu/tests/test_spu_lockline_peer.c
65
+ index 4bf08693..f945ab0b 100644
66
+ --- a/runtime/spu/tests/test_spu_lockline_peer.c
67
+ +++ b/runtime/spu/tests/test_spu_lockline_peer.c
68
+ @@ -347,6 +347,34 @@ static void test_wide_put_finds_the_reserved_line(void)
69
+ CHECK(mem_is(LINE_D, 0xB0, 0x200));
70
+ }
71
+
72
+ +/* The reserved line is copied under the lock and the rest of the span outside
73
+ + * it, so the partial first and last lines are their own pieces: each has to
74
+ + * land exactly, and nothing either side of the span may move. */
75
+ +static void test_unaligned_wide_put_around_a_reserved_line(void)
76
+ +{
77
+ + reset_pair();
78
+ + memset(g_guest_mem + LINE_D, 0xEE, 0x200);
79
+ + unsigned long raised = g_spu_lr_raise;
80
+ +
81
+ + spu_atomic(&g_a, LSA_A, LINE_D + 0x80, MFC_GETLLAR_CMD); /* the middle line */
82
+ +
83
+ + TEST("an unaligned PUT over a reserved line raises once");
84
+ + stage(&g_b, LSA_B, 0xC0, 0x100);
85
+ + spu_put(&g_b, LSA_B, LINE_D + 0x40, 0x100);
86
+ + CHECK_EQ_U32(g_a.event_status & SPU_EVENT_LR, SPU_EVENT_LR);
87
+ + CHECK(g_a.resv_valid == 0);
88
+ + CHECK(g_spu_lr_raise == raised + 1);
89
+ +
90
+ + TEST("...the span landed, partial lines included");
91
+ + CHECK(mem_is(LINE_D + 0x40, 0xC0, 0x100));
92
+ +
93
+ + TEST("...and the bytes either side of it did not move");
94
+ + int untouched = 1;
95
+ + for (uint32_t i = 0; i < 0x40; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE;
96
+ + for (uint32_t i = 0x140; i < 0x200; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE;
97
+ + CHECK(untouched);
98
+ +}
99
+ +
100
+ /* ===========================================================================
101
+ * The event acknowledge against a concurrent raise
102
+ *
103
+ @@ -426,6 +454,7 @@ int main(void)
104
+ test_plain_put_breaks_peer();
105
+ test_plain_put_elsewhere_is_quiet();
106
+ test_wide_put_finds_the_reserved_line();
107
+ + test_unaligned_wide_put_around_a_reserved_line();
108
+ test_ack_keeps_a_concurrent_raise();
109
+
110
+ printf("\nSPU-to-SPU lock-line coherence tests: %d passed, %d failed\n",
tasks/sp00nznet__ps3recomp-484/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/sp00nznet__ps3recomp-484/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/sp00nznet__ps3recomp-485/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/sp00nznet__ps3recomp-485/instruction.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** rsx_vp_decompiler: branch on the transform branch bits; leaders up to slot 544
4
+
5
+ ## Description
6
+
7
+ I ran into this with a 543-slot vertex program, an uber shader for glows and light shafts. It picks its optional paths with about twenty `BRB !bN` branches on SET_TRANSFORM_BRANCH_BITS, and the bits change from draw to draw. Two things kept it off screen.
8
+
9
+ First, the decompiler's block-leader table stopped at slot 512, but transform program memory has 544 slots (`RSX_DSP_VP_INSTR`). A branching program is emitted as one `if (_pc == N)` block per leader. Past slot 511 no block was opened, so every later branch closed a block that was never opened, `main()` ended early, and glslang rejected it with "function does not return a value". The engine dropped every draw that used it. Raising the limit to 544 fixes that.
10
+
11
+ Second, BRB and CLB were "not modelled" and just fell through. With only the first fix, the program compiled but ran every optional path, and the effects came out as red stretched polygons. They now test bit D3[23:27] of the branch bits against D3[28], the same way RPCS3's `GetOptionalBranchCond` does; the CC condition doesn't apply to them. CLB pushes the return slot like CAL.
12
+
13
+ The bits are baked into the generated HLSL as a constant, much like the unnorm texture sizes, so the compiler can drop the dead paths. That makes them pipeline identity, but only for programs that actually contain BRB or CLB (`rsx_vp_uses_branch_bits`). Every other program keeps the same key and the same HLSL as before. The draw engine and `rsx_live_draw` both read register 0x1FF8, pass it with `rsx_vp_set_branch_bits`, and key on it. I've only run the draw engine path; the live_draw change is the same few lines but untested, since I don't have a D3D12 setup.
14
+
15
+ One thing I noticed but didn't change: the draw engine never calls `rsx_vp_set_branch_base`, and its key doesn't include the VP start slot. A branching program loaded somewhere other than slot 0 would get the wrong targets there. The programs I hit all start at slot 0, so I left it for a separate change.
16
+
17
+ Tests:
18
+ - `test_shader_msl`: a 519-slot program with BRIs past slot 512 gets its blocks, and a small BRB/CLB program takes or skips its targets for two sets of bits and translates to MSL. With the decompiler change reverted, 5 of these checks fail. 133/133 pass.
19
+ - `test_rsx_draw_engine`, `test_fp_decompiler` (74/74), `test_color_feedback_engine` (45/45), `test_shadow_engine`, `tools/test_live_draw_sampler_key.py` and `tools/test_rsx_immediate_vertices.py` pass, and CTest is 15/15 on macOS arm64.
20
+ - In-game on Metal: no more dropped pipelines, and the glows and light shafts show up as on the console.
21
+
22
+ No game data or program bytes are included.
23
+
24
+ ## Task
25
+
26
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-485/solution/patch.diff ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c
2
+ index f99986b3..4a02779b 100644
3
+ --- a/libs/video/rsx_draw_engine.c
4
+ +++ b/libs/video/rsx_draw_engine.c
5
+ @@ -1631,6 +1631,10 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
6
+ const u32 cube_mask = eng_cube_mask();
7
+ const u32 vol_mask = eng_volume_mask();
8
+ const u32 vtex_mask = eng_vtex_mask();
9
+ + /* BRB/CLB outcomes are baked into the program: the branch bits are
10
+ + * identity only for a program that tests them. */
11
+ + const int vp_branch_bits_used = !fixed && rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16u);
12
+ + const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0;
13
+ rsx_fp_shadow_desc shadow[RSX_DSP_NUM_TEXTURES] = {{0}};
14
+ u32 shadow_mask = 0;
15
+ const u32 sampled_units = fixed ? 0 : rsx_fp_texture_units(fp_uc, fp_size);
16
+ @@ -1686,6 +1690,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
17
+ key = eng_fnv1a(&fixed_tag, sizeof fixed_tag, key);
18
+ } else {
19
+ key = eng_fnv1a(vp_uc, vp_instrs * 16u, key);
20
+ + if (vp_branch_bits_used) key = eng_fnv1a(&vp_branch_bits, sizeof vp_branch_bits, key);
21
+ key = rsx_fp_structural_hash(fp_uc, fp_size, key);
22
+ if (!key) return 0;
23
+ const u32 fp_ctrl_key = fp_ctrl & 0x4Eu; /* colour width and fragment depth export */
24
+ @@ -1727,6 +1732,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
25
+ snprintf(s_vs_hlsl, sizeof s_vs_hlsl, "%s", kEngFixedVS);
26
+ snprintf(s_ps_hlsl, sizeof s_ps_hlsl, "%s", kEngFixedPS);
27
+ } else {
28
+ + rsx_vp_set_branch_bits(vp_branch_bits);
29
+ vi = rsx_vp_decompile_compact_ex(vp_uc, vp_instrs * 16u, vtex_mask,
30
+ layout->mask, s_vs_hlsl,
31
+ sizeof s_vs_hlsl);
32
+ diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c
33
+ index 2e65b8ee..54fdffd9 100644
34
+ --- a/libs/video/rsx_live_draw.c
35
+ +++ b/libs/video/rsx_live_draw.c
36
+ @@ -4766,6 +4766,11 @@ static ID3D12PipelineState* get_pso(
37
+ key = fnv1a(&fp_ctrl_key, sizeof(fp_ctrl_key), key);
38
+ key = fnv1a(&cube_mask, sizeof(cube_mask), key);
39
+ key = fnv1a(&vtex_mask, sizeof(vtex_mask), key);
40
+ + /* BRB/CLB outcomes are baked into the program (rsx_vp_set_branch_bits). */
41
+ + const int vp_branch_bits_used = rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16);
42
+ + const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0;
43
+ + if (vp_branch_bits_used)
44
+ + key = fnv1a(&vp_branch_bits, sizeof(vp_branch_bits), key);
45
+ /* Texel-addressed (RSX_TEX_FMT_UNNORM) units need their coordinates divided
46
+ * by the texture size in the shader -- D3D12 has no unnormalised addressing
47
+ * mode. The divisor is baked into the HLSL, so the sizes are part of the
48
+ @@ -4880,6 +4885,7 @@ static ID3D12PipelineState* get_pso(
49
+ const LONGLONG decompile_begin = ld_profile_qpc();
50
+ #endif
51
+ rsx_vp_set_branch_base(rsx_dsp_vp_start(&g.rsx));
52
+ + rsx_vp_set_branch_bits(vp_branch_bits);
53
+ const int vi = masked_layout
54
+ ? rsx_vp_decompile_compact_ex(
55
+ vp_uc, vp_instrs * 16, vtex_mask, masked_layout->mask,
56
+ diff --git a/libs/video/rsx_vp_decompiler.c b/libs/video/rsx_vp_decompiler.c
57
+ index b9ed32be..4547280b 100644
58
+ --- a/libs/video/rsx_vp_decompiler.c
59
+ +++ b/libs/video/rsx_vp_decompiler.c
60
+ @@ -132,11 +132,27 @@ static void emit_store(Out* b, const char* dst_fmt, u32 idx, const char* m)
61
+ }
62
+
63
+ /* ---- flow control -------------------------------------------------------- */
64
+ -#define RSX_VP_MAX_INSTR 512
65
+ +/* The transform program memory holds 544 slots (RSX_DSP_VP_INSTR), not 512:
66
+ + * a branch target or block leader past slot 511 must still open a block. */
67
+ +#define RSX_VP_MAX_INSTR 544
68
+
69
+ static u32 s_vp_branch_base = 0; /* VP slot the program being decompiled starts at */
70
+ void rsx_vp_set_branch_base(u32 start_slot) { s_vp_branch_base = start_slot; }
71
+
72
+ +static u32 s_vp_branch_bits = 0; /* SET_TRANSFORM_BRANCH_BITS, tested by BRB/CLB */
73
+ +void rsx_vp_set_branch_bits(u32 bits) { s_vp_branch_bits = bits; }
74
+ +
75
+ +int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes)
76
+ +{
77
+ + if (!ucode) return 0;
78
+ + for (u32 off = 0; off + 16 <= max_bytes; off += 16) {
79
+ + const u32 sca_op = (rd_le(ucode + off + 4) >> 27) & 0x1Fu;
80
+ + if (sca_op == 0x11 || sca_op == 0x12) return 1; /* BRB, CLB */
81
+ + if (rd_le(ucode + off + 12) & 1u) break; /* D3.end */
82
+ + }
83
+ + return 0;
84
+ +}
85
+ +
86
+ /* BRA BRI CAL CLI RET BRB CLB (scalar opcodes). */
87
+ static int vp_is_flow(u32 sca_op)
88
+ {
89
+ @@ -500,10 +516,20 @@ static int rsx_vp_decompile_impl(
90
+ snprintf(flow_term, sizeof flow_term,
91
+ " if (%s) { if (_csp > 0) { _csp--; _pc = _cs[_csp]; } else _pc = -1; } else _pc = %d;\n",
92
+ c, next);
93
+ - else { /* BRB/CLB: boolean-register branches */
94
+ - n_flow_skipped++;
95
+ - snprintf(flow_term, sizeof flow_term,
96
+ - " _pc = %d; /* TODO: %s not modelled */\n", next, rsx_vp_sca_name(sca_op));
97
+ + else { /* BRB, CLB */
98
+ + /* A boolean branch tests bit D3[23:27] of the transform
99
+ + * branch bits against D3[28] and ignores the CC condition
100
+ + * (RPCS3's GetOptionalBranchCond). The bits are baked in:
101
+ + * the caller keys the program on them. */
102
+ + const u32 bit = (s_vp_branch_bits >> ((d3 >> 23) & 0x1Fu)) & 1u;
103
+ + const int taken = bit == ((d3 >> 28) & 1u);
104
+ + if (!taken)
105
+ + snprintf(flow_term, sizeof flow_term, " _pc = %d;\n", next);
106
+ + else if (sca_op == 0x11)
107
+ + snprintf(flow_term, sizeof flow_term, " _pc = %u;\n", tgt);
108
+ + else
109
+ + snprintf(flow_term, sizeof flow_term,
110
+ + " _cs[_csp] = %d; _csp = min(_csp + 1, 7); _pc = %u;\n", next, tgt);
111
+ }
112
+ }
113
+ /* ---- scalar ALU (reads SRC2) ---- */
114
+ diff --git a/libs/video/rsx_vp_decompiler.h b/libs/video/rsx_vp_decompiler.h
115
+ index ecc53fce..9310c482 100644
116
+ --- a/libs/video/rsx_vp_decompiler.h
117
+ +++ b/libs/video/rsx_vp_decompiler.h
118
+ @@ -57,6 +57,12 @@ int rsx_vp_decompile(const u8* ucode, u32 max_bytes, char* out, u32 out_size);
119
+ * to the ucode pointer handed in. Defaults to 0. */
120
+ void rsx_vp_set_branch_base(u32 start_slot);
121
+
122
+ +/* SET_TRANSFORM_BRANCH_BITS for the next program decompiled. BRB and CLB
123
+ + * branch on one of these bits; the decompiler bakes the outcome in, so a
124
+ + * program that rsx_vp_uses_branch_bits() must be keyed on them too. */
125
+ +void rsx_vp_set_branch_bits(u32 bits);
126
+ +int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes);
127
+ +
128
+ /* Bit N in vtex_mask declares NV40 2D vertex-texture unit N at t(16+N),
129
+ * sampler sN, and turns TXL for that unit into SampleLevel(..., LOD 0).
130
+ * Unmasked units retain the defined-zero fallback. */
131
+ diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c
132
+ index de2a6dc6..293386e2 100644
133
+ --- a/libs/video/tests/test_shader_msl.c
134
+ +++ b/libs/video/tests/test_shader_msl.c
135
+ @@ -20,6 +20,8 @@
136
+ * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0
137
+ * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map
138
+ * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16
139
+ + * VP 519 slots, BRI past slot 512 a long effects program's branches
140
+ + * VP BRB, CLB on transform branch bits its optional paths
141
+ * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs
142
+ *
143
+ * Each program's HLSL is checked for what was meant before the MSL is looked
144
+ @@ -70,8 +72,23 @@ static void check_count(const char* what, int got, int want)
145
+
146
+ /* ---- the translation step, shared by every case -------------------------- */
147
+
148
+ -static char g_hlsl[65536];
149
+ -static char g_msl[65536];
150
+ +static char g_hlsl[262144];
151
+ +static char g_msl[262144];
152
+ +static u8 g_long_vp[519 * 16]; /* the 519-slot program; also has no BRB/CLB */
153
+ +
154
+ +/* Flow instruction `sca_op` (0x09 BRI, 0x11 BRB, 0x12 CLB) to VP slot
155
+ + * `target`: cond [10:12] = 7 (TR), the target split over D0[23], D2[0:5] and
156
+ + * D3[29:31]; a boolean branch tests branch bit `bit` (D3[23:27]) for
157
+ + * `if_set` (D3[28]). No ALU writes. */
158
+ +static void vp_branch(u8* p, u32 sca_op, u32 target, u32 bit, u32 if_set)
159
+ +{
160
+ + const u32 d0 = (0x3Fu << 15) | (7u << 10) | (((target >> 9) & 1u) << 23);
161
+ + const u32 d1 = sca_op << 27;
162
+ + const u32 d2 = (target >> 3) & 0x3Fu;
163
+ + const u32 d3 = (0x3Fu << 7) | (bit << 23) | (if_set << 28) | ((target & 7u) << 29);
164
+ + rsx_test_put_le32(p + 0, d0); rsx_test_put_le32(p + 4, d1);
165
+ + rsx_test_put_le32(p + 8, d2); rsx_test_put_le32(p + 12, d3);
166
+ +}
167
+ static char g_log[4096];
168
+
169
+ static int translate(const char* what, int stage)
170
+ @@ -129,6 +146,86 @@ int main(int argc, char** argv)
171
+ }
172
+ }
173
+
174
+ + /* ---- vertex program: branches past slot 512 ------------------------------
175
+ + * The transform program memory has 544 slots. A branching program is
176
+ + * emitted as one "if (_pc == N)" block per leader; a leader past slot 511
177
+ + * opened no block, so every later branch closed a block that was never
178
+ + * opened and main() ended early. A 543-slot effects program failed that
179
+ + * way and every draw using it was dropped. */
180
+ + {
181
+ + u8* vp = g_long_vp;
182
+ + for (u32 i = 0; i < 513; i++)
183
+ + rsx_test_vp_mov_out(vp + i * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0); /* MOV o0, v0 */
184
+ + vp_branch(vp + 513 * 16, 0x09, 515, 0, 0);
185
+ + rsx_test_vp_mov_out(vp + 514 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* skipped */
186
+ + rsx_test_vp_mov_out(vp + 515 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* MOV o1, v1 */
187
+ + vp_branch(vp + 516 * 16, 0x09, 518, 0, 0);
188
+ + rsx_test_vp_mov_out(vp + 517 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 2, 0); /* skipped */
189
+ + rsx_test_vp_mov_out(vp + 518 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 1); /* MOV o2, v2, END */
190
+ + rsx_vp_set_branch_base(0);
191
+ + if (rsx_vp_decompile(vp, sizeof g_long_vp, g_hlsl, sizeof g_hlsl) > 0) {
192
+ + check("long VP HLSL", g_hlsl, "if (_pc == 514) {");
193
+ + check("long VP HLSL", g_hlsl, "if (_pc == 515) {");
194
+ + check("long VP HLSL", g_hlsl, "if (_pc == 518) {");
195
+ + if (translate("long VP", RSX_SHADER_STAGE_VERTEX) == 0)
196
+ + check("long VP MSL", g_msl, "vertex ");
197
+ + } else {
198
+ + printf("[FAIL] long VP -- decompile failed\n");
199
+ + g_fail++;
200
+ + }
201
+ + }
202
+ +
203
+ + /* ---- vertex program: boolean branches --------------------------------
204
+ + * BRB and CLB branch on one bit of SET_TRANSFORM_BRANCH_BITS, not on a
205
+ + * condition code. An uber effects program skips its optional paths with
206
+ + * "BRB !bN"; run straight through, every path was taken and the glows
207
+ + * came out as red stretched polygons.
208
+ + * 0 MOV o0, v0 1 BRB !b3 -> 3 2 MOV o1, v1
209
+ + * 3 CLB b12 -> 6 4 MOV o2, v2 5 BRI -> 8
210
+ + * 6 MOV o3, v3 7 RET 8 MOV o4, v4 (END) */
211
+ + {
212
+ + static u8 vp[9 * 16];
213
+ + rsx_test_vp_mov_out(vp + 0 * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0);
214
+ + vp_branch(vp + 1 * 16, 0x11, 3, 3, 0);
215
+ + rsx_test_vp_mov_out(vp + 2 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0);
216
+ + vp_branch(vp + 3 * 16, 0x12, 6, 12, 1);
217
+ + rsx_test_vp_mov_out(vp + 4 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 0);
218
+ + vp_branch(vp + 5 * 16, 0x09, 8, 0, 0);
219
+ + rsx_test_vp_mov_out(vp + 6 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 3, 0);
220
+ + vp_branch(vp + 7 * 16, 0x0C, 0, 0, 0);
221
+ + rsx_test_vp_mov_out(vp + 8 * 16, 4, RSX_TEST_VP_SWZ_IDENT, 4, 1);
222
+ + if (rsx_vp_uses_branch_bits(vp, sizeof vp) &&
223
+ + !rsx_vp_uses_branch_bits(g_long_vp, sizeof g_long_vp)) {
224
+ + printf("[PASS] bool VP -- keyed on the branch bits, the BRI-only program not\n");
225
+ + g_pass++;
226
+ + } else {
227
+ + printf("[FAIL] bool VP -- rsx_vp_uses_branch_bits\n");
228
+ + g_fail++;
229
+ + }
230
+ + static const struct { u32 bits; const char* brb; const char* clb; } cases[] = {
231
+ + { 0x0000u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 3;",
232
+ + "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n _pc = 4;" },
233
+ + { 0x1008u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 2;",
234
+ + "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n"
235
+ + " _cs[_csp] = 4; _csp = min(_csp + 1, 7); _pc = 6;" },
236
+ + };
237
+ + for (u32 i = 0; i < 2; i++) {
238
+ + rsx_vp_set_branch_base(0);
239
+ + rsx_vp_set_branch_bits(cases[i].bits);
240
+ + if (rsx_vp_decompile(vp, sizeof vp, g_hlsl, sizeof g_hlsl) > 0) {
241
+ + check("bool VP HLSL", g_hlsl, cases[i].brb);
242
+ + check("bool VP HLSL", g_hlsl, cases[i].clb);
243
+ + check_absent("bool VP HLSL", g_hlsl, "not modelled");
244
+ + if (translate("bool VP", RSX_SHADER_STAGE_VERTEX) == 0)
245
+ + check("bool VP MSL", g_msl, "vertex ");
246
+ + } else {
247
+ + printf("[FAIL] bool VP -- decompile failed\n");
248
+ + g_fail++;
249
+ + }
250
+ + }
251
+ + rsx_vp_set_branch_bits(0);
252
+ + }
253
+ +
254
+ /* ---- fragment program: MOV r0, COL0 ---------------------------------- */
255
+ {
256
+ u8 fp[16];
tasks/sp00nznet__ps3recomp-485/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/sp00nznet__ps3recomp-485/task.toml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/sp00nznet__ps3recomp-485"
5
+ description = "rsx_vp_decompiler: branch on the transform branch bits; leaders up to slot 544"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "ps3recomp",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "sp00nznet/ps3recomp"
19
+ ref = "a6d76c895f77eb30b90a806c830544e61821b77f"
20
+ reference = "https://github.com/sp00nznet/ps3recomp/pull/485"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:59.627812+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:202dda984e653bdaf8ad710f51d8cb81d3c3f7c73f1491357497ca21421bf38d"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-26T15:32:55Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "libs/video/rsx_draw_engine.c",
34
+ "libs/video/rsx_live_draw.c",
35
+ "libs/video/rsx_vp_decompiler.c",
36
+ "libs/video/rsx_vp_decompiler.h",
37
+ "libs/video/tests/test_shader_msl.c",
38
+ ]
39
+ bootstrap_image = "python:3.12-slim"
40
+
41
+ [metadata.repo2env.reward_calibration]
42
+ baseline_reward = 0.0
43
+ loc_changed = 155
44
+ difficulty = "large"
45
+
46
+ [metadata.repo2env.evaluation]
47
+ schema_version = "1"
48
+ status = "unverified"
49
+ stage = "generation"
50
+ reason_codes = [
51
+ "validation_not_run",
52
+ ]
53
+ detail = "Generated task; validation has not been established."
54
+ provenance = "unknown"
55
+ evidence = []
56
+
57
+ [metadata.repo2env.reproducibility]
58
+ mode = "inline_dockerfile"
59
+ image_ref = "python:3.12-slim"
60
+ image_tag = "python:3.12-slim"
61
+ image_visibility = "public"
62
+ pushed_at = "2026-11-16T16:20:03.116463+00:00"
63
+ pushed_by = "scalingX"
64
+ inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1"
65
+ inline_recipe_lines = 37
66
+ inline_recipe_source = "user_dockerfile"
67
+
68
+ [agent]
69
+ timeout_sec = 1800.0
70
+
71
+ [verifier]
72
+ timeout_sec = 300.0
tasks/sp00nznet__ps3recomp-485/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/sp00nznet__ps3recomp-485/tests/instruction.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** rsx_vp_decompiler: branch on the transform branch bits; leaders up to slot 544
4
+
5
+ ## Description
6
+
7
+ I ran into this with a 543-slot vertex program, an uber shader for glows and light shafts. It picks its optional paths with about twenty `BRB !bN` branches on SET_TRANSFORM_BRANCH_BITS, and the bits change from draw to draw. Two things kept it off screen.
8
+
9
+ First, the decompiler's block-leader table stopped at slot 512, but transform program memory has 544 slots (`RSX_DSP_VP_INSTR`). A branching program is emitted as one `if (_pc == N)` block per leader. Past slot 511 no block was opened, so every later branch closed a block that was never opened, `main()` ended early, and glslang rejected it with "function does not return a value". The engine dropped every draw that used it. Raising the limit to 544 fixes that.
10
+
11
+ Second, BRB and CLB were "not modelled" and just fell through. With only the first fix, the program compiled but ran every optional path, and the effects came out as red stretched polygons. They now test bit D3[23:27] of the branch bits against D3[28], the same way RPCS3's `GetOptionalBranchCond` does; the CC condition doesn't apply to them. CLB pushes the return slot like CAL.
12
+
13
+ The bits are baked into the generated HLSL as a constant, much like the unnorm texture sizes, so the compiler can drop the dead paths. That makes them pipeline identity, but only for programs that actually contain BRB or CLB (`rsx_vp_uses_branch_bits`). Every other program keeps the same key and the same HLSL as before. The draw engine and `rsx_live_draw` both read register 0x1FF8, pass it with `rsx_vp_set_branch_bits`, and key on it. I've only run the draw engine path; the live_draw change is the same few lines but untested, since I don't have a D3D12 setup.
14
+
15
+ One thing I noticed but didn't change: the draw engine never calls `rsx_vp_set_branch_base`, and its key doesn't include the VP start slot. A branching program loaded somewhere other than slot 0 would get the wrong targets there. The programs I hit all start at slot 0, so I left it for a separate change.
16
+
17
+ Tests:
18
+ - `test_shader_msl`: a 519-slot program with BRIs past slot 512 gets its blocks, and a small BRB/CLB program takes or skips its targets for two sets of bits and translates to MSL. With the decompiler change reverted, 5 of these checks fail. 133/133 pass.
19
+ - `test_rsx_draw_engine`, `test_fp_decompiler` (74/74), `test_color_feedback_engine` (45/45), `test_shadow_engine`, `tools/test_live_draw_sampler_key.py` and `tools/test_rsx_immediate_vertices.py` pass, and CTest is 15/15 on macOS arm64.
20
+ - In-game on Metal: no more dropped pipelines, and the glows and light shafts show up as on the console.
21
+
22
+ No game data or program bytes are included.
23
+
24
+ ## Task
25
+
26
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-485/tests/oracle.patch ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c
2
+ index f99986b3..4a02779b 100644
3
+ --- a/libs/video/rsx_draw_engine.c
4
+ +++ b/libs/video/rsx_draw_engine.c
5
+ @@ -1631,6 +1631,10 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
6
+ const u32 cube_mask = eng_cube_mask();
7
+ const u32 vol_mask = eng_volume_mask();
8
+ const u32 vtex_mask = eng_vtex_mask();
9
+ + /* BRB/CLB outcomes are baked into the program: the branch bits are
10
+ + * identity only for a program that tests them. */
11
+ + const int vp_branch_bits_used = !fixed && rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16u);
12
+ + const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0;
13
+ rsx_fp_shadow_desc shadow[RSX_DSP_NUM_TEXTURES] = {{0}};
14
+ u32 shadow_mask = 0;
15
+ const u32 sampled_units = fixed ? 0 : rsx_fp_texture_units(fp_uc, fp_size);
16
+ @@ -1686,6 +1690,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
17
+ key = eng_fnv1a(&fixed_tag, sizeof fixed_tag, key);
18
+ } else {
19
+ key = eng_fnv1a(vp_uc, vp_instrs * 16u, key);
20
+ + if (vp_branch_bits_used) key = eng_fnv1a(&vp_branch_bits, sizeof vp_branch_bits, key);
21
+ key = rsx_fp_structural_hash(fp_uc, fp_size, key);
22
+ if (!key) return 0;
23
+ const u32 fp_ctrl_key = fp_ctrl & 0x4Eu; /* colour width and fragment depth export */
24
+ @@ -1727,6 +1732,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout,
25
+ snprintf(s_vs_hlsl, sizeof s_vs_hlsl, "%s", kEngFixedVS);
26
+ snprintf(s_ps_hlsl, sizeof s_ps_hlsl, "%s", kEngFixedPS);
27
+ } else {
28
+ + rsx_vp_set_branch_bits(vp_branch_bits);
29
+ vi = rsx_vp_decompile_compact_ex(vp_uc, vp_instrs * 16u, vtex_mask,
30
+ layout->mask, s_vs_hlsl,
31
+ sizeof s_vs_hlsl);
32
+ diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c
33
+ index 2e65b8ee..54fdffd9 100644
34
+ --- a/libs/video/rsx_live_draw.c
35
+ +++ b/libs/video/rsx_live_draw.c
36
+ @@ -4766,6 +4766,11 @@ static ID3D12PipelineState* get_pso(
37
+ key = fnv1a(&fp_ctrl_key, sizeof(fp_ctrl_key), key);
38
+ key = fnv1a(&cube_mask, sizeof(cube_mask), key);
39
+ key = fnv1a(&vtex_mask, sizeof(vtex_mask), key);
40
+ + /* BRB/CLB outcomes are baked into the program (rsx_vp_set_branch_bits). */
41
+ + const int vp_branch_bits_used = rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16);
42
+ + const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0;
43
+ + if (vp_branch_bits_used)
44
+ + key = fnv1a(&vp_branch_bits, sizeof(vp_branch_bits), key);
45
+ /* Texel-addressed (RSX_TEX_FMT_UNNORM) units need their coordinates divided
46
+ * by the texture size in the shader -- D3D12 has no unnormalised addressing
47
+ * mode. The divisor is baked into the HLSL, so the sizes are part of the
48
+ @@ -4880,6 +4885,7 @@ static ID3D12PipelineState* get_pso(
49
+ const LONGLONG decompile_begin = ld_profile_qpc();
50
+ #endif
51
+ rsx_vp_set_branch_base(rsx_dsp_vp_start(&g.rsx));
52
+ + rsx_vp_set_branch_bits(vp_branch_bits);
53
+ const int vi = masked_layout
54
+ ? rsx_vp_decompile_compact_ex(
55
+ vp_uc, vp_instrs * 16, vtex_mask, masked_layout->mask,
56
+ diff --git a/libs/video/rsx_vp_decompiler.c b/libs/video/rsx_vp_decompiler.c
57
+ index b9ed32be..4547280b 100644
58
+ --- a/libs/video/rsx_vp_decompiler.c
59
+ +++ b/libs/video/rsx_vp_decompiler.c
60
+ @@ -132,11 +132,27 @@ static void emit_store(Out* b, const char* dst_fmt, u32 idx, const char* m)
61
+ }
62
+
63
+ /* ---- flow control -------------------------------------------------------- */
64
+ -#define RSX_VP_MAX_INSTR 512
65
+ +/* The transform program memory holds 544 slots (RSX_DSP_VP_INSTR), not 512:
66
+ + * a branch target or block leader past slot 511 must still open a block. */
67
+ +#define RSX_VP_MAX_INSTR 544
68
+
69
+ static u32 s_vp_branch_base = 0; /* VP slot the program being decompiled starts at */
70
+ void rsx_vp_set_branch_base(u32 start_slot) { s_vp_branch_base = start_slot; }
71
+
72
+ +static u32 s_vp_branch_bits = 0; /* SET_TRANSFORM_BRANCH_BITS, tested by BRB/CLB */
73
+ +void rsx_vp_set_branch_bits(u32 bits) { s_vp_branch_bits = bits; }
74
+ +
75
+ +int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes)
76
+ +{
77
+ + if (!ucode) return 0;
78
+ + for (u32 off = 0; off + 16 <= max_bytes; off += 16) {
79
+ + const u32 sca_op = (rd_le(ucode + off + 4) >> 27) & 0x1Fu;
80
+ + if (sca_op == 0x11 || sca_op == 0x12) return 1; /* BRB, CLB */
81
+ + if (rd_le(ucode + off + 12) & 1u) break; /* D3.end */
82
+ + }
83
+ + return 0;
84
+ +}
85
+ +
86
+ /* BRA BRI CAL CLI RET BRB CLB (scalar opcodes). */
87
+ static int vp_is_flow(u32 sca_op)
88
+ {
89
+ @@ -500,10 +516,20 @@ static int rsx_vp_decompile_impl(
90
+ snprintf(flow_term, sizeof flow_term,
91
+ " if (%s) { if (_csp > 0) { _csp--; _pc = _cs[_csp]; } else _pc = -1; } else _pc = %d;\n",
92
+ c, next);
93
+ - else { /* BRB/CLB: boolean-register branches */
94
+ - n_flow_skipped++;
95
+ - snprintf(flow_term, sizeof flow_term,
96
+ - " _pc = %d; /* TODO: %s not modelled */\n", next, rsx_vp_sca_name(sca_op));
97
+ + else { /* BRB, CLB */
98
+ + /* A boolean branch tests bit D3[23:27] of the transform
99
+ + * branch bits against D3[28] and ignores the CC condition
100
+ + * (RPCS3's GetOptionalBranchCond). The bits are baked in:
101
+ + * the caller keys the program on them. */
102
+ + const u32 bit = (s_vp_branch_bits >> ((d3 >> 23) & 0x1Fu)) & 1u;
103
+ + const int taken = bit == ((d3 >> 28) & 1u);
104
+ + if (!taken)
105
+ + snprintf(flow_term, sizeof flow_term, " _pc = %d;\n", next);
106
+ + else if (sca_op == 0x11)
107
+ + snprintf(flow_term, sizeof flow_term, " _pc = %u;\n", tgt);
108
+ + else
109
+ + snprintf(flow_term, sizeof flow_term,
110
+ + " _cs[_csp] = %d; _csp = min(_csp + 1, 7); _pc = %u;\n", next, tgt);
111
+ }
112
+ }
113
+ /* ---- scalar ALU (reads SRC2) ---- */
114
+ diff --git a/libs/video/rsx_vp_decompiler.h b/libs/video/rsx_vp_decompiler.h
115
+ index ecc53fce..9310c482 100644
116
+ --- a/libs/video/rsx_vp_decompiler.h
117
+ +++ b/libs/video/rsx_vp_decompiler.h
118
+ @@ -57,6 +57,12 @@ int rsx_vp_decompile(const u8* ucode, u32 max_bytes, char* out, u32 out_size);
119
+ * to the ucode pointer handed in. Defaults to 0. */
120
+ void rsx_vp_set_branch_base(u32 start_slot);
121
+
122
+ +/* SET_TRANSFORM_BRANCH_BITS for the next program decompiled. BRB and CLB
123
+ + * branch on one of these bits; the decompiler bakes the outcome in, so a
124
+ + * program that rsx_vp_uses_branch_bits() must be keyed on them too. */
125
+ +void rsx_vp_set_branch_bits(u32 bits);
126
+ +int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes);
127
+ +
128
+ /* Bit N in vtex_mask declares NV40 2D vertex-texture unit N at t(16+N),
129
+ * sampler sN, and turns TXL for that unit into SampleLevel(..., LOD 0).
130
+ * Unmasked units retain the defined-zero fallback. */
131
+ diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c
132
+ index de2a6dc6..293386e2 100644
133
+ --- a/libs/video/tests/test_shader_msl.c
134
+ +++ b/libs/video/tests/test_shader_msl.c
135
+ @@ -20,6 +20,8 @@
136
+ * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0
137
+ * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map
138
+ * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16
139
+ + * VP 519 slots, BRI past slot 512 a long effects program's branches
140
+ + * VP BRB, CLB on transform branch bits its optional paths
141
+ * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs
142
+ *
143
+ * Each program's HLSL is checked for what was meant before the MSL is looked
144
+ @@ -70,8 +72,23 @@ static void check_count(const char* what, int got, int want)
145
+
146
+ /* ---- the translation step, shared by every case -------------------------- */
147
+
148
+ -static char g_hlsl[65536];
149
+ -static char g_msl[65536];
150
+ +static char g_hlsl[262144];
151
+ +static char g_msl[262144];
152
+ +static u8 g_long_vp[519 * 16]; /* the 519-slot program; also has no BRB/CLB */
153
+ +
154
+ +/* Flow instruction `sca_op` (0x09 BRI, 0x11 BRB, 0x12 CLB) to VP slot
155
+ + * `target`: cond [10:12] = 7 (TR), the target split over D0[23], D2[0:5] and
156
+ + * D3[29:31]; a boolean branch tests branch bit `bit` (D3[23:27]) for
157
+ + * `if_set` (D3[28]). No ALU writes. */
158
+ +static void vp_branch(u8* p, u32 sca_op, u32 target, u32 bit, u32 if_set)
159
+ +{
160
+ + const u32 d0 = (0x3Fu << 15) | (7u << 10) | (((target >> 9) & 1u) << 23);
161
+ + const u32 d1 = sca_op << 27;
162
+ + const u32 d2 = (target >> 3) & 0x3Fu;
163
+ + const u32 d3 = (0x3Fu << 7) | (bit << 23) | (if_set << 28) | ((target & 7u) << 29);
164
+ + rsx_test_put_le32(p + 0, d0); rsx_test_put_le32(p + 4, d1);
165
+ + rsx_test_put_le32(p + 8, d2); rsx_test_put_le32(p + 12, d3);
166
+ +}
167
+ static char g_log[4096];
168
+
169
+ static int translate(const char* what, int stage)
170
+ @@ -129,6 +146,86 @@ int main(int argc, char** argv)
171
+ }
172
+ }
173
+
174
+ + /* ---- vertex program: branches past slot 512 ------------------------------
175
+ + * The transform program memory has 544 slots. A branching program is
176
+ + * emitted as one "if (_pc == N)" block per leader; a leader past slot 511
177
+ + * opened no block, so every later branch closed a block that was never
178
+ + * opened and main() ended early. A 543-slot effects program failed that
179
+ + * way and every draw using it was dropped. */
180
+ + {
181
+ + u8* vp = g_long_vp;
182
+ + for (u32 i = 0; i < 513; i++)
183
+ + rsx_test_vp_mov_out(vp + i * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0); /* MOV o0, v0 */
184
+ + vp_branch(vp + 513 * 16, 0x09, 515, 0, 0);
185
+ + rsx_test_vp_mov_out(vp + 514 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* skipped */
186
+ + rsx_test_vp_mov_out(vp + 515 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* MOV o1, v1 */
187
+ + vp_branch(vp + 516 * 16, 0x09, 518, 0, 0);
188
+ + rsx_test_vp_mov_out(vp + 517 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 2, 0); /* skipped */
189
+ + rsx_test_vp_mov_out(vp + 518 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 1); /* MOV o2, v2, END */
190
+ + rsx_vp_set_branch_base(0);
191
+ + if (rsx_vp_decompile(vp, sizeof g_long_vp, g_hlsl, sizeof g_hlsl) > 0) {
192
+ + check("long VP HLSL", g_hlsl, "if (_pc == 514) {");
193
+ + check("long VP HLSL", g_hlsl, "if (_pc == 515) {");
194
+ + check("long VP HLSL", g_hlsl, "if (_pc == 518) {");
195
+ + if (translate("long VP", RSX_SHADER_STAGE_VERTEX) == 0)
196
+ + check("long VP MSL", g_msl, "vertex ");
197
+ + } else {
198
+ + printf("[FAIL] long VP -- decompile failed\n");
199
+ + g_fail++;
200
+ + }
201
+ + }
202
+ +
203
+ + /* ---- vertex program: boolean branches --------------------------------
204
+ + * BRB and CLB branch on one bit of SET_TRANSFORM_BRANCH_BITS, not on a
205
+ + * condition code. An uber effects program skips its optional paths with
206
+ + * "BRB !bN"; run straight through, every path was taken and the glows
207
+ + * came out as red stretched polygons.
208
+ + * 0 MOV o0, v0 1 BRB !b3 -> 3 2 MOV o1, v1
209
+ + * 3 CLB b12 -> 6 4 MOV o2, v2 5 BRI -> 8
210
+ + * 6 MOV o3, v3 7 RET 8 MOV o4, v4 (END) */
211
+ + {
212
+ + static u8 vp[9 * 16];
213
+ + rsx_test_vp_mov_out(vp + 0 * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0);
214
+ + vp_branch(vp + 1 * 16, 0x11, 3, 3, 0);
215
+ + rsx_test_vp_mov_out(vp + 2 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0);
216
+ + vp_branch(vp + 3 * 16, 0x12, 6, 12, 1);
217
+ + rsx_test_vp_mov_out(vp + 4 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 0);
218
+ + vp_branch(vp + 5 * 16, 0x09, 8, 0, 0);
219
+ + rsx_test_vp_mov_out(vp + 6 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 3, 0);
220
+ + vp_branch(vp + 7 * 16, 0x0C, 0, 0, 0);
221
+ + rsx_test_vp_mov_out(vp + 8 * 16, 4, RSX_TEST_VP_SWZ_IDENT, 4, 1);
222
+ + if (rsx_vp_uses_branch_bits(vp, sizeof vp) &&
223
+ + !rsx_vp_uses_branch_bits(g_long_vp, sizeof g_long_vp)) {
224
+ + printf("[PASS] bool VP -- keyed on the branch bits, the BRI-only program not\n");
225
+ + g_pass++;
226
+ + } else {
227
+ + printf("[FAIL] bool VP -- rsx_vp_uses_branch_bits\n");
228
+ + g_fail++;
229
+ + }
230
+ + static const struct { u32 bits; const char* brb; const char* clb; } cases[] = {
231
+ + { 0x0000u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 3;",
232
+ + "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n _pc = 4;" },
233
+ + { 0x1008u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 2;",
234
+ + "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n"
235
+ + " _cs[_csp] = 4; _csp = min(_csp + 1, 7); _pc = 6;" },
236
+ + };
237
+ + for (u32 i = 0; i < 2; i++) {
238
+ + rsx_vp_set_branch_base(0);
239
+ + rsx_vp_set_branch_bits(cases[i].bits);
240
+ + if (rsx_vp_decompile(vp, sizeof vp, g_hlsl, sizeof g_hlsl) > 0) {
241
+ + check("bool VP HLSL", g_hlsl, cases[i].brb);
242
+ + check("bool VP HLSL", g_hlsl, cases[i].clb);
243
+ + check_absent("bool VP HLSL", g_hlsl, "not modelled");
244
+ + if (translate("bool VP", RSX_SHADER_STAGE_VERTEX) == 0)
245
+ + check("bool VP MSL", g_msl, "vertex ");
246
+ + } else {
247
+ + printf("[FAIL] bool VP -- decompile failed\n");
248
+ + g_fail++;
249
+ + }
250
+ + }
251
+ + rsx_vp_set_branch_bits(0);
252
+ + }
253
+ +
254
+ /* ---- fragment program: MOV r0, COL0 ---------------------------------- */
255
+ {
256
+ u8 fp[16];
tasks/sp00nznet__ps3recomp-485/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/sp00nznet__ps3recomp-485/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/sp00nznet__ps3recomp-490/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/sp00nznet__ps3recomp-490/instruction.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** sys_mutex: destroy refuses a mutex that is held or has waiters (EBUSY)
4
+
5
+ ## Description
6
+
7
+ ## Why
8
+
9
+ This fix comes from the Resistance: Fall of Man (BCUS98107) native port. I found it while chasing the hang after Resistance's level-1 intro movie. To be clear, it turned out **not** to be that hang's cause; that was the shared callback stack, #489. It changes nothing visible in the game, but it is a correctness fix on its own.
10
+
11
+ lv2 returns `EBUSY` from `sys_mutex_destroy` when the mutex is locked, or when a thread is blocked acquiring it. Ours destroyed the host mutex anyway, under the blocked thread. The next `sys_mutex_create` in the same slot then initialised a new mutex over it: every other thread used the new one, and the blocked thread waited on the dead one for good.
12
+
13
+ ## What
14
+
15
+ - `sys_mutex_info.waiters` counts the threads blocked acquiring the mutex:
16
+ - around the acquire in `sys_mutex_lock`, on both hosts; both timeout returns give the count back;
17
+ - around the re-lock in `sys_cond_wait`.
18
+ - `sys_mutex_destroy` returns `EBUSY` while the lock count or `waiters` is nonzero, and logs the first 16 refusals with the owner, count and waiters.
19
+
20
+ This merges cleanly with #474 (MUTEX_WATCH), in either order. I checked the merge locally, and the four sync_stress ctests below pass on it.
21
+
22
+ ## Tests
23
+
24
+ - New `tests/sync_stress/test_mutex_destroy.c` (ctest `mutex_destroy`, built on every host; off Windows it uses the Win32 shim like `sync_stress`). It checks that destroy returns `EBUSY`:
25
+ 1. while the mutex is held;
26
+ 2. while it is held and another thread is blocked on it. That thread then gets the mutex once it is released;
27
+ 3. while a thread is blocked on the host lock with the guest lock count at 0. That is the moment a released mutex passes to a waiter;
28
+ 4. while a `sys_cond_wait` re-lock is blocked, from the signaler that still holds the mutex.
29
+
30
+ It also checks that a timed lock that times out gives its count back, and that once the mutex is free destroy returns `CELL_OK` and a second destroy returns `ESRCH`.
31
+
32
+ Without the check in `sys_mutex_destroy`, cases 1 to 3 get `CELL_OK` and the checks after them fail too.
33
+ - `sync_stress` passes. macOS; the Windows build is clang-cl, which has the `__atomic` builtins (`sys_rwlock.c` already uses them).
34
+
35
+ ## Task
36
+
37
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-490/solution/patch.diff ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/runtime/syscalls/sys_cond.c b/runtime/syscalls/sys_cond.c
2
+ index 45235ea6..e1311a27 100644
3
+ --- a/runtime/syscalls/sys_cond.c
4
+ +++ b/runtime/syscalls/sys_cond.c
5
+ @@ -195,7 +195,10 @@ int64_t sys_cond_wait(ppu_context* ctx)
6
+ while (*link != &waiter) link = &(*link)->next;
7
+ *link = waiter.next;
8
+ cond_unlock(c);
9
+ + /* Re-acquiring counts as waiting on the mutex (sys_mutex_destroy). */
10
+ + __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
11
+ for (int i = 0; i < depth; ++i) guest_lock(m);
12
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
13
+ m->owner_tid = ctx->thread_id;
14
+ m->lock_count = depth;
15
+ return result;
16
+ diff --git a/runtime/syscalls/sys_mutex.c b/runtime/syscalls/sys_mutex.c
17
+ index 2e760ea5..76f4c0d4 100644
18
+ --- a/runtime/syscalls/sys_mutex.c
19
+ +++ b/runtime/syscalls/sys_mutex.c
20
+ @@ -159,6 +159,22 @@ int64_t sys_mutex_destroy(ppu_context* ctx)
21
+ return (int64_t)(int32_t)CELL_ESRCH;
22
+ }
23
+
24
+ + /* lv2 refuses to destroy a mutex that is held or has waiters (EBUSY).
25
+ + * Destroying it anyway freed the host mutex under a thread blocked on it,
26
+ + * and the next sys_mutex_create in the same slot initialised a new one
27
+ + * over it: everyone else then used the new mutex and the blocked thread
28
+ + * waited on the dead one for good. */
29
+ + if (m->lock_count > 0 || __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST) > 0) {
30
+ + static int n = 0;
31
+ + if (n++ < 16)
32
+ + fprintf(stderr, "[mutex] destroy of mutex %u '%.8s' refused: owner tid=%llu "
33
+ + "count=%d waiters=%d (EBUSY)\n", mutex_id, m->name,
34
+ + (unsigned long long)m->owner_tid, m->lock_count,
35
+ + __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST));
36
+ + mtx_table_unlock();
37
+ + return (int64_t)(int32_t)CELL_EBUSY;
38
+ + }
39
+ +
40
+ #ifdef _WIN32
41
+ DeleteCriticalSection(&m->cs);
42
+ if (m->wait_handle) CloseHandle(m->wait_handle);
43
+ @@ -195,6 +211,7 @@ int64_t sys_mutex_lock(ppu_context* ctx)
44
+ return (int64_t)(int32_t)CELL_EDEADLK;
45
+ }
46
+
47
+ + __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); /* see sys_mutex_destroy */
48
+ #ifdef _WIN32
49
+ if (timeout_us == 0) {
50
+ /* Infinite wait */
51
+ @@ -210,6 +227,7 @@ int64_t sys_mutex_lock(ppu_context* ctx)
52
+ int64_t deadline = lv2_usec_deadline(timeout_us);
53
+ while (!TryEnterCriticalSection(&m->cs)) {
54
+ if (lv2_deadline_passed(deadline)) {
55
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
56
+ return (int64_t)(int32_t)CELL_ETIMEDOUT;
57
+ }
58
+ if (timeout_us < 1000) SwitchToThread();
59
+ @@ -230,10 +248,12 @@ int64_t sys_mutex_lock(ppu_context* ctx)
60
+ }
61
+ int rc = pthread_mutex_timedlock(&m->mtx, &ts);
62
+ if (rc == ETIMEDOUT) {
63
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
64
+ return (int64_t)(int32_t)CELL_ETIMEDOUT;
65
+ }
66
+ }
67
+ #endif
68
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
69
+
70
+ m->owner_tid = caller_tid;
71
+ m->lock_count++;
72
+ diff --git a/runtime/syscalls/sys_mutex.h b/runtime/syscalls/sys_mutex.h
73
+ index bfe849d8..08b20e46 100644
74
+ --- a/runtime/syscalls/sys_mutex.h
75
+ +++ b/runtime/syscalls/sys_mutex.h
76
+ @@ -62,6 +62,7 @@ typedef struct sys_mutex_info {
77
+ int recursive;
78
+ uint64_t owner_tid; /* thread_id of current owner (for recursive/error checking) */
79
+ int lock_count; /* recursive lock count */
80
+ + volatile int waiters; /* threads blocked acquiring it (sys_mutex_lock, cond re-lock) */
81
+
82
+ #ifdef _WIN32
83
+ CRITICAL_SECTION cs;
84
+ diff --git a/tests/sync_stress/CMakeLists.txt b/tests/sync_stress/CMakeLists.txt
85
+ index 52fb8216..df1ccc35 100644
86
+ --- a/tests/sync_stress/CMakeLists.txt
87
+ +++ b/tests/sync_stress/CMakeLists.txt
88
+ @@ -89,6 +89,27 @@ set_tests_properties(sync_stress PROPERTIES
89
+ TIMEOUT 120
90
+ )
91
+
92
+ +# sys_mutex_destroy: EBUSY while the mutex is held or a thread is blocked
93
+ +# acquiring it. Win32 host threads, through the shim off Windows.
94
+ +add_executable(test_mutex_destroy
95
+ + test_mutex_destroy.c test_shims.c
96
+ + "${RUNTIME_SYNC_DIR}/sys_mutex.c"
97
+ + "${RUNTIME_SYNC_DIR}/sys_cond.c")
98
+ +if(NOT WIN32)
99
+ + target_sources(test_mutex_destroy PRIVATE
100
+ + "${PS3RECOMP_TREE_ROOT}/runtime/platform/win32_compat.c")
101
+ + find_package(Threads REQUIRED)
102
+ + target_link_libraries(test_mutex_destroy PRIVATE Threads::Threads)
103
+ +endif()
104
+ +target_include_directories(test_mutex_destroy PRIVATE
105
+ + "${PS3RECOMP_TREE_ROOT}" "${PS3RECOMP_TREE_ROOT}/include"
106
+ + "${RUNTIME_SYNC_DIR}" "${PS3RECOMP_TREE_ROOT}/runtime")
107
+ +if(MSVC)
108
+ + target_compile_definitions(test_mutex_destroy PRIVATE _CRT_SECURE_NO_WARNINGS)
109
+ +endif()
110
+ +add_test(NAME mutex_destroy COMMAND test_mutex_destroy)
111
+ +set_tests_properties(mutex_destroy PROPERTIES LABELS "runtime;sync" TIMEOUT 20)
112
+ +
113
+ # The focused condition tests use Win32 host threads. POSIX execution also
114
+ # needs the waitable-handle implementation supplied by the native host port.
115
+ if(WIN32)
116
+ diff --git a/tests/sync_stress/test_mutex_destroy.c b/tests/sync_stress/test_mutex_destroy.c
117
+ new file mode 100644
118
+ index 00000000..ed1f219d
119
+ --- /dev/null
120
+ +++ b/tests/sync_stress/test_mutex_destroy.c
121
+ @@ -0,0 +1,114 @@
122
+ +/* sys_mutex_destroy refuses a mutex that is held or has a thread blocked
123
+ + * acquiring it, with EBUSY, as lv2 does. It used to destroy the host mutex
124
+ + * under the blocked thread; the next sys_mutex_create in that slot then
125
+ + * initialised a new mutex over it, and the blocked thread waited on the dead
126
+ + * one for good.
127
+ + *
128
+ + * The blocked acquires are counted in sys_mutex_info.waiters: sys_mutex_lock
129
+ + * (both timeouts give the count back) and sys_cond_wait's re-lock. */
130
+ +#include "runtime/platform/win32_compat.h"
131
+ +#include "runtime/syscalls/sys_cond.h"
132
+ +#include <stdio.h>
133
+ +#include <stdlib.h>
134
+ +#include <string.h>
135
+ +
136
+ +uint8_t* vm_base;
137
+ +static uint32_t mid, cid;
138
+ +static int failures;
139
+ +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); failures++; } } while (0)
140
+ +static int32_t call(int64_t (*f)(ppu_context*), ppu_context* c, uint64_t a, uint64_t b, uint64_t d) {
141
+ + c->gpr[3]=a; c->gpr[4]=b; c->gpr[5]=d;
142
+ + return (int32_t)f(c);
143
+ +}
144
+ +static uint32_t be_read(unsigned off) {
145
+ + uint8_t* p=vm_base+off;
146
+ + return ((uint32_t)p[0]<<24)|((uint32_t)p[1]<<16)|((uint32_t)p[2]<<8)|p[3];
147
+ +}
148
+ +static int waiters(void) { return __atomic_load_n(&g_sys_mutexes[mid-1].waiters, __ATOMIC_SEQ_CST); }
149
+ +static int wait_waiters(int want) {
150
+ + for (int i=0;i<2000 && waiters()!=want;i++) Sleep(1);
151
+ + return waiters()==want;
152
+ +}
153
+ +/* Thread 2: lock (blocking, or with the timeout in raw), record, unlock. */
154
+ +static volatile int32_t s_rc=-1;
155
+ +static DWORD WINAPI locker(void* raw) {
156
+ + ppu_context c={0}; c.thread_id=2;
157
+ + s_rc=call(sys_mutex_lock,&c,mid,(uint64_t)(uintptr_t)raw,0);
158
+ + if (s_rc==CELL_OK) call(sys_mutex_unlock,&c,mid,0,0);
159
+ + return 0;
160
+ +}
161
+ +static DWORD WINAPI signaler(void* raw) {
162
+ + (void)raw;
163
+ + ppu_context c={0}; c.thread_id=3;
164
+ + while (call(sys_mutex_lock,&c,mid,0,0)!=CELL_OK) Sleep(1);
165
+ + call(sys_cond_signal,&c,cid,0,0);
166
+ + /* Hold it: the waiter is now blocked re-acquiring. */
167
+ + CHECK(wait_waiters(1));
168
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
169
+ + call(sys_mutex_unlock,&c,mid,0,0);
170
+ + return 0;
171
+ +}
172
+ +int main(void) {
173
+ + vm_base=calloc(1,65536);
174
+ + ppu_context c={0}; c.thread_id=1;
175
+ + vm_base[0x103]=1; vm_base[0x107]=0x20; /* FIFO, not recursive */
176
+ + CHECK(call(sys_mutex_create,&c,0x200,0x100,0)==CELL_OK);
177
+ + mid=be_read(0x200);
178
+ +
179
+ + /* 1. Held: EBUSY. */
180
+ + CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK);
181
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
182
+ +
183
+ + /* 2. Held, with a thread blocked on it: EBUSY, and the blocked thread
184
+ + * gets the mutex once it is released. */
185
+ + HANDLE h=CreateThread(NULL,0,locker,NULL,0,NULL);
186
+ + CHECK(wait_waiters(1));
187
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
188
+ + CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK);
189
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
190
+ + CHECK(s_rc==CELL_OK && waiters()==0);
191
+ +
192
+ + /* 3. A timed lock that times out gives its count back. */
193
+ + CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK);
194
+ + s_rc=-1;
195
+ + h=CreateThread(NULL,0,locker,(void*)(uintptr_t)20000,0,NULL);
196
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
197
+ + CHECK(s_rc==(int32_t)CELL_ETIMEDOUT && waiters()==0);
198
+ + CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK);
199
+ +
200
+ + /* 4. A thread blocked on the host lock while the guest count is 0 (the
201
+ + * window in which a released mutex passes to a waiter): EBUSY. */
202
+ + sys_mutex_info* m=&g_sys_mutexes[mid-1];
203
+ +#ifdef _WIN32
204
+ + EnterCriticalSection(&m->cs);
205
+ +#else
206
+ + pthread_mutex_lock(&m->mtx);
207
+ +#endif
208
+ + h=CreateThread(NULL,0,locker,NULL,0,NULL);
209
+ + CHECK(wait_waiters(1) && m->lock_count==0);
210
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
211
+ +#ifdef _WIN32
212
+ + LeaveCriticalSection(&m->cs);
213
+ +#else
214
+ + pthread_mutex_unlock(&m->mtx);
215
+ +#endif
216
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
217
+ +
218
+ + /* 5. sys_cond_wait's re-lock counts as a waiter. */
219
+ + CHECK(call(sys_cond_create,&c,0x204,mid,0)==CELL_OK);
220
+ + cid=be_read(0x204);
221
+ + CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK);
222
+ + h=CreateThread(NULL,0,signaler,NULL,0,NULL);
223
+ + CHECK(call(sys_cond_wait,&c,cid,0,0)==CELL_OK);
224
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
225
+ + CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK);
226
+ + CHECK(call(sys_cond_destroy,&c,cid,0,0)==CELL_OK);
227
+ +
228
+ + /* 6. Free and uncontended: destroyed. */
229
+ + CHECK(waiters()==0);
230
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==CELL_OK);
231
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_ESRCH);
232
+ +
233
+ + printf("mutex destroy: %s\n",failures?"FAIL":"PASS");
234
+ + return failures?1:0;
235
+ +}
tasks/sp00nznet__ps3recomp-490/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/sp00nznet__ps3recomp-490/task.toml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/sp00nznet__ps3recomp-490"
5
+ description = "sys_mutex: destroy refuses a mutex that is held or has waiters (EBUSY)"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "ps3recomp",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "sp00nznet/ps3recomp"
19
+ ref = "a6d76c895f77eb30b90a806c830544e61821b77f"
20
+ reference = "https://github.com/sp00nznet/ps3recomp/pull/490"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:59.863839+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:3bd934c95535d0d165fbde05729492d959cc9cbbb4f0c97384bc4fbe3c48db3f"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-26T15:32:55Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "runtime/syscalls/sys_cond.c",
34
+ "runtime/syscalls/sys_mutex.c",
35
+ "runtime/syscalls/sys_mutex.h",
36
+ "tests/sync_stress/CMakeLists.txt",
37
+ "tests/sync_stress/test_mutex_destroy.c",
38
+ ]
39
+ bootstrap_image = "python:3.12-slim"
40
+
41
+ [metadata.repo2env.reward_calibration]
42
+ baseline_reward = 0.0
43
+ loc_changed = 159
44
+ difficulty = "large"
45
+
46
+ [metadata.repo2env.evaluation]
47
+ schema_version = "1"
48
+ status = "unverified"
49
+ stage = "generation"
50
+ reason_codes = [
51
+ "validation_not_run",
52
+ ]
53
+ detail = "Generated task; validation has not been established."
54
+ provenance = "unknown"
55
+ evidence = []
56
+
57
+ [metadata.repo2env.reproducibility]
58
+ mode = "inline_dockerfile"
59
+ image_ref = "python:3.12-slim"
60
+ image_tag = "python:3.12-slim"
61
+ image_visibility = "public"
62
+ pushed_at = "2026-11-16T16:20:03.116999+00:00"
63
+ pushed_by = "scalingX"
64
+ inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1"
65
+ inline_recipe_lines = 37
66
+ inline_recipe_source = "user_dockerfile"
67
+
68
+ [agent]
69
+ timeout_sec = 1800.0
70
+
71
+ [verifier]
72
+ timeout_sec = 300.0
tasks/sp00nznet__ps3recomp-490/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/sp00nznet__ps3recomp-490/tests/instruction.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** sys_mutex: destroy refuses a mutex that is held or has waiters (EBUSY)
4
+
5
+ ## Description
6
+
7
+ ## Why
8
+
9
+ This fix comes from the Resistance: Fall of Man (BCUS98107) native port. I found it while chasing the hang after Resistance's level-1 intro movie. To be clear, it turned out **not** to be that hang's cause; that was the shared callback stack, #489. It changes nothing visible in the game, but it is a correctness fix on its own.
10
+
11
+ lv2 returns `EBUSY` from `sys_mutex_destroy` when the mutex is locked, or when a thread is blocked acquiring it. Ours destroyed the host mutex anyway, under the blocked thread. The next `sys_mutex_create` in the same slot then initialised a new mutex over it: every other thread used the new one, and the blocked thread waited on the dead one for good.
12
+
13
+ ## What
14
+
15
+ - `sys_mutex_info.waiters` counts the threads blocked acquiring the mutex:
16
+ - around the acquire in `sys_mutex_lock`, on both hosts; both timeout returns give the count back;
17
+ - around the re-lock in `sys_cond_wait`.
18
+ - `sys_mutex_destroy` returns `EBUSY` while the lock count or `waiters` is nonzero, and logs the first 16 refusals with the owner, count and waiters.
19
+
20
+ This merges cleanly with #474 (MUTEX_WATCH), in either order. I checked the merge locally, and the four sync_stress ctests below pass on it.
21
+
22
+ ## Tests
23
+
24
+ - New `tests/sync_stress/test_mutex_destroy.c` (ctest `mutex_destroy`, built on every host; off Windows it uses the Win32 shim like `sync_stress`). It checks that destroy returns `EBUSY`:
25
+ 1. while the mutex is held;
26
+ 2. while it is held and another thread is blocked on it. That thread then gets the mutex once it is released;
27
+ 3. while a thread is blocked on the host lock with the guest lock count at 0. That is the moment a released mutex passes to a waiter;
28
+ 4. while a `sys_cond_wait` re-lock is blocked, from the signaler that still holds the mutex.
29
+
30
+ It also checks that a timed lock that times out gives its count back, and that once the mutex is free destroy returns `CELL_OK` and a second destroy returns `ESRCH`.
31
+
32
+ Without the check in `sys_mutex_destroy`, cases 1 to 3 get `CELL_OK` and the checks after them fail too.
33
+ - `sync_stress` passes. macOS; the Windows build is clang-cl, which has the `__atomic` builtins (`sys_rwlock.c` already uses them).
34
+
35
+ ## Task
36
+
37
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-490/tests/oracle.patch ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/runtime/syscalls/sys_cond.c b/runtime/syscalls/sys_cond.c
2
+ index 45235ea6..e1311a27 100644
3
+ --- a/runtime/syscalls/sys_cond.c
4
+ +++ b/runtime/syscalls/sys_cond.c
5
+ @@ -195,7 +195,10 @@ int64_t sys_cond_wait(ppu_context* ctx)
6
+ while (*link != &waiter) link = &(*link)->next;
7
+ *link = waiter.next;
8
+ cond_unlock(c);
9
+ + /* Re-acquiring counts as waiting on the mutex (sys_mutex_destroy). */
10
+ + __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
11
+ for (int i = 0; i < depth; ++i) guest_lock(m);
12
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
13
+ m->owner_tid = ctx->thread_id;
14
+ m->lock_count = depth;
15
+ return result;
16
+ diff --git a/runtime/syscalls/sys_mutex.c b/runtime/syscalls/sys_mutex.c
17
+ index 2e760ea5..76f4c0d4 100644
18
+ --- a/runtime/syscalls/sys_mutex.c
19
+ +++ b/runtime/syscalls/sys_mutex.c
20
+ @@ -159,6 +159,22 @@ int64_t sys_mutex_destroy(ppu_context* ctx)
21
+ return (int64_t)(int32_t)CELL_ESRCH;
22
+ }
23
+
24
+ + /* lv2 refuses to destroy a mutex that is held or has waiters (EBUSY).
25
+ + * Destroying it anyway freed the host mutex under a thread blocked on it,
26
+ + * and the next sys_mutex_create in the same slot initialised a new one
27
+ + * over it: everyone else then used the new mutex and the blocked thread
28
+ + * waited on the dead one for good. */
29
+ + if (m->lock_count > 0 || __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST) > 0) {
30
+ + static int n = 0;
31
+ + if (n++ < 16)
32
+ + fprintf(stderr, "[mutex] destroy of mutex %u '%.8s' refused: owner tid=%llu "
33
+ + "count=%d waiters=%d (EBUSY)\n", mutex_id, m->name,
34
+ + (unsigned long long)m->owner_tid, m->lock_count,
35
+ + __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST));
36
+ + mtx_table_unlock();
37
+ + return (int64_t)(int32_t)CELL_EBUSY;
38
+ + }
39
+ +
40
+ #ifdef _WIN32
41
+ DeleteCriticalSection(&m->cs);
42
+ if (m->wait_handle) CloseHandle(m->wait_handle);
43
+ @@ -195,6 +211,7 @@ int64_t sys_mutex_lock(ppu_context* ctx)
44
+ return (int64_t)(int32_t)CELL_EDEADLK;
45
+ }
46
+
47
+ + __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); /* see sys_mutex_destroy */
48
+ #ifdef _WIN32
49
+ if (timeout_us == 0) {
50
+ /* Infinite wait */
51
+ @@ -210,6 +227,7 @@ int64_t sys_mutex_lock(ppu_context* ctx)
52
+ int64_t deadline = lv2_usec_deadline(timeout_us);
53
+ while (!TryEnterCriticalSection(&m->cs)) {
54
+ if (lv2_deadline_passed(deadline)) {
55
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
56
+ return (int64_t)(int32_t)CELL_ETIMEDOUT;
57
+ }
58
+ if (timeout_us < 1000) SwitchToThread();
59
+ @@ -230,10 +248,12 @@ int64_t sys_mutex_lock(ppu_context* ctx)
60
+ }
61
+ int rc = pthread_mutex_timedlock(&m->mtx, &ts);
62
+ if (rc == ETIMEDOUT) {
63
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
64
+ return (int64_t)(int32_t)CELL_ETIMEDOUT;
65
+ }
66
+ }
67
+ #endif
68
+ + __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST);
69
+
70
+ m->owner_tid = caller_tid;
71
+ m->lock_count++;
72
+ diff --git a/runtime/syscalls/sys_mutex.h b/runtime/syscalls/sys_mutex.h
73
+ index bfe849d8..08b20e46 100644
74
+ --- a/runtime/syscalls/sys_mutex.h
75
+ +++ b/runtime/syscalls/sys_mutex.h
76
+ @@ -62,6 +62,7 @@ typedef struct sys_mutex_info {
77
+ int recursive;
78
+ uint64_t owner_tid; /* thread_id of current owner (for recursive/error checking) */
79
+ int lock_count; /* recursive lock count */
80
+ + volatile int waiters; /* threads blocked acquiring it (sys_mutex_lock, cond re-lock) */
81
+
82
+ #ifdef _WIN32
83
+ CRITICAL_SECTION cs;
84
+ diff --git a/tests/sync_stress/CMakeLists.txt b/tests/sync_stress/CMakeLists.txt
85
+ index 52fb8216..df1ccc35 100644
86
+ --- a/tests/sync_stress/CMakeLists.txt
87
+ +++ b/tests/sync_stress/CMakeLists.txt
88
+ @@ -89,6 +89,27 @@ set_tests_properties(sync_stress PROPERTIES
89
+ TIMEOUT 120
90
+ )
91
+
92
+ +# sys_mutex_destroy: EBUSY while the mutex is held or a thread is blocked
93
+ +# acquiring it. Win32 host threads, through the shim off Windows.
94
+ +add_executable(test_mutex_destroy
95
+ + test_mutex_destroy.c test_shims.c
96
+ + "${RUNTIME_SYNC_DIR}/sys_mutex.c"
97
+ + "${RUNTIME_SYNC_DIR}/sys_cond.c")
98
+ +if(NOT WIN32)
99
+ + target_sources(test_mutex_destroy PRIVATE
100
+ + "${PS3RECOMP_TREE_ROOT}/runtime/platform/win32_compat.c")
101
+ + find_package(Threads REQUIRED)
102
+ + target_link_libraries(test_mutex_destroy PRIVATE Threads::Threads)
103
+ +endif()
104
+ +target_include_directories(test_mutex_destroy PRIVATE
105
+ + "${PS3RECOMP_TREE_ROOT}" "${PS3RECOMP_TREE_ROOT}/include"
106
+ + "${RUNTIME_SYNC_DIR}" "${PS3RECOMP_TREE_ROOT}/runtime")
107
+ +if(MSVC)
108
+ + target_compile_definitions(test_mutex_destroy PRIVATE _CRT_SECURE_NO_WARNINGS)
109
+ +endif()
110
+ +add_test(NAME mutex_destroy COMMAND test_mutex_destroy)
111
+ +set_tests_properties(mutex_destroy PROPERTIES LABELS "runtime;sync" TIMEOUT 20)
112
+ +
113
+ # The focused condition tests use Win32 host threads. POSIX execution also
114
+ # needs the waitable-handle implementation supplied by the native host port.
115
+ if(WIN32)
116
+ diff --git a/tests/sync_stress/test_mutex_destroy.c b/tests/sync_stress/test_mutex_destroy.c
117
+ new file mode 100644
118
+ index 00000000..ed1f219d
119
+ --- /dev/null
120
+ +++ b/tests/sync_stress/test_mutex_destroy.c
121
+ @@ -0,0 +1,114 @@
122
+ +/* sys_mutex_destroy refuses a mutex that is held or has a thread blocked
123
+ + * acquiring it, with EBUSY, as lv2 does. It used to destroy the host mutex
124
+ + * under the blocked thread; the next sys_mutex_create in that slot then
125
+ + * initialised a new mutex over it, and the blocked thread waited on the dead
126
+ + * one for good.
127
+ + *
128
+ + * The blocked acquires are counted in sys_mutex_info.waiters: sys_mutex_lock
129
+ + * (both timeouts give the count back) and sys_cond_wait's re-lock. */
130
+ +#include "runtime/platform/win32_compat.h"
131
+ +#include "runtime/syscalls/sys_cond.h"
132
+ +#include <stdio.h>
133
+ +#include <stdlib.h>
134
+ +#include <string.h>
135
+ +
136
+ +uint8_t* vm_base;
137
+ +static uint32_t mid, cid;
138
+ +static int failures;
139
+ +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); failures++; } } while (0)
140
+ +static int32_t call(int64_t (*f)(ppu_context*), ppu_context* c, uint64_t a, uint64_t b, uint64_t d) {
141
+ + c->gpr[3]=a; c->gpr[4]=b; c->gpr[5]=d;
142
+ + return (int32_t)f(c);
143
+ +}
144
+ +static uint32_t be_read(unsigned off) {
145
+ + uint8_t* p=vm_base+off;
146
+ + return ((uint32_t)p[0]<<24)|((uint32_t)p[1]<<16)|((uint32_t)p[2]<<8)|p[3];
147
+ +}
148
+ +static int waiters(void) { return __atomic_load_n(&g_sys_mutexes[mid-1].waiters, __ATOMIC_SEQ_CST); }
149
+ +static int wait_waiters(int want) {
150
+ + for (int i=0;i<2000 && waiters()!=want;i++) Sleep(1);
151
+ + return waiters()==want;
152
+ +}
153
+ +/* Thread 2: lock (blocking, or with the timeout in raw), record, unlock. */
154
+ +static volatile int32_t s_rc=-1;
155
+ +static DWORD WINAPI locker(void* raw) {
156
+ + ppu_context c={0}; c.thread_id=2;
157
+ + s_rc=call(sys_mutex_lock,&c,mid,(uint64_t)(uintptr_t)raw,0);
158
+ + if (s_rc==CELL_OK) call(sys_mutex_unlock,&c,mid,0,0);
159
+ + return 0;
160
+ +}
161
+ +static DWORD WINAPI signaler(void* raw) {
162
+ + (void)raw;
163
+ + ppu_context c={0}; c.thread_id=3;
164
+ + while (call(sys_mutex_lock,&c,mid,0,0)!=CELL_OK) Sleep(1);
165
+ + call(sys_cond_signal,&c,cid,0,0);
166
+ + /* Hold it: the waiter is now blocked re-acquiring. */
167
+ + CHECK(wait_waiters(1));
168
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
169
+ + call(sys_mutex_unlock,&c,mid,0,0);
170
+ + return 0;
171
+ +}
172
+ +int main(void) {
173
+ + vm_base=calloc(1,65536);
174
+ + ppu_context c={0}; c.thread_id=1;
175
+ + vm_base[0x103]=1; vm_base[0x107]=0x20; /* FIFO, not recursive */
176
+ + CHECK(call(sys_mutex_create,&c,0x200,0x100,0)==CELL_OK);
177
+ + mid=be_read(0x200);
178
+ +
179
+ + /* 1. Held: EBUSY. */
180
+ + CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK);
181
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
182
+ +
183
+ + /* 2. Held, with a thread blocked on it: EBUSY, and the blocked thread
184
+ + * gets the mutex once it is released. */
185
+ + HANDLE h=CreateThread(NULL,0,locker,NULL,0,NULL);
186
+ + CHECK(wait_waiters(1));
187
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
188
+ + CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK);
189
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
190
+ + CHECK(s_rc==CELL_OK && waiters()==0);
191
+ +
192
+ + /* 3. A timed lock that times out gives its count back. */
193
+ + CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK);
194
+ + s_rc=-1;
195
+ + h=CreateThread(NULL,0,locker,(void*)(uintptr_t)20000,0,NULL);
196
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
197
+ + CHECK(s_rc==(int32_t)CELL_ETIMEDOUT && waiters()==0);
198
+ + CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK);
199
+ +
200
+ + /* 4. A thread blocked on the host lock while the guest count is 0 (the
201
+ + * window in which a released mutex passes to a waiter): EBUSY. */
202
+ + sys_mutex_info* m=&g_sys_mutexes[mid-1];
203
+ +#ifdef _WIN32
204
+ + EnterCriticalSection(&m->cs);
205
+ +#else
206
+ + pthread_mutex_lock(&m->mtx);
207
+ +#endif
208
+ + h=CreateThread(NULL,0,locker,NULL,0,NULL);
209
+ + CHECK(wait_waiters(1) && m->lock_count==0);
210
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY);
211
+ +#ifdef _WIN32
212
+ + LeaveCriticalSection(&m->cs);
213
+ +#else
214
+ + pthread_mutex_unlock(&m->mtx);
215
+ +#endif
216
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
217
+ +
218
+ + /* 5. sys_cond_wait's re-lock counts as a waiter. */
219
+ + CHECK(call(sys_cond_create,&c,0x204,mid,0)==CELL_OK);
220
+ + cid=be_read(0x204);
221
+ + CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK);
222
+ + h=CreateThread(NULL,0,signaler,NULL,0,NULL);
223
+ + CHECK(call(sys_cond_wait,&c,cid,0,0)==CELL_OK);
224
+ + CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h);
225
+ + CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK);
226
+ + CHECK(call(sys_cond_destroy,&c,cid,0,0)==CELL_OK);
227
+ +
228
+ + /* 6. Free and uncontended: destroyed. */
229
+ + CHECK(waiters()==0);
230
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==CELL_OK);
231
+ + CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_ESRCH);
232
+ +
233
+ + printf("mutex destroy: %s\n",failures?"FAIL":"PASS");
234
+ + return failures?1:0;
235
+ +}
tasks/sp00nznet__ps3recomp-490/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/sp00nznet__ps3recomp-490/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/sp00nznet__ps3recomp-494/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/sp00nznet__ps3recomp-494/instruction.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** cellPad: load XInput at run time, do not import it
4
+
5
+ ## Description
6
+
7
+ ## Why
8
+
9
+ On Windows, `ps3recomp_runtime` links `xinput`. With MinGW that is `XINPUT1_3.dll`. Only the DirectX June 2010 redistributable installs that DLL. Stock Windows 10 and 11 do not have it. They ship `XInput1_4.dll` and `XInput9_1_0.dll`.
10
+
11
+ So an exe built on this runtime does not start on a clean Windows install. The loader fails before `main` with `0xC0000135` (`STATUS_DLL_NOT_FOUND`). I found this with Killzone 3 on a clean Windows 10 VM.
12
+
13
+ ## Change
14
+
15
+ - `CMakeLists.txt`: drop `xinput` from the Windows link libraries.
16
+ - `libs/input/cellPad.c`:
17
+ - Remove `#pragma comment(lib, "xinput.lib")` (MinGW ignores it). Keep `<xinput.h>` for the types only.
18
+ - New `pad_xinput_load()`. It tries `XInput1_4.dll`, `XInput1_3.dll`, then `XInput9_1_0.dll`. It uses `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_SYSTEM32`, so nothing is loaded from the exe folder, the working directory or `PATH`.
19
+ - It resolves `XInputGetState` and `XInputSetState` with `GetProcAddress`. These are the only two XInput calls the file makes, and all three DLLs export both. A DLL without both is skipped.
20
+ - `pad_init_backend()` calls it once at `cellPadInit`. The DLL stays loaded until exit.
21
+ - If no DLL loads, every slot reads as unplugged. The keyboard fallback on port 0 still works. Rumble does nothing.
22
+ - It prints one line: `[cellPad] XInput from <dll>`, or a "no XInput DLL" line.
23
+
24
+ Linux, macOS and the SDL2 backend are not touched.
25
+
26
+ ## Tests
27
+
28
+ Against master `a6d76c8`:
29
+
30
+ - `git apply --check` and `patch -p1 --dry-run` both apply the patch cleanly (one `+++` header per file).
31
+ - Linux host build, `cmake -G Ninja -DCMAKE_BUILD_TYPE=Release` and `--target ps3recomp_host`, with SDL2: gcc 16.2 and clang 19.1 both build (160/160).
32
+ - `libs/input/tests/test_pad_rumble.c`, built as `linux.yml` builds it: `test_pad_rumble: ok` on gcc and clang, before and after.
33
+ - Windows cross build with mingw-w64 gcc 16.2 and the toolkit's CMake: `cellPad.c` compiles; `-Wall -Wextra` gave 1 warning before (the `#pragma comment`, which MinGW ignores) and 0 after.
34
+ - The `windows.yml` clang-cl build was not run here. Please let CI run it.
35
+
36
+ ## Evidence
37
+
38
+ The start-up failure, on a clean Windows 10 VM with no DirectX redistributable, in a Killzone 3 exe built on this runtime with MinGW:
39
+
40
+ - Before: the exe does not start, exit code `0xC0000135` (`XINPUT1_3.dll` not found).
41
+ - After: it starts and runs.
42
+
43
+ That exe reads pads through SDL, so this run shows that the start-up failure is gone. It does not exercise the new XInput loader. I have not run a pad through the XInput backend after the change.
44
+
45
+ PE imports of a probe exe built from the toolkit's `cellPad.c.obj` (`x86_64-w64-mingw32-objdump -p`, `DLL Name` lines):
46
+
47
+ ```
48
+ before after
49
+ KERNEL32.dll KERNEL32.dll
50
+ msvcrt.dll msvcrt.dll
51
+ USER32.dll USER32.dll
52
+ XINPUT1_3.dll
53
+ ```
54
+
55
+ Import entries that mention XInput or the loader:
56
+
57
+ ```
58
+ before: GetProcAddress; XINPUT1_3.dll: XInputGetState, XInputSetState
59
+ after: FreeLibrary, GetProcAddress, LoadLibraryExW (no XInput import)
60
+ ```
61
+
62
+ ## Overlap
63
+
64
+ - #472 (reopen a controller that is switched off and on again) and #466: each applies cleanly together with this change, in either order.
65
+ - #447 (Folklore line) reworks `cellPad.c` and keeps the `xinput.lib` pragma, so a textual conflict is likely. Whichever lands second can rebase; I can do that rebase.
66
+
67
+ ## Task
68
+
69
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-494/solution/patch.diff ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/CMakeLists.txt b/CMakeLists.txt
2
+ index bdd2f85a..5d14c1b2 100644
3
+ --- a/CMakeLists.txt
4
+ +++ b/CMakeLists.txt
5
+ @@ -132,7 +132,6 @@ target_include_directories(ps3recomp_runtime PRIVATE
6
+ if(WIN32)
7
+ target_link_libraries(ps3recomp_runtime PRIVATE
8
+ ws2_32 # Winsock for network modules
9
+ - xinput # XInput for gamepad
10
+ ole32 # COM for WASAPI audio
11
+ bcrypt # BCryptGenRandom for SSL RNG
12
+ )
13
+ diff --git a/libs/input/cellPad.c b/libs/input/cellPad.c
14
+ index 7fa8cab9..0f3c9324 100644
15
+ --- a/libs/input/cellPad.c
16
+ +++ b/libs/input/cellPad.c
17
+ @@ -4,7 +4,8 @@
18
+ * Reads real gamepad input from the host and translates to PS3 pad format.
19
+ *
20
+ * Backend selection:
21
+ - * - Windows default: XInput (no extra dependencies)
22
+ + * - Windows default: XInput, loaded at run time from System32 (XInput1_4.dll,
23
+ + * XInput1_3.dll, XInput9_1_0.dll); no XInput DLL means no pads
24
+ * - Everywhere else / if PS3RECOMP_PAD_USE_SDL2 is defined: SDL2 GameController
25
+ *
26
+ * Define PS3RECOMP_PAD_USE_SDL2 to force SDL2 backend on Windows.
27
+ @@ -53,8 +54,11 @@ static double pad_clock(unsigned long long t0_ms)
28
+ #define WIN32_LEAN_AND_MEAN
29
+ #endif
30
+ #include <windows.h>
31
+ + /* Types only. The exe must not import an XInput DLL: MinGW's libxinput is
32
+ + * xinput1_3.dll, which only the DirectX June 2010 redistributable installs,
33
+ + * so on a stock Windows 10/11 the exe did not start (0xC0000135). The DLL is
34
+ + * loaded at run time instead, see pad_xinput_load(). */
35
+ #include <xinput.h>
36
+ - #pragma comment(lib, "xinput.lib")
37
+ #endif
38
+
39
+ #if PAD_BACKEND_SDL2
40
+ @@ -143,6 +147,39 @@ static void pad_rumble_levels(u8 small_on, u8 large, u16* lo, u16* hi)
41
+ #define PAD_STICK_DEADZONE 7849
42
+ #define PAD_TRIGGER_THRESHOLD 30
43
+
44
+ +/* XInput is resolved at run time. Only XInputGetState and XInputSetState are
45
+ + * called, and XInput9_1_0.dll exports both, so any of the three DLLs serves.
46
+ + * Loaded once, from System32 only (not the exe folder, the working directory
47
+ + * or PATH), and kept loaded until exit. No DLL, or one without the two entry
48
+ + * points, means every slot reads as unplugged. */
49
+ +typedef DWORD (WINAPI *pad_xi_get_state_fn)(DWORD, XINPUT_STATE*);
50
+ +typedef DWORD (WINAPI *pad_xi_set_state_fn)(DWORD, XINPUT_VIBRATION*);
51
+ +static pad_xi_get_state_fn p_xi_get_state;
52
+ +static pad_xi_set_state_fn p_xi_set_state;
53
+ +static int s_xi_tried;
54
+ +
55
+ +static int pad_xinput_load(void)
56
+ +{
57
+ + static const wchar_t* const names[] = { L"XInput1_4.dll", L"XInput1_3.dll", L"XInput9_1_0.dll" };
58
+ + if (s_xi_tried) return p_xi_get_state != NULL;
59
+ + s_xi_tried = 1;
60
+ + for (size_t k = 0; k < sizeof(names) / sizeof(names[0]); k++) {
61
+ + HMODULE m = LoadLibraryExW(names[k], NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
62
+ + pad_xi_get_state_fn g;
63
+ + pad_xi_set_state_fn st;
64
+ + if (!m) continue;
65
+ + g = (pad_xi_get_state_fn)(void (*)(void))GetProcAddress(m, "XInputGetState");
66
+ + st = (pad_xi_set_state_fn)(void (*)(void))GetProcAddress(m, "XInputSetState");
67
+ + if (!g || !st) { FreeLibrary(m); continue; }
68
+ + p_xi_get_state = g;
69
+ + p_xi_set_state = st;
70
+ + printf("[cellPad] XInput from %ls\n", names[k]);
71
+ + return 1;
72
+ + }
73
+ + printf("[cellPad] no XInput DLL (XInput1_4, XInput1_3, XInput9_1_0): no XInput pads\n");
74
+ + return 0;
75
+ +}
76
+ +
77
+ static u8 pad_xinput_stick_to_u8(short raw, short deadzone)
78
+ {
79
+ float normalized;
80
+ @@ -240,7 +277,8 @@ static void pad_poll_xinput(void)
81
+ XINPUT_STATE state;
82
+ memset(&state, 0, sizeof(state));
83
+
84
+ - DWORD result = XInputGetState((DWORD)i, &state);
85
+ + DWORD result = p_xi_get_state ? p_xi_get_state((DWORD)i, &state)
86
+ + : ERROR_DEVICE_NOT_CONNECTED;
87
+ if (result != ERROR_SUCCESS) {
88
+ s_host_state[i].connected = 0;
89
+ continue;
90
+ @@ -299,7 +337,8 @@ static void pad_poll_xinput(void)
91
+
92
+ static void pad_init_backend(void)
93
+ {
94
+ - /* XInput needs no explicit init */
95
+ + /* XInput needs no explicit init, only the run-time load of the DLL */
96
+ + pad_xinput_load();
97
+ }
98
+
99
+ static void pad_shutdown_backend(void)
100
+ @@ -1151,7 +1190,7 @@ s32 cellPadSetActDirect(u32 port_no, CellPadActParam* param)
101
+ XINPUT_VIBRATION vib;
102
+ vib.wLeftMotorSpeed = (WORD)lo;
103
+ vib.wRightMotorSpeed = (WORD)hi;
104
+ - XInputSetState((DWORD)port_no, &vib);
105
+ + if (p_xi_set_state) p_xi_set_state((DWORD)port_no, &vib);
106
+ }
107
+ #endif
108
+
tasks/sp00nznet__ps3recomp-494/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/sp00nznet__ps3recomp-494/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/sp00nznet__ps3recomp-494"
5
+ description = "cellPad: load XInput at run time, do not import it"
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "ps3recomp",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "sp00nznet/ps3recomp"
19
+ ref = "a6d76c895f77eb30b90a806c830544e61821b77f"
20
+ reference = "https://github.com/sp00nznet/ps3recomp/pull/494"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:59.826729+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:d092db26d28604c9aec44f95a4984acde163825341968f1da569c771f8044cf2"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-26T15:32:55Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "CMakeLists.txt",
34
+ "libs/input/cellPad.c",
35
+ ]
36
+ bootstrap_image = "python:3.12-slim"
37
+
38
+ [metadata.repo2env.reward_calibration]
39
+ baseline_reward = 0.0
40
+ loc_changed = 50
41
+ difficulty = "medium"
42
+
43
+ [metadata.repo2env.evaluation]
44
+ schema_version = "1"
45
+ status = "unverified"
46
+ stage = "generation"
47
+ reason_codes = [
48
+ "validation_not_run",
49
+ ]
50
+ detail = "Generated task; validation has not been established."
51
+ provenance = "unknown"
52
+ evidence = []
53
+
54
+ [metadata.repo2env.reproducibility]
55
+ mode = "inline_dockerfile"
56
+ image_ref = "python:3.12-slim"
57
+ image_tag = "python:3.12-slim"
58
+ image_visibility = "public"
59
+ pushed_at = "2026-11-16T16:20:03.117579+00:00"
60
+ pushed_by = "scalingX"
61
+ inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1"
62
+ inline_recipe_lines = 37
63
+ inline_recipe_source = "user_dockerfile"
64
+
65
+ [agent]
66
+ timeout_sec = 1800.0
67
+
68
+ [verifier]
69
+ timeout_sec = 300.0
tasks/sp00nznet__ps3recomp-494/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/sp00nznet__ps3recomp-494/tests/instruction.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** cellPad: load XInput at run time, do not import it
4
+
5
+ ## Description
6
+
7
+ ## Why
8
+
9
+ On Windows, `ps3recomp_runtime` links `xinput`. With MinGW that is `XINPUT1_3.dll`. Only the DirectX June 2010 redistributable installs that DLL. Stock Windows 10 and 11 do not have it. They ship `XInput1_4.dll` and `XInput9_1_0.dll`.
10
+
11
+ So an exe built on this runtime does not start on a clean Windows install. The loader fails before `main` with `0xC0000135` (`STATUS_DLL_NOT_FOUND`). I found this with Killzone 3 on a clean Windows 10 VM.
12
+
13
+ ## Change
14
+
15
+ - `CMakeLists.txt`: drop `xinput` from the Windows link libraries.
16
+ - `libs/input/cellPad.c`:
17
+ - Remove `#pragma comment(lib, "xinput.lib")` (MinGW ignores it). Keep `<xinput.h>` for the types only.
18
+ - New `pad_xinput_load()`. It tries `XInput1_4.dll`, `XInput1_3.dll`, then `XInput9_1_0.dll`. It uses `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_SYSTEM32`, so nothing is loaded from the exe folder, the working directory or `PATH`.
19
+ - It resolves `XInputGetState` and `XInputSetState` with `GetProcAddress`. These are the only two XInput calls the file makes, and all three DLLs export both. A DLL without both is skipped.
20
+ - `pad_init_backend()` calls it once at `cellPadInit`. The DLL stays loaded until exit.
21
+ - If no DLL loads, every slot reads as unplugged. The keyboard fallback on port 0 still works. Rumble does nothing.
22
+ - It prints one line: `[cellPad] XInput from <dll>`, or a "no XInput DLL" line.
23
+
24
+ Linux, macOS and the SDL2 backend are not touched.
25
+
26
+ ## Tests
27
+
28
+ Against master `a6d76c8`:
29
+
30
+ - `git apply --check` and `patch -p1 --dry-run` both apply the patch cleanly (one `+++` header per file).
31
+ - Linux host build, `cmake -G Ninja -DCMAKE_BUILD_TYPE=Release` and `--target ps3recomp_host`, with SDL2: gcc 16.2 and clang 19.1 both build (160/160).
32
+ - `libs/input/tests/test_pad_rumble.c`, built as `linux.yml` builds it: `test_pad_rumble: ok` on gcc and clang, before and after.
33
+ - Windows cross build with mingw-w64 gcc 16.2 and the toolkit's CMake: `cellPad.c` compiles; `-Wall -Wextra` gave 1 warning before (the `#pragma comment`, which MinGW ignores) and 0 after.
34
+ - The `windows.yml` clang-cl build was not run here. Please let CI run it.
35
+
36
+ ## Evidence
37
+
38
+ The start-up failure, on a clean Windows 10 VM with no DirectX redistributable, in a Killzone 3 exe built on this runtime with MinGW:
39
+
40
+ - Before: the exe does not start, exit code `0xC0000135` (`XINPUT1_3.dll` not found).
41
+ - After: it starts and runs.
42
+
43
+ That exe reads pads through SDL, so this run shows that the start-up failure is gone. It does not exercise the new XInput loader. I have not run a pad through the XInput backend after the change.
44
+
45
+ PE imports of a probe exe built from the toolkit's `cellPad.c.obj` (`x86_64-w64-mingw32-objdump -p`, `DLL Name` lines):
46
+
47
+ ```
48
+ before after
49
+ KERNEL32.dll KERNEL32.dll
50
+ msvcrt.dll msvcrt.dll
51
+ USER32.dll USER32.dll
52
+ XINPUT1_3.dll
53
+ ```
54
+
55
+ Import entries that mention XInput or the loader:
56
+
57
+ ```
58
+ before: GetProcAddress; XINPUT1_3.dll: XInputGetState, XInputSetState
59
+ after: FreeLibrary, GetProcAddress, LoadLibraryExW (no XInput import)
60
+ ```
61
+
62
+ ## Overlap
63
+
64
+ - #472 (reopen a controller that is switched off and on again) and #466: each applies cleanly together with this change, in either order.
65
+ - #447 (Folklore line) reworks `cellPad.c` and keeps the `xinput.lib` pragma, so a textual conflict is likely. Whichever lands second can rebase; I can do that rebase.
66
+
67
+ ## Task
68
+
69
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d76c895f77`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/sp00nznet__ps3recomp-494/tests/oracle.patch ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/CMakeLists.txt b/CMakeLists.txt
2
+ index bdd2f85a..5d14c1b2 100644
3
+ --- a/CMakeLists.txt
4
+ +++ b/CMakeLists.txt
5
+ @@ -132,7 +132,6 @@ target_include_directories(ps3recomp_runtime PRIVATE
6
+ if(WIN32)
7
+ target_link_libraries(ps3recomp_runtime PRIVATE
8
+ ws2_32 # Winsock for network modules
9
+ - xinput # XInput for gamepad
10
+ ole32 # COM for WASAPI audio
11
+ bcrypt # BCryptGenRandom for SSL RNG
12
+ )
13
+ diff --git a/libs/input/cellPad.c b/libs/input/cellPad.c
14
+ index 7fa8cab9..0f3c9324 100644
15
+ --- a/libs/input/cellPad.c
16
+ +++ b/libs/input/cellPad.c
17
+ @@ -4,7 +4,8 @@
18
+ * Reads real gamepad input from the host and translates to PS3 pad format.
19
+ *
20
+ * Backend selection:
21
+ - * - Windows default: XInput (no extra dependencies)
22
+ + * - Windows default: XInput, loaded at run time from System32 (XInput1_4.dll,
23
+ + * XInput1_3.dll, XInput9_1_0.dll); no XInput DLL means no pads
24
+ * - Everywhere else / if PS3RECOMP_PAD_USE_SDL2 is defined: SDL2 GameController
25
+ *
26
+ * Define PS3RECOMP_PAD_USE_SDL2 to force SDL2 backend on Windows.
27
+ @@ -53,8 +54,11 @@ static double pad_clock(unsigned long long t0_ms)
28
+ #define WIN32_LEAN_AND_MEAN
29
+ #endif
30
+ #include <windows.h>
31
+ + /* Types only. The exe must not import an XInput DLL: MinGW's libxinput is
32
+ + * xinput1_3.dll, which only the DirectX June 2010 redistributable installs,
33
+ + * so on a stock Windows 10/11 the exe did not start (0xC0000135). The DLL is
34
+ + * loaded at run time instead, see pad_xinput_load(). */
35
+ #include <xinput.h>
36
+ - #pragma comment(lib, "xinput.lib")
37
+ #endif
38
+
39
+ #if PAD_BACKEND_SDL2
40
+ @@ -143,6 +147,39 @@ static void pad_rumble_levels(u8 small_on, u8 large, u16* lo, u16* hi)
41
+ #define PAD_STICK_DEADZONE 7849
42
+ #define PAD_TRIGGER_THRESHOLD 30
43
+
44
+ +/* XInput is resolved at run time. Only XInputGetState and XInputSetState are
45
+ + * called, and XInput9_1_0.dll exports both, so any of the three DLLs serves.
46
+ + * Loaded once, from System32 only (not the exe folder, the working directory
47
+ + * or PATH), and kept loaded until exit. No DLL, or one without the two entry
48
+ + * points, means every slot reads as unplugged. */
49
+ +typedef DWORD (WINAPI *pad_xi_get_state_fn)(DWORD, XINPUT_STATE*);
50
+ +typedef DWORD (WINAPI *pad_xi_set_state_fn)(DWORD, XINPUT_VIBRATION*);
51
+ +static pad_xi_get_state_fn p_xi_get_state;
52
+ +static pad_xi_set_state_fn p_xi_set_state;
53
+ +static int s_xi_tried;
54
+ +
55
+ +static int pad_xinput_load(void)
56
+ +{
57
+ + static const wchar_t* const names[] = { L"XInput1_4.dll", L"XInput1_3.dll", L"XInput9_1_0.dll" };
58
+ + if (s_xi_tried) return p_xi_get_state != NULL;
59
+ + s_xi_tried = 1;
60
+ + for (size_t k = 0; k < sizeof(names) / sizeof(names[0]); k++) {
61
+ + HMODULE m = LoadLibraryExW(names[k], NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
62
+ + pad_xi_get_state_fn g;
63
+ + pad_xi_set_state_fn st;
64
+ + if (!m) continue;
65
+ + g = (pad_xi_get_state_fn)(void (*)(void))GetProcAddress(m, "XInputGetState");
66
+ + st = (pad_xi_set_state_fn)(void (*)(void))GetProcAddress(m, "XInputSetState");
67
+ + if (!g || !st) { FreeLibrary(m); continue; }
68
+ + p_xi_get_state = g;
69
+ + p_xi_set_state = st;
70
+ + printf("[cellPad] XInput from %ls\n", names[k]);
71
+ + return 1;
72
+ + }
73
+ + printf("[cellPad] no XInput DLL (XInput1_4, XInput1_3, XInput9_1_0): no XInput pads\n");
74
+ + return 0;
75
+ +}
76
+ +
77
+ static u8 pad_xinput_stick_to_u8(short raw, short deadzone)
78
+ {
79
+ float normalized;
80
+ @@ -240,7 +277,8 @@ static void pad_poll_xinput(void)
81
+ XINPUT_STATE state;
82
+ memset(&state, 0, sizeof(state));
83
+
84
+ - DWORD result = XInputGetState((DWORD)i, &state);
85
+ + DWORD result = p_xi_get_state ? p_xi_get_state((DWORD)i, &state)
86
+ + : ERROR_DEVICE_NOT_CONNECTED;
87
+ if (result != ERROR_SUCCESS) {
88
+ s_host_state[i].connected = 0;
89
+ continue;
90
+ @@ -299,7 +337,8 @@ static void pad_poll_xinput(void)
91
+
92
+ static void pad_init_backend(void)
93
+ {
94
+ - /* XInput needs no explicit init */
95
+ + /* XInput needs no explicit init, only the run-time load of the DLL */
96
+ + pad_xinput_load();
97
+ }
98
+
99
+ static void pad_shutdown_backend(void)
100
+ @@ -1151,7 +1190,7 @@ s32 cellPadSetActDirect(u32 port_no, CellPadActParam* param)
101
+ XINPUT_VIBRATION vib;
102
+ vib.wLeftMotorSpeed = (WORD)lo;
103
+ vib.wRightMotorSpeed = (WORD)hi;
104
+ - XInputSetState((DWORD)port_no, &vib);
105
+ + if (p_xi_set_state) p_xi_set_state((DWORD)port_no, &vib);
106
+ }
107
+ #endif
108
+